2013-07-18 27 views
6

我有Spring MVC的REST通道:如何在Spring MVC REST通道中獲取登錄的用戶名/主體?

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

,我有我的方法:

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

現在我需要在登錄的用戶名一般情況下,我可以通過該方法做

HttpServletRequest.getUserPrincipal() 

但如何在這裏?我有標題註釋(@RequestHeader),甚至cookie(@CookieValue)。但是我怎麼能在我的方法中獲得Principal

回答

19

你可以注入Principal對象控制器處理方法

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

the spring reference manual for more info

+0

OK,我的錯誤是,我只用註釋嘗試過。 –

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

與將Principal注入控制器方法相比,此方法也適用於無法注入Principal對象的其他處理程序方法。 –

2

您也可以通過註釋假設CustomUser實現的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 } 
相關問題