我需要在登录前检查用户是否已超过生效日期并且未过期。我应该怎么做?我既有定制authenticationsuccesshandler
,也有authenticationfailurehandler
.
<form-login login-page="/login"
authentication-failure-url="/login?error"
authentication-failure-handler-ref="authenticationFailureHandler"
authentication-success-handler-ref="authenticationSuccessHandlerWithoutReferer1"/>
弹簧安全.xml
<authentication-manager>
<authentication-provider>
<jdbc-user-service data-source-ref="dataSource"
users-by-username-query="select USER_ID,USER_PWD,USER_STATUS from USER where USER_ID=?"
authorities-by-username-query="select username, authority from authorities where username =? " />
<password-encoder hash="md5"/>
</authentication-provider>
</authentication-manager>
您需要实现 UserDetailsService 接口。
@Service("customUserService")
public class CustomUserService implements UserDetailsService {
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
// find out all necessary information about the user
// for example, use JdbcTemplate to query from your data source
// note especially the boolean accountNonExpired below
return new User(username, password, enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, authorities);
}
}
不能使用 jdbc-user-service
标记。相反:
<authentication-manager>
<authentication-provider user-service-ref="customUserService">
<!-- password encoder etc -->
</authentication-provider>
</authentication-manager>
如果你需要根据文档进行一些特殊情况的身份验证,你必须实现 AuthenticationProvider
http://docs.spring.io/spring-security/site/docs/4.0.0.RC1/reference/htmlsingle/#tech-userdetailsservice
然后,如果您使用的是 Javaconfig,请将其添加到您的AuthenticationManagerBuilder
中。如果使用元数据,我认为您需要执行以下操作:
<authentication-manager>
<authentication-provider ref="customAuthenticationProvider"/>
</authentication-manager>
创建自定义用户详细信息服务实现
例:
@Service("customUserService")
public class UserServiceImpl implements UserDetailsService{
/**
* Used by spring security
*/
public UserDetails loadUserByUsername(String username)
throws UsernameNotFoundException {
try{
//Do all your check
//create object of User and return, password can be anything
return new User(username, password, authorities);
}catch(NubeException e){
throw new UsernameNotFoundException("user_not_found");
}
}
}
然后告诉 spring 使用你的类来进行身份验证:
<authentication-manager>
<authentication-provider user-service-ref="customUserService" />
</authentication-manager>