Spring Social + Spring Security HTTPS/HTTP - spring

How can I make the remember me cookie and session accessible through http when requesting a facebook login from either http or https with spring social. Currently if a user logs in through https the cookie is not readable through http pages (no user logged in). I am using use-secure-cookie="false" but that doesn't help.
<s:remember-me key="mykey" services-ref="rememberMeServices" use-secure-cookie="false"/>
<bean id="rememberMeServices" class="org.springframework.security.web.authentication.rememberme.PersistentTokenBasedRememberMeServices">
<property name="userDetailsService" ref="userService" />
<property name="tokenRepository" ref="persistentTokenRepository" />
<property name="key" value="mykey" />
<property name="cookieName" value="rmb" />
<property name="useSecureCookie" value="false" />
<property name="tokenValiditySeconds" value="946708560" />
<property name="alwaysRemember" value="true"></property>
</bean>
My Social Config:
#Configuration
public class SocialConfig {
#Inject
private Environment environment;
#Inject
private DataSource dataSource;
#Inject
private TextEncryptor textEncryptor;
#Value("${app.url}")
private String applicationUrl;
#Value("${facebook.clientId}")
private String facebookClientId;
#Value("${facebook.clientSecret}")
private String facebookClientSecret;
#Bean
public ConnectionFactoryLocator connectionFactoryLocator() {
ConnectionFactoryRegistry registry = new ConnectionFactoryRegistry();
registry.addConnectionFactory(new FacebookConnectionFactory(
facebookClientId,
facebookClientSecret));
return registry;
}
#Bean
#Scope(value="request", proxyMode=ScopedProxyMode.INTERFACES)
public ConnectionRepository connectionRepository() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication == null) {
throw new IllegalStateException("Unable to get a ConnectionRepository: no user signed in");
}
return usersConnectionRepository().createConnectionRepository(authentication.getName());
}
#Bean
public UsersConnectionRepository usersConnectionRepository() {
JdbcUsersConnectionRepository repository = new JdbcUsersConnectionRepository(
dataSource, connectionFactoryLocator(), textEncryptor);
repository.setConnectionSignUp(connectionSignUp());
return repository;
}
#Bean
public TextEncryptor textEncryptor() {
return Encryptors.noOpText();
}
#Bean
public ConnectController connectController() {
ConnectController controller = new ConnectController(
connectionFactoryLocator(), connectionRepository());
controller.setApplicationUrl(applicationUrl);
return controller;
}
#Bean
public ProviderSignInController providerSignInController(RequestCache requestCache) {
ProviderSignInController controller = new ProviderSignInController(connectionFactoryLocator(),
usersConnectionRepository(), signInAdapter());
controller.setSignUpUrl("/register");
controller.setSignInUrl("/socialSignIn");
controller.setPostSignInUrl("socialSignIn");
controller.addSignInInterceptor(new RedirectAfterConnectInterceptor());
return controller;
}
#Bean
public SignInAdapter signInAdapter() {
return new SignInAdapterImpl();
}
#Bean
public ConnectionSignUp connectionSignUp() {
return new ConnectionSignUpImpl();
}
}

Related

Bean Required for Spring MVC xml file for Amazon S3

What should be the beans in xml file for this same java based configuration?
#Configuration
#ComponentScan(basePackageClasses = Application.class, excludeFilters = #Filter({Controller.class, Configuration.class}))
public class ApplicationConfig {
#Value("${aws_access_key_id}")
private String awsId;
#Value("${aws_secret_access_key}")
private String awsKey;
#Bean
public static PropertyPlaceholderConfigurer propertyPlaceholderConfigurer() {
PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer();
ppc.setLocations(new Resource[] {
new ClassPathResource("/amazon.properties")
});
return ppc;
}
#Bean
public AWSCredentials credential() {
return new BasicAWSCredentials(awsId, awsKey);
}
#Bean
public AmazonS3 s3client() {
return new AmazonS3Client(credential());
}
}
<context:property-placeholder
ignore-resource-not-found="true" ignore-unresolvable="true"
system-properties-mode="OVERRIDE" order="0"
location="classpath:amazon.properties"/>
<bean id="credential" class="com.amazonaws.auth.BasicAWSCredentials">
<constructor-arg name="accessKey" value="${aws_access_key_id}"/>
<constructor-arg name="secretKey" value="${aws_secret_access_key}"/>
</bean>
<bean id="s3client" class="com.amazonaws.services.s3.AmazonS3Client">
<constructor-arg ref="credential"/>
</bean>

