2013-07-18 12 views
6

mam Wiosna MVC REST kanał:Jak uzyskać zalogowaną nazwę użytkownika/zleceniodawcę w kanale Spring MVC REST?

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

i mam metodę.

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

teraz muszę nazwę użytkownika, który jest zalogowany Normalnie mogę to zrobić metodą

HttpServletRequest.getUserPrincipal() 

ale jak go uzyskać? Mam adnotacje do nagłówków (@RequestHeader), a nawet pliki cookie (@CookieValue). Ale jak mogę uzyskać Principal w mojej metodzie?

Odpowiedz

19

można wstrzykiwać głównego przedmiotu do metody procedury obsługi kontrolera

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

Zobacz the spring reference manual for more info

+0

OK, mój błąd był, próbowałem go tylko z opisów. –

9

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 reference

+0

W porównaniu z wtryskiem Principal do metody kontrolera, będzie to działało również w innych metodach obsługi, które nie mogą uzyskać zastanego obiektu głównego. –

2

Można również uzyskać poprzez adnotacje zakładając CustomUser realizuje 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 } 
Powiązane problemy