2013-07-18 43 views
6

Tôi có kênh Spring MVC REST:Làm thế nào để đăng nhập tên người dùng/Hiệu trưởng trong kênh REST MVC Spring?

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

và tôi có phương pháp của tôi:.

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

Bây giờ tôi cần tên của người dùng được đăng nhập Bình thường, tôi có thể làm điều đó bằng phương pháp

HttpServletRequest.getUserPrincipal() 

nhưng cách tải ứng dụng ở đây? Tôi có chú thích cho tiêu đề (@RequestHeader) hoặc thậm chí là cookie (@CookieValue). Nhưng làm thế nào tôi có thể nhận được Principal trong phương pháp của tôi?

Trả lời

19

Bạn có thể tiêm đối tượng chủ yếu đến phương pháp xử lý điều khiển của bạn

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

Xem the spring reference manual for more info

+0

OK, lỗi của tôi là, tôi đã thử nó chỉ có chú thích. –

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

So với việc tiêm Hiệu trưởng vào phương thức điều khiển, điều này cũng sẽ hoạt động trong các phương thức xử lý khác mà không thể lấy đối tượng Chính được tiêm vào. –

2

Bạn cũng có thể nhận được thông qua các chú thích giả CustomUser thực hiện 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 } 
Các vấn đề liên quan