从spring-security获取用户信息

// 业务逻辑层中有获得当前登录用户信息的需求
// 我们的项目会在控制器方法运行前运行的过滤器中,解析前端传入的JWT
// 将解析获得的用户信息保存在SpringSecurity上下文中
// 这里可以编写方法从SpringSecurity上下文中获得用户信息
public CsmallAuthenticationInfo getUserInfo(){
    // 编写SpringSecurity上下文中获得用户信息的代码
    UsernamePasswordAuthenticationToken authenticationToken=
            (UsernamePasswordAuthenticationToken)
                    SecurityContextHolder.getContext().getAuthentication();
    // 为了逻辑严谨性,判断一下SpringSecurity上下文中的信息是不是null
    if(authenticationToken == null){
        throw new LeaseServiceException(
                ResponseCode.UNAUTHORIZED,"您没有登录!");
    }
    // 确定authenticationToken不为null
    // 就可以从中获得用户信息了
    CsmallAuthenticationInfo csmallAuthenticationInfo=
            (CsmallAuthenticationInfo) authenticationToken.getCredentials();
    // 别忘了返回
    return csmallAuthenticationInfo;
}
// 业务逻辑层中的方法实际上都只需要用户的id即可
// 我们可以再编写一个方法,从用户对象中获得id
public Long getUserId(){
    return getUserInfo().getId();
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值