How to get registered username / principal in Spring channel MVC REST?

I have a 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 who is logged in. Normally I could do this with a method

 HttpServletRequest.getUserPrincipal() 

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

+7
java spring spring-mvc principal
source share
3 answers

You can add a 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 details.

+20
source share

SecurityContextHolder + Authentication.getName ()

 import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; @Controller public class LoginController { @RequestMapping(value="/login", method = RequestMethod.GET) public String printUser(ModelMap model) { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); String name = auth.getName(); //get logged in username model.addAttribute("username", name); return "hello"; } 

Here is the link

+9
source share

You can also get 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 } 
+2
source share

All Articles