一尘不染

如何在Spring Security中调用target-url之前在登录/注销时重定向到方法?

spring-mvc

一旦登录成功,我试图记录登录的当前时间(在方法或对象中),并在注销时将LastLogin时间分配给当前登录时间。我正在使用Spring
Security进行登录,注销。但是我不知道在进入目标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" />

控制者

@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 
}

问题

我收到-项目标题/ j_spring_security_check URL的错误404,当我尝试调试时,它根本没有出现在控制器方法中。

我是否应该为此目的使用一些过滤器或其他工具?

我发现和,但没有帮助。


阅读 446

收藏
2020-06-01

共1个答案

一尘不染

自己写 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);
    }
}

注销成功处理程序

@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);       
    }
}
2020-06-01