Spring #Autowire retuning null while creating an object

I am new to this Spring and trying to learn it.
I am using basic auth jersey and using spring to inject my db props and instantiate the class. However I am getting null pointer exception when I try this with a REST call using postman.
Below is code snippet
AppContx.xml
<context:annotation-config />
<context:component-scan base-package="com.rest" />
<bean id="userDao" class="com.rest.dao.UserDao">
<property name="dataSource" ref="ds" />
</bean>
<bean id="ds" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName" value="java:comp/env/jdbc/Weber" />
<property name="resourceRef" value="true" />
</bean>
Filter
#Provider
public class AuthenticationFilter implements ContainerRequestFilter {
/*ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
IuserDao userDao = (IuserDao) ctx.getBean("userDao");*/
#Autowired
UserDao userDao;
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
public UserDao getUserDao() {
return userDao;
}
if (userDao.getUSerForAuthentication(password, username) == 1) {
String userRole = "ADMIN";
if (rolesSet.contains(userRole)) {
isAllowed = true;
}
DAO
#Autowired
private DataSource dataSource;
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
I am successfully able to inject DB properties to my data source using #Autowired but I am unable to instantiate the UserDao in my Filter class.
Thank You
Mark

Convert JMS out bound channel adapter to equavalent Spring Integration DSL in java 1.7

How can I convert <int-jms:outbound-channel-adapter channel="topicChannel" destination="requestQueue"/> to equivalent Spring Integration DSL in java 1.7
Below is the ActiveMQ configuration:
<bean id="connectionFactory" class="org.springframework.jms.connection.CachingConnectionFactory">
<property name="targetConnectionFactory">
<bean class="org.apache.activemq.ActiveMQConnectionFactory">
<property name="brokerURL" value="tcp://localhost:61616"/>
</bean>
</property>
<property name="sessionCacheSize" value="10"/>
</bean>
<bean id="requestQueue" class="org.apache.activemq.command.ActiveMQQueue">
<constructor-arg value="queue.demo"/>
</bean>
#Bean
public ActiveMQQueue requestQueue() {
return new ActiveMQQueue("queue.demo");
}
etc.
You can configure the sender like this:
#Configuration
#ComponentScan(basePackages = { "com.sample.dispatcher" })
public class DispatcherConfig {
public static final String JOB_TOPIC = "jobTopic";
#Bean
#ServiceActivator(inputChannel = JOB_TOPIC)
public MessageHandler outboundJmsAdapter(JmsTemplate template) {
JmsSendingMessageHandler handler = new JmsSendingMessageHandler(template);
handler.setDestinationName(JOB_TOPIC);
return handler;
}
#Bean(name = JOB_TOPIC)
public MessageChannel jobTopic() {
return new PublishSubscribeChannel();
}
}
and the listener like this
#Configuration
#ComponentScan(basePackages = { "com.sample.processor" })
#IntegrationComponentScan(basePackages = { "com.sample.processor" })
public class ProcessorConfig {
public static final String ON_POST_JOB = "onPostJob";
public static final String JOB_TOPIC = "jobTopic";
#Bean
public Queue jobTopic() {
return new ActiveMQQueue(JOB_TOPIC);
}
#Bean
public JmsMessageDrivenEndpoint inboundJmsAdapter(ConnectionFactory connectionFactory) {
return new JmsMessageEndpointBuilder()
.setConnectionFactory(connectionFactory)
.setDestination(JOB_TOPIC)
.setInputChannel(onPostJob())
.build();
}
#Bean(name = ON_POST_JOB)
public MessageChannel onPostJob() {
return new PublishSubscribeChannel();
}
}
I have a sample project that uses jms and Spring Integration as form of communication between two applications running on separate vm/process/:
https://github.com/vineey/sample-jobqueue

Spring #Cacheable Not Working

I have a dao method annotate with #Cacheable but its cache not working at all. I put log message inside the method.
<cache:annotation-driven mode="proxy" proxy-target-class="true" cache-manager="cacheManager" />
<bean id="ehcache" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
<property name="configLocation" value="WEB-INF/ehcache/ehcache.xml"></property>
<property name="shared" value="true"></property>
</bean>
<bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager">
<property name="cacheManager" ref="ehcache"></property>
</bean>
#Controller
#RequestMapping(value = "/analytics")
public class AnalyticsController {
#Autowired
private ReportDao reportDao;
/**
*
*/
public AnalyticsController() {
}
#RequestMapping(value = "/lcr-report", method = RequestMethod.GET)
public String viewCostReport(ModelMap map) {
List<Country> countryList = reportDao.getAllCountry();
map.put("countryList", countryList);
return "lcrReport";
}
}
#Repository
#Transactional(propagation=Propagation.REQUIRED, isolation=Isolation.DEFAULT,
rollbackFor={DataAccessException.class, SQLException.class, Exception.class})
public class ReportDao {
#Autowired
private JdbcTemplate dao;
/**
*
*/
public ReportDao() {
}
#Cacheable(value = {"reportDao"}/*, key= "T(Country).hash(#List<Country>)"*/)
#Transactional(propagation=Propagation.REQUIRED, isolation=Isolation.DEFAULT, readOnly=true,
rollbackFor={DataAccessException.class, SQLException.class, Exception.class})
public List<Country> getAllCountry() {
List<Country> countryList = null;
BeanPropertyRowMapper<Country> mapper = new BeanPropertyRowMapper<Country>(Country.class);
PreparedStatementCreator psc = new GenericPreparedStatementCreator("select c.country_code as countryCode, c.name as countryName from country c");
System.out.println("Not from cache");
countryList = dao.query(psc, mapper);
return countryList;
}
}
You should create key by using parameters to method getAllCountry. In your case it is empty, so you can do like this:
#Transactional(readOnly = true)
#Cacheable(value = CACHE_NAME, key = "'countries'")
and check if it works using Map cache:
#Configuration
#EnableCaching(proxyTargetClass = true)
public class CacheProducer {
#Bean
public CacheManager cacheManager() {
SimpleCacheManager result = new SimpleCacheManager();
result.setCaches(Arrays.asList(new ConcurrentMapCache(DictionaryServiceImpl.CACHE_NAME)));
return result;
}
}
If it works - it is time to check your echache config.

