开发者

How Can I get log in time while using spring security

I am using spring secu开发者_如何学JAVArity 3 and would like to display the time when user logged in to current session.

Does Spring security provide any such token?

Thanks, - Akshay


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