Frage

I have a spring-mvc application that currently has two channels - web application and a REST service. Both have user's http session and I can easily get the "current user" in my service classes.

Now I need to develop another REST service where there are no http sessions and the current user depends on a request parameter. So the controller would read that request parameter and would find the current user.

Now I either need to: 1. modify my service layer methods to accept current user as parameter or 2. just modify the class that gets the current user from the http session.

I also have the requirement to create an audit log and I'm going to use Spring AOP for that. The Aspect will need access to the "current user" too. So option #1 probably won't work for me and I will go with #2.

For option #2 I'll create an interceptor that will put the current user in a ThreadLocal variable. The controller for the new REST service will do the same and then in my service layer and in the audit log aspect I can get the current user from there.

I haven't done anything like this before and was wondering if there is a better approach. Or what kind of issues I should expect with this approach.

I will appreciate any comments and ideas.

Oz

Here is how I currently get the current user:

@Override
public User getCurrentUser()
{
    Authentication currentUser = getAuthentication();

    return userService.getByLoginName(currentUser.getName());
}


protected Authentication getAuthentication()
{
    return SecurityContextHolder.getContext().getAuthentication();
}
War es hilfreich?

Lösung

I think a simple way to do what you need is to configure a servlet filter for your new REST webservice to populate the SecurityContextHolder with an Authentication object build from request parameters.

You can read this : http://static.springsource.org/spring-security/site/docs/3.1.x/reference/springsecurity-single.html#d0e2171 for more details.

With this solution you don't need to modify the code to retrieve the current user. (note that the SecurityContextHolder is already using a ThreadLocal to store the SecurityContext and so the Authentication)

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top