Programing

Spring MVC 컨트롤러의 보안 컨텍스트에서 UserDetails 객체 가져 오기

lottogame 2020. 11. 17. 07:40
반응형

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

참고URL : https://stackoverflow.com/questions/6161985/get-userdetails-object-from-security-context-in-spring-mvc-controller

반응형