Nelson Tatius
Nelson Tatius

Reputation: 8043

Spring Security: how to pass additional user info to JSP?

In JSP I can get username by ${pageContext.request.remoteUser}. But there is also additional info (rating of user) I need to display on every page of my site. How can I access it, considering there is a @Service to get it by username?

For what it's worth I use custom authentication provider:

@Service
public class MyUserDetailsService implements UserDetailsService {
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        return new User(s, "password", Arrays.asList(new SimpleGrantedAuthority("ROLE_USER")));
    }
}
<security:authentication-manager>
    <security:authentication-provider user-service-ref='myUserDetailsService'/>
</security:authentication-manager>

Upvotes: 1

Views: 1078

Answers (2)

Simon
Simon

Reputation: 629

You can create a custom UserDetails class (e.g. MyUserDetails) and save the extra information there. In your UserDetailsService, just return this MyUserDetails instead of the normal UserDetail.

public class MyUserDetails extends UserDetail {
    private int rating;
    ... // other properties
    ... // getter setter
}

@Service
public class MyUserDetailsService implements UserDetailsService {
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        return new MyUserDetails(...);
    }
}

In every controller, you can call

(MyUserDetails)SecurityContextHolder.getContext().getAuthentication().getPrincipal();

to the get the current principal/UserDetails, which contains your extra info(e.g. rating of the user).

P.s. If this extra info is related to users, sessions are not the right place to store it, because sessions may expire after closing the browser. If this extra info is just some temporary data, then @Branislav Lazic's answer is correct. Since I can't add a comment, so I have to write the comments to @Branislav Lazic's answer here.

Upvotes: 3

Branislav Lazic
Branislav Lazic

Reputation: 14806

You could create implementation of AuthenticationSuccessHandler and set an attribute there:

@Component
public class AuthenticationSuccessHandlerImpl implements AuthenticationSuccessHandler {
    Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
            Authentication authentication) throws IOException, ServletException {
        request.getSession().setAttribute("someDetail", "detailsValue");
        response.sendRedirect("/to-whatever-url-you-want")
    }
}

Upon successful login, someDetail attribute will be set. Note that you can also obtain currently logged in user from Authentication instance and perform some logic.

Upvotes: 3

Related Questions