我对成功的 认证通过后执行自定义任务的方法是在 春季安全使用自定义身份验证成功处理程序。
你可以如下做到这一点:
创建自定义AuthenticationSuccessHandler
像TMGAuthenticationSuccessHandler
。如果检测到用户使用默认的机器生成密码,我创建了一个将用户重定向到密码更改页面的示例代码。
@Component("tMGAuthSuccessHandler")
public class TMGAuthSuccessHandler implements AuthenticationSuccessHandler {
private AuthenticationSuccessHandler target = new SavedRequestAwareAuthenticationSuccessHandler();
@Autowired
private UserService userService;
private static final Logger LOGGER = LoggerFactory.getLogger(TMGAuthSuccessHandler.class);
@Override
public void onAuthenticationSuccess(HttpServletRequest servletRequest, HttpServletResponse servletResponse, Authentication authentication)
throws IOException, ServletException {
if (hasDefaultPassword(authentication)) {
LOGGER.debug("Default password detected for username: " + authentication.getName());
servletResponse.sendRedirect("changePassword");
} else {
target.onAuthenticationSuccess(servletRequest, servletResponse, authentication);
}
}
/**
* Checks whether default password is used in login.
*/
private boolean hasDefaultPassword(Authentication authentication) {
String username = authentication.getName();
User user = userService.findOnUsername(username, true, false, false, false);
if (user != null && user.getLoginAuditTrail() != null && user.getLoginAuditTrail().isDefaultPasswordUsed() != null) {
return user.getLoginAuditTrail().isDefaultPasswordUsed();
}
return false;
}
/**
* Proceeds to the requested URL.
*/
public void proceed(HttpServletRequest servletRequest, HttpServletResponse servletResponse, Authentication authentication) throws IOException,
ServletException {
target.onAuthenticationSuccess(servletRequest, servletResponse, authentication);
}
}
修改securityContext.xml
或包含弹簧安全相关配置的类似文件。将此定制版本添加到http
配置为authentication-success-handler-ref="tMGAuthSuccessHandler"
。代码片段如下所示:
<security:http use-expressions="true" authentication-manager-ref="webAppAuthManager">
<!-- signin and signout -->
<security:intercept-url pattern="/signin" access="permitAll" />
<security:intercept-url pattern="/logout" access="permitAll" />
<security:intercept-url pattern="/accessDenied" access="permitAll"/>
<security:intercept-url pattern="/**" access="isAuthenticated()" />
<!-- sign in Configuration -->
<security:form-login login-page="/signin"
username-parameter="username"
password-parameter="password"
authentication-failure-url="/signin?authFail=true"
authentication-success-handler-ref="inoticeAuthSuccessHandler" />
<security:logout logout-url="/signout" invalidate-session="true" delete-cookies="JSESSIONID" logout-success-url="/signin?logout=true" />
</security:http>
你现在很好走。
参考信用:How to use custom filter with authentication-success-handler-ref equivalent in spring security
我提供了一个不同的方法来达到你想要什么,请检查出来,让我知道它是否能解决你的问题。 – SyntaX