Spring Security 获取解析JWT

/**
 * 自定义认证框架数据封装
 */
@Data
@ApiModel(value="自定义认证框架数据封装")
public class AuthenticationInfo {
    /**
     * 用户id 可以是admin用户也可以是普通user用户id
     */
    @ApiModelProperty(value="用户id")
    private Long id;
    @ApiModelProperty(value="用户名")
    private String username;
    @ApiModelProperty(value="用户类型")
    private String userType;
    @ApiModelProperty(value="用户权限列表")
    private List<String> authorities;
}

/**
 * 从Spring Securety上下文中解析获取JWT解析的对象
 * @return
 */
public AuthenticationInfo getUserInfo(){
    UsernamePasswordAuthenticationToken authenticationToken = (UsernamePasswordAuthenticationToken)
            SecurityContextHolder.getContext().getAuthentication();
    if(authenticationToken==null){
        throw new ServiceException(ResponseCode.UNAUTHORIZED,"用户没有登录!!!");
    }
    //从上下文中获取登录登录用户的信息--信息有JWT解析获得
    AuthenticationInfo AuthenticationInfo = (AuthenticationInfo) authenticationToken.getCredentials();
    //返回登录信息
    return AuthenticationInfo;
}

// 业务逻辑层大多数方法都是只需要用户的ID,专门编写一个方法返回id
public Long getUserId(){
    return getUserInfo().getId();
}
posted @   Sentinel-163  阅读(55)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
点击右上角即可分享
微信分享提示