Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get logged user name/Principal in Spring MVC REST channel?

I have Spring MVC REST channel:

@Controller
@RequestMapping("/rest")
public class REST {

and I have my method:

@RequestMapping(value = "/doSomething")
public @ResponseBody DoSomethingResultDTO doSomething(
    @RequestBody DoSomethingRequestDTO)

Now I need the name of the user that is logged in. Normally I could do it by the method

HttpServletRequest.getUserPrincipal()

but how to get it here? I have annotations for headers (@RequestHeader), or even cookies (@CookieValue). But how can I get the Principal in my method?

like image 794
Danubian Sailor Avatar asked Jul 18 '13 10:07

Danubian Sailor


2 Answers

You can inject Principal object to your controller handler method

@RequestMapping(value = "/doSomething")
public @ResponseBody DoSomethingResultDTO doSomething(
    @RequestBody DoSomethingRequestDTO, Principal principal)

See the spring reference manual for more info

like image 74
gerrytan Avatar answered Sep 20 '22 16:09

gerrytan


You can also get through annotations assuming CustomUser implements UserDetails

@RequestMapping(value = { "/home" }, method = RequestMethod.GET)
public String home(@AuthenticationPrincipal CustomUser customUser, Model model, HttpServletRequest request,
        HttpServletResponse response, Locale locale) throws Exception {

    System.out.println("Entering Home Controller @AuthenticationPrincipal: " + customUser);
}

public class CustomUser implements UserDetails { // code omitted }
like image 22
Anand Avatar answered Sep 20 '22 16:09

Anand