当您使用 Spring Security 时,我假设您已经配置了 authenticationManager,并且您的 UserEntity 实现了 UserDetails。
我的建议是提供自定义身份验证失败处理程序并在您的 UserEntity 中覆盖 isCredentialsNonExpired()。
这是一个示例(使用基于 java 的配置)。
自定义身份验证失败提供程序
@Bean
public AuthenticationFailureHandler customAuthenticationFailureHandler() {
ExceptionMappingAuthenticationFailureHandler exceptionMappingAuthenticationFailureHandler =
new ExceptionMappingAuthenticationFailureHandler();
Map<Object, Object> map = new HashMap<>();
map.put(
"org.springframework.security.authentication.CredentialsExpiredException",
"/resetPassword.html"
);
exceptionMappingAuthenticationFailureHandler.setExceptionMappings(map);
exceptionMappingAuthenticationFailureHandler.setRedirectStrategy(
new RedirectStrategy() {
@Override
public void sendRedirect(
HttpServletRequest request, HttpServletResponse response, String url
) throws IOException {
response.sendRedirect(request.getContextPath() + url);
}
}
);
return exceptionMappingAuthenticationFailureHandler;
}
XML方式
<bean id="customAuthenticationFailureHandler" class="org.springframework.security.web.authentication.ExceptionMappingAuthenticationFailureHandler">
<property name="exceptionMappings">
<props>
<prop key="org.springframework.security.authentication.CredentialsExpiredException">/change_password_page</prop>
</props>
</property>
<property name="defaultFailureUrl" value="/resetPassword"/>
</bean>
在你的 security.xml 中
<security:form-login ... authentication-failure-handler-ref="customAuthenticationFailureHandler">
最后在你的UserEntity
@Override
public boolean isCredentialsNonExpired() {
if (// check password is expired or not) {
return false;
}
return true;
}
所以当密码过期时,失败处理程序将重定向到您想要的页面。