반응형
Spring MVC 컨트롤러의 보안 컨텍스트에서 UserDetails 객체 가져 오기
Spring Security 3 및 Spring MVC 3.05를 사용하고 있습니다.
현재 로그인 한 사용자의 사용자 이름을 인쇄하고 싶습니다. 컨트롤러에서 UserDetails를 가져 오려면 어떻게해야합니까?
@RequestMapping(value="/index.html", method=RequestMethod.GET)
public ModelAndView indexView(){
UserDetails user = ?
mv.addObject("username", user.getUsername());
ModelAndView mv = new ModelAndView("index");
return mv;
}
사용자가 로그인되어 있는지 이미 알고있는 경우 /index.html
(보호 된 경우 예제에서 ) :
UserDetails userDetails =
(UserDetails)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
사용자가 로그인하는 경우, 최초로 확인하려면, 현재는 확인 Authentication
하지 않은 것입니다 AnonymousAuthenticationToken
.
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (!(auth instanceof AnonymousAuthenticationToken)) {
// userDetails = auth.getPrincipal()
}
Spring 3 주입이이를 처리하도록합니다.
tsunade21 덕분에 가장 쉬운 방법은 다음과 같습니다.
@RequestMapping(method = RequestMethod.GET)
public ModelAndView anyMethodNameGoesHere(Principal principal) {
final String loggedInUserName = principal.getName();
}
페이지에 사용자 이름 만 인쇄하려는 경우이 솔루션이 마음에들 것입니다. 객체 캐스팅이 없으며 Spring Security 없이도 작동합니다.
@RequestMapping(value = "/index.html", method = RequestMethod.GET)
public ModelAndView indexView(HttpServletRequest request) {
ModelAndView mv = new ModelAndView("index");
String userName = "not logged in"; // Any default user name
Principal principal = request.getUserPrincipal();
if (principal != null) {
userName = principal.getName();
}
mv.addObject("username", userName);
// By adding a little code (same way) you can check if user has any
// roles you need, for example:
boolean fAdmin = request.isUserInRole("ROLE_ADMIN");
mv.addObject("isAdmin", fAdmin);
return mv;
}
참고 " HttpServletRequest 요청 "매개 변수가 추가되었습니다.
Works fine because Spring injects it's own objects (wrappers) for HttpServletRequest, Principal etc., so you can use standard java methods to retrieve user information.
That's another solution (Spring Security 3):
public String getLoggedUser() throws Exception {
String name = SecurityContextHolder.getContext().getAuthentication().getName();
return (!name.equals("anonymousUser")) ? name : null;
}
if you are using spring security then you can get the current logged in user by
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
String name = auth.getName(); //get logged in username
반응형
'Programing' 카테고리의 다른 글
Visual Studio 2008에서 디버깅 할 기본 브라우저를 변경하는 방법은 무엇입니까? (0) | 2020.11.17 |
---|---|
Python : 한 줄의 try 문 (0) | 2020.11.17 |
nodejs-http.createServer가 두 번 호출하는 것 같습니다. (0) | 2020.11.17 |
PHP는 명령 줄에서 입력을 기다립니다. (0) | 2020.11.17 |
AngularJ는 컨트롤러 ($ scope)에서 양식 개체에 액세스 할 수 없습니다. (0) | 2020.11.17 |