Get UserDetails object from Security Context in Spring MVC controller

前端 未结 6 411
栀梦
栀梦 2020-12-04 06:26

I\'m using Spring Security 3 and Spring MVC 3.05.

I would like to print username of currently logged in user,how can I fetch UserDetails in my Controller?

         


        
相关标签:
6条回答
  • 2020-12-04 07:01

    Let Spring 3 injection take care of this.

    Thanks to tsunade21 the easiest way is:

     @RequestMapping(method = RequestMethod.GET)   
     public ModelAndView anyMethodNameGoesHere(Principal principal) {
            final String loggedInUserName = principal.getName();
    
     }
    
    0 讨论(0)
  • 2020-12-04 07:05

    You can use below code to find out principal (user email who logged in)

      org.opensaml.saml2.core.impl.NameIDImpl principal =  
      (NameIDImpl) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    
      String email = principal.getValue();
    

    This code is written on top of SAML.

    0 讨论(0)
  • 2020-12-04 07:07

    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
    
    0 讨论(0)
  • 2020-12-04 07:12

    That's another solution (Spring Security 3):

    public String getLoggedUser() throws Exception {
        String name = SecurityContextHolder.getContext().getAuthentication().getName();
        return (!name.equals("anonymousUser")) ? name : null;
    }
    
    0 讨论(0)
  • 2020-12-04 07:17

    If you just want to print user name on the pages, maybe you'll like this solution. It's free from object castings and works without Spring Security too:

    @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;
    }
    

    Note "HttpServletRequest request" parameter added.

    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.

    0 讨论(0)
  • 2020-12-04 07:24

    If you already know for sure that the user is logged in (in your example if /index.html is protected):

    UserDetails userDetails =
     (UserDetails)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    

    To first check if the user is logged in, check that the current Authentication is not a AnonymousAuthenticationToken.

    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    if (!(auth instanceof AnonymousAuthenticationToken)) {
            // userDetails = auth.getPrincipal()
    }
    
    0 讨论(0)
提交回复
热议问题