当前位置:网站首页>SecurityContextHolder. getContext(). getAuthentication(). Getprincipal() gets username instead of userdetails

SecurityContextHolder. getContext(). getAuthentication(). Getprincipal() gets username instead of userdetails

2022-06-11 22:36:00 Shan Xiaofeng

1. Problem introduction

I am using SpringSecurity+JWT When doing authority authentication , @PreAuthorize("@el.check(‘system:user:query’)")
Use the above annotation to determine whether the user has method level operation permission , However, when using the method below to obtain the current login user, only the user name is obtained , instead of UserDetails object .
SecurityContextHolder.getContext().getAuthentication().getPrincipal()

2. Solutions

Check whether it is saved after successful login Authentication auth
Although the print has been deleted , But the test can print auth Of , It includes UserDetails

    @Override
    protected void successfulAuthentication(HttpServletRequest req, HttpServletResponse res, FilterChain chain,
                                            Authentication auth) throws IOException, ServletException {
    
        SecurityUser user = (SecurityUser) auth.getPrincipal();
        String token = tokenManager.createToken(user.getCurrentUserInfo().getAccount());

        SecurityContextHolder.getContext().setAuthentication(auth);

        redisUtil.set(user.getCurrentUserInfo().getAccount(),user, GlobalConstant.REDIS_SAVE_TIME);
        log.info(" 3. Login successfully saved the user to redis And back to token=="+token);
        ResponseUtil.out(res, ResultJson.ok().data(GlobalConstant.ACCESS_TOKEN, token));
    }

And in the code below .getAuthentication().getPrincipal() What you get is username, Cause problems with certification

    /** *  Get the current login user  * @return UserDetails */
    public static UserDetails getCurrentUser() {
    
        final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null) {
    
            throw new BizException(CommonEnum.STATUS_EXPIRED);
        }
        if (authentication.getPrincipal() instanceof UserDetails) {
    
            UserDetails userDetails = (UserDetails) authentication.getPrincipal();
            UserDetailsService userDetailsService = SpringContextHolder.getBean(UserDetailsService.class);
            return userDetailsService.loadUserByUsername(userDetails.getUsername());
        }
        throw new BizException(CommonEnum.NOT_FIND_LOGIN_INFORMATION);
    }

Later, I found that there was no problem with the login authorization , But when asked to hold token When I came to authenticate, I made a mistake . Because I wrote it myself token Decision filter , So I checked the code again and again and finally found the problem : user.getUsername()

                    logger.info("4. More token Access authorization ==" + user.getAuthorities());
                    return new UsernamePasswordAuthenticationToken(user.getUsername(), null, user.getAuthorities());

Change to
UsernamePasswordAuthenticationToken(user, null, user.getAuthorities());
That's right

原网站

版权声明
本文为[Shan Xiaofeng]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/162/202206112234039078.html