用户注册在spring security 4.0.1中使用自定义身份验证筛选器失败

时间:2015-05-19 06:52:39

标签: java spring spring-mvc authentication spring-security

我尝试在数据库中创建用户实体后对用户进行身份验证,以便在安全上下文中设置经过身份验证的用户。但它没有投出 Bad Credentials 错误。

这是代码

 UserDetails userDetails = userAuthService.loadUserByUsername(form.getUsername());
            UsernamePasswordAuthenticationToken loggedIn = new UsernamePasswordAuthenticationToken(userDetails, userDetails.getPassword(), userDetails.getAuthorities());
            //loggedIn.setDetails(userDetails);
            authMgr.authenticate(loggedIn);

我正确地获取了userDetails。在第一个声明中。

我正在使用下面的自定义身份验证

<authentication-manager alias="authMgr">
    <authentication-provider user-service-ref="userAuthService">
        <password-encoder hash="bcrypt"></password-encoder> 
    </authentication-provider>
</authentication-manager>
<beans:bean id="userAuthService" class="com.csn.service.UserAuthService" >
</beans:bean>

UserAuthService类是这样的。

public class UserAuthService implements UserDetailsService,Serializable{
@Override
public UserDetails loadUserByUsername(String username)
        throws UsernameNotFoundException, DataAccessException {
    try{
        com.xxx.yyy.Authentication auth = new UserAuthDao().getUserByUsername(username);
        if(auth!=null){
            List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
            authorities.add(new com.xxx.ppp.GrantedAuthorityImpl(Constants.userRole));

            return new User(auth.getUsername(), auth.getPassword(), true, true, true, true, authorities);
        }
        else{
            return  new User(username, "", true, true, true, true, null);
        }
    }
    catch(Exception e){
        log.error(className, "loadUserByUsername", e);
    }
    return null;
}
}

1 个答案:

答案 0 :(得分:2)

这应该有所帮助:

SecurityContextHolder.getContext().setAuthentication(loggedIn);