How Can I get log in time while using spring secur

2019-08-07 04:56发布

问题:

I am using spring security 3 and would like to display the time when user logged in to current session.

Does Spring security provide any such token?

Thanks, - Akshay

回答1:

The most reliable option would be customizing your Spring Security filter chain to save a timestamp in the user's session when a successful login occurs. Then you would access it in the same way you access any session attribute.



回答2:

According to the documentation, you can add your own filters to the Spring Security filter chain.
You could add a filter after UsernamePasswordAuthenticationFilter, if you are using http/form-login, or after BasicAuthenticationFilter, in case of http/http-basic, so we guarantee that the session is already created.
To cover both, you can add a filter after the last one, and add the information to the session.

Declare your filter-bean:

<bean id="myFilter" class="com.MyFilter"/>

Add it to the chain, right after BasicAuthenticationFilter:

<http>
    <custom-filter ref="myFilter"  after="BASIC_AUTH_FILTER"/>
    ...

Your doFilter method should look like:

private static final String LOGGED_TIME_KEY = "LOGGED_TIME";

@Override
public void doFilter(ServletRequest req, ServletResponse res,
        FilterChain chain) throws IOException, ServletException {
    HttpServletRequest request = (HttpServletRequest) req;

    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    if (authentication != null && authentication.isAuthenticated()) {
        HttpSession session = request.getSession(false);
        if (session != null && session.getAttribute(LOGGED_TIME_KEY) == null) {
            session.setAttribute(LOGGED_TIME_KEY, new Date());
        }
    }
    chain.doFilter(req, res);
}

Keep in mind that you can use other hooks. You can add it even to your AuthenticationProvider.

EDIT:

There is a easier way to do that, if you are using form-login.
You can use a custom AuthenticationSuccessHandler. To define it, update your form-login tag, adding the attribute authentication-success-handler-ref.