如何在spring-security,spring mvc中调用target-url之前重定向到登录/注销时的方法

sar*_*ara 16 spring-mvc spring-security

我试图在登录成功后记录登录的当前时间(在方法或对象中),并在注销时将LastLogin时间分配给当前登录时间.我使用spring security登录,注销.但是我不知道在进入target-URL之前如何控制方法.

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" />
Run Code Online (Sandbox Code Playgroud)

控制器 - /home -

 @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 }
Run Code Online (Sandbox Code Playgroud)

问题 - 我得到错误404 - project-title/j_spring_security_check URL.当我尝试调试时,它根本不会进入控制器方法.我应该为此目的使用一些过滤器或其他东西吗?

我见过SpringSecurity:总是将登录用户重定向到页面以及如何使用Spring Security/Spring MVC处理表单登录.但无法实现我的目标.

我是春天安全的新手,我需要一些帮助才能朝着正确的方向前进.

  • 谢谢

lsc*_*hin 32

编写自己的AuthenticationSuccessHandlerLogoutSuccessHandler.

示例:

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"
/>
Run Code Online (Sandbox Code Playgroud)

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

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);       
    }
}
Run Code Online (Sandbox Code Playgroud)