shiro通过sessionId获取当前用户登录信息

一、应用场景

前后端分离架构,使用shiro做权限管理,登录成功将sessionId返回,访问接口时在请求头携带即可。由于业务需要,现有需要接口不做拦截,在方法内做权限判断,于是将sessionId携带在RequestParam中,进行登录或权限校验。

 

二、实现代码

ProfileResult:登录中构造安全数据的实体类

import com.guangjutx.entity.auth.Permission;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.UnknownSessionException;
import org.apache.shiro.session.mgt.DefaultSessionKey;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.apache.shiro.subject.support.DefaultSubjectContext;
import java.util.List;
import java.util.Map;
/**
 * @Title:ShiroUtils
 * @Author 丁文浩
 * @Date 2020/4/17 12:17
 */
@Slf4j
public class ShiroUtils {

    public static ProfileResult getUserInfoBySessionId(String sessionId){
        ProfileResult result = null;
        try{
            Session se = SecurityUtils.getSecurityManager().getSession(new DefaultSessionKey(sessionId));
            Object obj = se.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY);
            SimplePrincipalCollection coll = (SimplePrincipalCollection) obj;
            result = (ProfileResult)coll.getPrimaryPrincipal();
        }catch (UnknownSessionException e){
            log.error("There is no session with id [{}]",sessionId);
        }
        return result;
    }

    public static boolean isPermissions(ProfileResult profileResult,String permissions){
        Map<String, Object> roleAndPerm = profileResult.getRoleAndPerm();
        List<Permission> permissionList = (List)roleAndPerm.get("perms");
        for(Permission permission : permissionList){
            if(permission.getCode().equals(permissions)){
                return true;
            }
        }
        return false;
    }

}

 

  • 1
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值