当前位置:网站首页>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
边栏推荐
- Exercise 9-1 time conversion (15 points)
- 什么是死锁?(把死锁给大家讲明白,知道是什么,为什么用,怎么用)
- Glory earbud 3 Pro with three global first strong breakdowns flagship earphone Market
- 二叉树的基本操作与题型总结
- [nodejs] electron installation
- Review C language I
- R7-1 sum of numeric elements of a list or tuple
- STM32开发笔记113:ADS1258驱动设计——读取温度值
- Stack栈的实现
- [Yu Yue education] General English of Shenyang Institute of Engineering (4) reference materials
猜你喜欢

Regular execution of shell scripts in crontab

Fastapi 5 - common requests and use of postman and curl (parameters, x-www-form-urlencoded, raw)
![[Chongqing Guangdong education] college physics of Xiangtan University: mechanical and thermal reference materials](/img/64/683a190d14406a9971edd79037cc97.jpg)
[Chongqing Guangdong education] college physics of Xiangtan University: mechanical and thermal reference materials

【解决】修改子物体Transform信息导致变换不对称、异常问题的解决方案

leetcode 257. Binary tree paths all paths to a binary tree (simple)

CloudCompare源码分析:读取ply文件

0-1 knapsack problem of dynamic programming (detailed explanation + analysis + original code)

仅需三步学会使用低代码ThingJS与森数据DIX数据对接

Php+mysql library management system (course design)

Why is the printer unable to print the test page
随机推荐
STM32 development note 113:ads1258 drive design - reading temperature value
Exercise 8-2 finding a specified element in an array (15 points)
MATLAB点云处理(二十五):点云生成 DEM(pc2dem)
Point cloud read / write (2): read / write TXT point cloud (space separated | comma separated)
[uniapp native plug-in] shangmi cashbox plug-in
Tkinter study notes (II)
Swiper -- a solution to the conflict of single page multicast plug-ins
Gcache of goframe memory cache
Lecture de l'article dense Visual SLAM for RGB - D Cameras
Huawei equipment configuration hovpn
Learn to crawl for a month and earn 6000 a month? Don't be fooled. The teacher told you the truth about the reptile
习题11-2 查找星期 (15 分)
[Yu Yue education] basic engineering English of Zhejiang industrial and Commercial University (wuyiping) reference materials
Are you still using localstorage directly? It's time to raise the bar
点云读写(二):读写txt点云(空格分隔 | 逗号分隔)
Glory earbud 3 Pro with three global first strong breakdowns flagship earphone Market
Summary of common paging methods
[Yu Yue education] Yancheng Normal University Advanced Algebra reference
启牛商学院送华泰账户安不安全?真的吗
电脑强制关机 oracle登录不上