Spring not dynamic Switch DataSource

Why use AbstractRoutingDataSource can not dynamic switch DataSource
This is the configuration information
public class DynamicSwitch {
public static final ThreadLocal<String> local=new ThreadLocal<String>();
public static void setDB(String id){
local.set(id);
}
public static String getDB(){
return local.get();
}
public static void removeDB(){
local.remove();
}
}
public class DynamicSource extends AbstractRoutingDataSource implements InitializingBean{
#Override
protected Object determineCurrentLookupKey() {
// TODO Auto-generated method stub
return DynamicSwitch.getDB();
}
}
<bean id="dynamic" class="com.aware.DynamicSource">
<property name="targetDataSources">
<map key-type="java.lang.String">
<entry key="1" value-ref="dataSource"></entry>
<entry key="2" value-ref="localdataSource"></entry>
</map>
</property>
<property name="defaultTargetDataSource" ref="dataSource"></property>
</bean>
<bean id="methodService" class="com.test.service.MethodServiceImpl">
<property name="sqlMapClient" ref="sqlMapClient"></property>
</bean>
<bean id="test" class="com.test.Test" scope="prototype"></bean>
public class Test2 extends ActionSupport{
public String execute() throws Exception {
// TODO Auto-generated method stub
DynamicSwitch.setDB("2");
MethodService methodService=(MethodService)ApplicationAware.getBean("methodService");
Map<String, String> map=new HashMap<String, String>();
List list=methodService.testList("Service_ks_missionSpace.getService_ks_missionList", map);
System.out.println(list.size());
return SUCCESS;
}
Invoke DynamicSwitch.setDB("2") find can not Switch DataSource.
DataSource or to default dataSource
Why

Resources