Get UserDetails object from Security Context in Spring MVC controller

前端 未结 6 445
栀梦
栀梦 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: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()
    }
    

提交回复
热议问题