2013-07-18 10 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)、またはクッキー(@CookieValue)のための注釈を持っています。しかし、どうすれば私の方法でPrincipalを手に入れることができますか?

答えて

19

あなたは

@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オブジェクトを注入することができます
+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 } 
関連する問題