Alex Rivera | Logout

Spring Security: put additional attributes(properties) in the session on success Authentication

Asked 2012-02-20T19:39:17.530
8

Just simple question: what is the best way to add attributes(properties) to the HttpSession on success authentication? The userID for example.

For now i'm using my own SimpleUrlAuthenticationSuccessHandler implementation in UsernamePasswordAuthenticationFilter and doing it like this:

public void onAuthenticationSuccess(HttpServletRequest request,
            HttpServletResponse response, Authentication auth)
            throws IOException, ServletException {
        PersonBean person = (PersonBean) auth.getPrincipal();
        request.getSession().setAttribute("currentUserId", person .getId().toString());
        super.onAuthenticationSuccess(request, response, auth);

But I dont think this is good approach as there is another ways to do authentication(RememberMe for example).

So what do I need to use here?

Edit
Report

1 Answer

-1

Spring does all this for you, you'll have to create a table *persistent_logins*, here is a snippet from app context that might help. And the official doc's lay describe in detail what is required :

<security:http auto-config='true'>
  <security:intercept-url pattern="/**" access="ROLE_USER" />
  <security:form-login login-page="/Login"
     authentication-success-handler-ref="authenticationSuccessHandler"
     authentication-failure-url="/Login?login_error=1" />
  <security:remember-me data-source-ref="dataSource"
    user-service-ref="myUserService" />
</security:http>

and then you can access the principal object from your anywhere in your app, eg below shows the tag to output username in jsp :

<sec:authentication property="principal.username" />

and from your java code this can be done :

MyUser user = (MyUser) authentication.getPrincipal();
answered 2012-02-21T10:18:19.053

Your Answer