如何在 Spring Security 中调用 target-url 之前在登录/注销时重定向到方法? [英] How to get redirected to a method at login/logout before target-url called in Spring Security?
问题描述
我试图在登录成功后记录当前登录时间(在方法或对象中),并在注销时将 LastLogin 时间分配给当前登录时间.我正在使用 Spring Security 进行登录、注销.但我不知道如何在一个方法进入目标 url 之前控制它.
I am trying to record current time of Login (in a method or object) once the login is successful and assign LastLogin time to current login time at logout. I am using spring security for login, logout. But I don't know how to take control to a method before it goes to the target-url.
spring-security.xml
spring-security.xml
<security:form-login login-page="/login" login-processing-url="/home/currentTime" authentication-failure-url="/login?error=true" default-target-url="/home"/>
<security:logout invalidate-session="true" logout-success-url="/home/copyLastloginToCurrentLoginTime" logout-url="/logout" />
控制器
@RequestMapping(value = "/currentTime", method = RequestMethod.GET)
public void recordCurrentLoginTime(Model model) {
// code to record current time
}
@RequestMapping(value = "/copyLastloginToCurrentLoginTime", method = RequestMethod.GET)
public void changeLastLoginTime(Model model) {
//code to copy current to last time
}
问题
我收到错误 404 for - project-title/j_spring_security_check URL,当我尝试调试时,它根本没有进入控制器方法.
I get Error 404 for - project-title/j_spring_security_check URL and when I try to debug, it doesn't come into the controller methods at all.
我应该为此使用一些过滤器还是其他东西?
Should I use some filters or something else for this purpose?
I found this and that and but that didn't help.
推荐答案
编写自己的 AuthenticationSuccessHandler
和 LogoutSuccessHandler
.
示例:
spring-security.xml:
<security:form-login login-page="/login"
login-processing-url="/login_check"
authentication-failure-url="/login?error=true"
authentication-success-handler-ref="myAuthenticationSuccessHandler"
/>
<security:logout
logout-url="/logout"
success-handler-ref="myLogoutSuccessHandler"
/>
AuthenticationSuccessHandler
@Component
public class MyAuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {
@Autowired
private UserService userService;
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
Authentication authentication) throws IOException, ServletException {
// changeLastLoginTime(username)
userService.changeLastLoginTime(authentication.getName());
setDefaultTargetUrl("/home");
super.onAuthenticationSuccess(request, response, authentication);
}
}
LogoutSuccessHandler
@Component
public class MyLogoutSuccessHandler extends SimpleUrlLogoutSuccessHandler {
@Override
public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response,
Authentication authentication) throws IOException, ServletException {
if (authentication != null) {
// do something
}
setDefaultTargetUrl("/login");
super.onLogoutSuccess(request, response, authentication);
}
}
这篇关于如何在 Spring Security 中调用 target-url 之前在登录/注销时重定向到方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!