Announcement Announcement Module
Collapse
No announcement yet.
Issues with automatic login with a custom user details service Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • Issues with automatic login with a custom user details service

    I'm having some issues with my implementation of spring security. I am using a custom user details service and when I attempt to signup a new account it doesn't seem to be logging in the user as it should. Here's the code that I'm attempting to use to login the user with the SignInUtils class

    SignInUtils.java

    Code:
    package com.youthministry.controller;
    	
    	import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
    	import org.springframework.security.core.context.SecurityContextHolder;
    	
    	public class SignInUtils {
    		/**
    		 * Programmatically signs in the user with the given the user ID.
    		 */
    		public static void signin(String userId) {
    			SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(userId, null, null));	
    		}
    	
    	}
    LoginController.java

    Code:
    package com.youthministry.controller;
    	
    	import javax.validation.Valid;
    	
    	import org.springframework.beans.factory.annotation.Autowired;
    	import org.springframework.social.connect.Connection;
    	import org.springframework.social.connect.web.ProviderSignInUtils;
    	import org.springframework.stereotype.Component;
    	import org.springframework.stereotype.Controller;
    	import org.springframework.validation.BindingResult;
    	import org.springframework.web.bind.annotation.RequestMapping;
    	import org.springframework.web.bind.annotation.RequestMethod;
    	import org.springframework.web.context.request.WebRequest;
    	import com.youthministry.controller.SignInUtils;
    	import com.youthministry.controller.SignupForm;
    	import com.youthministry.domain.Role;
    	import com.youthministry.domain.User;
    	import com.youthministry.domain.UserProfile;
    	
    	import com.youthministry.service.UserService;
    	
    	@Controller
    	public class LoginController {
    	
    		@Autowired
    		private UserService UserService;
    		
    		@RequestMapping(value={"/", "/signin"})
    		public String signin() {
    			return "signin";
    		}
    		
    		@RequestMapping(value="/signup", method=RequestMethod.GET)
    		public SignupForm signupForm(WebRequest request) {
    			Connection<?> connection = ProviderSignInUtils.getConnection(request);
    			if (connection != null) {
    				return SignupForm.fromProviderUser(connection.fetchUserProfile());
    			} else {
    				return new SignupForm();
    			}
    		}
    	
    		@RequestMapping(value="/signup", method=RequestMethod.POST)
    		public String signup(@Valid SignupForm form, BindingResult formBinding, WebRequest request) {
    			if (formBinding.hasErrors()) {
    				return null;
    			}
    			User user = createUser(form, formBinding);
    			if (user != null) {
    				SignInUtils.signin(user.getUsername());
    				ProviderSignInUtils.handlePostSignUp(user.getUsername(), request);
    				return "redirect:/home";
    			}
    			return null;
    		}
    		
    		// Internal helpers
    		private User createUser(SignupForm form, BindingResult formBinding) {
    			User user = new User();
    			user.setUsername(form.getUsername());
    			user.setPassword(form.getPassword());
    	
    			UserProfile userProfile = new UserProfile();
    			userProfile.setFirstName(form.getFirstName());
    			userProfile.setLastName(form.getLastName());
    	
    			user.setUserProfile(userProfile);
    	
    			Role role = new Role();
    			role.setName("ROLE_USER");
    			
    			user.getRoles().add(role);
    			
    			UserService.addUser(user);
    	
    			return user;
    		}
    	}
    spring-security.xml

    Code:
    <?xml version="1.0" encoding="UTF-8"?>
    	<beans:beans xmlns="http://www.springframework.org/schema/security"
    		xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    		xmlns:beans="http://www.springframework.org/schema/beans"
    		xsi:schemaLocation="http://www.springframework.org/schema/security http://www.springframework.org/schem...curity-3.1.xsd
    			http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">
    	
    		<http pattern="/resources/css/**" security="none"/>
    		<http pattern="/resources/images/**" security="none"/>
    		<http pattern="/resources/scripts/**" security="none"/>
    	 
    		<http use-expressions="true" access-denied-page="/accessDenied.jsp" >
    			<form-login login-page="/signin" default-target-url="/home" login-processing-url="/signin/authenticate" authentication-failure-url="/signin?error=bad_credentials"/>		
    			<logout logout-success-url="/signin" />
    			<intercept-url pattern="/admin/**" access="hasRole('ROLE_ADMIN')" />
    			<intercept-url pattern="/group/**" access="hasRole('ROLE_USER')" />
    			<intercept-url pattern="/group" access="hasRole('ROLE_USER')" />
    			<intercept-url pattern="/home" access="hasRole('ROLE_USER')" />
    			<intercept-url pattern="/**" access="permitAll" />
    			<intercept-url pattern="/auth/**" access="permitAll" />
    			<intercept-url pattern="/disconnect/facebook" access="permitAll" />
    			<remember-me user-service-ref="userDetailsService" />
    	
    		<!--<session-management invalid-session-url="/invalidsession.jsp">
    				<concurrency-control max-sessions="1"
    					error-if-maximum-exceeded="true" />
    			</session-management>-->
    	
    			<!--  Spring Social Security authentication filter -->
    			<custom-filter ref="socialAuthenticationFilter" before="PRE_AUTH_FILTER" />
    		</http>
    	 
    		<beans:bean id="customEncoder" class="com.youthministry.security.CustomPasswordEncoder" />
    		<beans:bean id="customUserService"
    			class="com.youthministry.security.CustomUserDetailService" >
    		</beans:bean>
    	
    		<authentication-manager alias="authenticationManager" >
    			<authentication-provider user-service-ref="customUserService">
    				<password-encoder ref="customEncoder" />
    			</authentication-provider>
    			<!-- Spring Social Security authentication provider -->
    			<authentication-provider ref="socialAuthenticationProvider" />
    		</authentication-manager>
    	
    		<jdbc-user-service id="userDetailsService" 
    						data-source-ref="dataSource" 
    						users-by-username-query="select username, password, true from User where username = ?"
    						authorities-by-username-query="select u.username username, r.name authority from user_roles u_roles, user u, roles r where u.username = ?"/>
    	
    		<beans:bean id="textEncryptor" class="org.springframework.security.crypto.encrypt.Encryptors"
    			factory-method="noOpText" />
    			
    		<beans:bean id="passwordEncoder" class="org.springframework.security.crypto.password.NoOpPasswordEncoder"
    			factory-method="getInstance" />
    	
    	</beans:beans>
    If any other files may be needed to help let me know. Otherwise here's the link the github repo.

    http://github.com/dmcquillan314/Yout...yHibernate.git

    Thanks in advance for any assistance I'm still new to spring and trying to figure out a few issues regarding initial spring-security configuration. Any comments on the github project are also welcome.
    Last edited by Rob Winch; Mar 19th, 2013, 10:07 AM. Reason: code formatting

  • #2
    You need to ensure to specify a role for the user in SignInUtils.signin otherwise they will not have access.

    PS: In the future it helps to use the code tags (i.e. the # button) as it makes it easier for the code to be read.

    Comment

    Working...
    X