How Can I get log in time while using spring security

不羁岁月 提交于 2019-12-24 10:45:48

问题


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.



来源:https://stackoverflow.com/questions/6596371/how-can-i-get-log-in-time-while-using-spring-security

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!