Announcement Announcement Module
Collapse
No announcement yet.
Spring Security Login not authenticating with database details Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • Spring Security Login not authenticating with database details

    I have an application that I'm trying to configure so that a user can log in with a username and password from the database. The problem is everytime I try to login with a username/password it returns the login failed page.

    In the output console is also this and no error message in the stack trace.

    Code:
    loadUserByUsername  :  ed23
    This is my implementation in the security xml:

    Code:
    	 <global-method-security pre-post-annotations="enabled" />
    
    <http auto-config="true" use-expressions="true" access-denied-page="/denied">
    
    		
        	<intercept-url pattern='/home.jsp' access="hasRole('ROLE_USER')" /> 
        	<intercept-url pattern='/admin.jsp' access="hasRole('ROLE_ADMIN')" />
            
            <form-login login-page='/login.jsp' always-use-default-target="true" default-target-url="/main/home" authentication-failure-url="/login_error.jsp?error=true"/>   
        
        	<logout invalidate-session="true" logout-success-url='/login.jsp' /> 
         
        	 
    	
        </http>
        
        <!-- authentication manager and password hashing -->
    		<authentication-manager alias="authenticationManager">
        		<authentication-provider ref="daoAuthenticationProvider"/>
    </authentication-manager>
    
    <beans:bean id="daoAuthenticationProvider" class="org.springframework.security.authentication.dao.DaoAuthenticationProvider">
        <beans:property name="userDetailsService" ref="userDetailsService"/>
        <beans:property name="saltSource">
            <beans:bean class="org.springframework.security.authentication.dao.ReflectionSaltSource">
                <beans:property name="userPropertyToUse" value="username"/>
            </beans:bean>
        </beans:property>
        <beans:property name="passwordEncoder" ref="passwordEncoder"/>
    </beans:bean>
    
    <beans:bean id="userDetailsService"  class="com.project.professional.service.StaffServiceImpl">
        
    </beans:bean>
    
    <beans:bean id="passwordEncoder" class="org.springframework.security.authentication.encoding.ShaPasswordEncoder">
        <beans:constructor-arg index="0" value="256"/>
    </beans:bean>
    My login form:

    Code:
    <form action="${loginUrl}" method="post" name="loginForm">
    
    		<p>
    		<label for="j_username">Username</label>
    		<input id="j_username" name="j_username" type="text" />
    		</p>
    
    		<p>
    		<label for="j_password">Password</label>
    		<input id="j_password" name="j_password" type="password" />
    		</p>
    
    		<input  type="submit" value="Login"/>								
    	
    		</form>

    The controller for this:

    Code:
    	@RequestMapping(value = "/main/home", method = RequestMethod.GET)
    	public String getHomePage(Locale locale, Model model) {
    		logger.info("Welcome home! The client locale is {}.", locale);
    		
    		Date date = new Date();
    		DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
    		
    		String formattedDate = dateFormat.format(date);
    		
    		model.addAttribute("serverTime", formattedDate );
    		
    		return "/main/home";
    	}
    	
    	@RequestMapping(value="/", method = RequestMethod.GET)
    	public String getLoginPage(ModelMap model) {
    		logger.info("This is the login page {}.");
    	
    		return "login";
    	
    	}
    My Implementation of the userdetails interface

    Code:
    public UserDetails loadUserByUsername(String username)
    				throws UsernameNotFoundException {
    			System.out.println("loadUserByUsername  :  " + username);
    			//DAO<Staff> sessionFactory = null;
    			Session session = sessionFactory.getCurrentSession();
    			
    			username = (username == null) ? "" : username;
    			Query query = session
    					.createQuery("from Staff where username=:username");
    			query.setParameter("username", username);
    
    			if (query.list().isEmpty()) {
    				return null;
    			}
    
    			return (UserDetails) query.list().get(0);
    
    		}
    along with this:

    Code:
    public Staff getStaffDetails(String username) {
    Session session = sessionFactory.getCurrentSession();
    		Query query = session.createQuery("from Staff where username=:username");
    		query.setParameter("username", username);
    
    		if (query.list().isEmpty()) {
    			return null;
    		}
    		return (Staff) query.list().get(0);
    I'm not sure where the error is. Also when I try to use an in memory username/password, that works but not when I then try to get the username/password from the database. I would appreciate any help as I have been struggling with this for days now.
    Last edited by Sannei; Apr 30th, 2013, 06:03 AM.

  • #2
    I think in your implementation of UserDetails , it not getting the org.springframework.security.core.userdetails.User object in return,
    so please try to return User object like below

    return new User(username,password,isEnabled,isAccountNonExpir ed,isCredentialsNonExpired,isAccountNonLocked,gran tedAuthorities(employee.getRoles()));

    Comment

    Working...
    X