Accessing The Currently Logged In User With Spring Security/MVC

A common scenario is wanting to access the currently logged in user in the controller layer of a Spring MVC application. There is a way to do it by implementing a custom WebArgumentResolver, but with Spring Security 3.2 there is an easier way.

Initial Conditions

This presumes that Spring Security is already working and already being used to authenticate users. At this point we also presume that we have an implementation of UserDetails. Our goal is to pass the currently logged in user to a Spring MVC web controller method.

Your Secure Free Lunch

As of Spring Security 3.2, a web argument resolver and annotation is provided for specifying the logged-in-user to controller methods. All you have to do is specify the @AuthenticationPrincipal annotation on your method’s User argument, and Spring Security will automatically resolve that argument for you. In the code below, the CustomUserDetails is our own implementation of UserDetails.

Observe:

@Controller
public class FooController {
    @RequestMapping(value="/foo/bar", method=RequestMethod.GET)
    public String fooAction(@AuthenticationPrinciple CustomUserDetails user) {
        System.out.print.println(user.getName());
        return "foo";
    }
}

Happy userdetailing!

Advertisements

Leave a comment

Filed under Software Engineering

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s