2013-07-18 18 views
6

Spring MVC DİNLENME kanal vardır:Spring MVC REST kanalında oturum açma kullanıcı adı/Müdür nasıl alınır?

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

ve benim yöntemi vardır:.

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

Şimdi kaydedilir kullanıcının adını ihtiyaç Normalde yöntemle yapabileceğini

HttpServletRequest.getUserPrincipal() 

ama nasıl burada alınır? Başlıklar için ek açıklamalarım ( @RequestHeader), hatta çerezler ( @CookieValue). Ama benim yöntemimde Principal nasıl alabilirim?

cevap

19

Sen

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

the spring reference manual for more info

+0

Tamam uygular, benim hata oldu, ben sadece ek açıklamalarla denedim. –

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 gör Denetleyiciniz işleyicisi yöntemine Baş nesne enjekte edebilir
+0

Denetleyici yöntemine Principal uygulamasının enjekte edilmesine kıyasla, bu, asıl nesne nesnesinin enjekte edilemediği diğer işleyici yöntemlerinde de çalışacaktır. –

2

Ayrıca CustomUser varsayarak ek açıklamalar geçebilecek 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 } 
İlgili konular