How to get redirected to a method at login/logout before target-url called in Spring Security?

后端 未结 2 1578
遥遥无期
遥遥无期 2020-12-04 12:30

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

相关标签:
2条回答
  • 2020-12-04 13:21

    You can map a default-target-url in your mapping like

    <security:form-login login-page="/login"
        login-processing-url="/login_check"
        authentication-failure-url="/login?error=true"
        default-target-url = "/welcome"
        authentication-success-handler-ref="myAuthenticationSuccessHandler"/>
    

    When the user is authenticated it is the time when user accessed your system. Make a update through DAO in the user table with current date and time. Simple process and you are done

    0 讨论(0)
  • 2020-12-04 13:34

    Write your own AuthenticationSuccessHandler and LogoutSuccessHandler.

    Example:

    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);       
        }
    }
    
    0 讨论(0)
提交回复
热议问题