关于shiro的 subject.getPrincipal()方法

2023-05-16

1、说明

上一篇文章说明了 principal,而subject.getPrincipal();是用来干嘛的,他就是来获取你存储的principal,内部是怎么获取的那,多个principal怎么指定获取哪一个那。

2、解释

1)subject.getPrincipal();最后调用的是下面这个方法

public Object getPrimaryPrincipal() {
        if (isEmpty()) {
            return null;
        }
        return iterator().next();
    }

2)可见他便利的是集合,那就是说明每次调用都会不一样,那么就存在一定的风险性。如果我们希望每次调用都返回一个固定的值例如id,应该怎么办呐,其实非常简单,只需要扩展两个类即可。

3、编码

1)扩展SimplePrincipalCollection这个类,新建一个类来继承他,我们只需要重写他的一个方法就好,另外类他添加一个额外的来接受id的属性,这样在getPrimaryPrincipal方法中我们只需把id返回就好。代码如下

public class CustomSimplePrincipalCollection extends SimplePrincipalCollection {

    private Object primary;

    public CustomSimplePrincipalCollection() {
    }


    public CustomSimplePrincipalCollection(Object primary, Object principal, String realmName) {
        super(principal, realmName);
        this.primary = primary;
    }

    public CustomSimplePrincipalCollection(Object principal, String realmName) {
        super(principal, realmName);
    }

    public CustomSimplePrincipalCollection(Collection principals, String realmName) {
        super(principals, realmName);
    }

    public CustomSimplePrincipalCollection(PrincipalCollection principals) {
        super(principals);
    }

    @Override
    public Object getPrimaryPrincipal() {
        return primary;
    }

    public Object getCustomPrimaryPrincipal() {
        return primary;
    }
}

2)然后重写SimpleAuthenticationInfo,这个需要实现响应的接口,然后修改部分方法即可

public class CustomSimpleAuthenticationInfo implements MergableAuthenticationInfo, SaltedAuthenticationInfo {

    /**
     * The principals identifying the account associated with this AuthenticationInfo instance.
     */
    protected PrincipalCollection principals;
    /**
     * The credentials verifying the account principals.
     */
    protected Object credentials;

    /**
     * Any salt used in hashing the credentials.
     *
     * @since 1.1
     */
    protected ByteSource credentialsSalt;

    /**
     * Default no-argument constructor.
     */
    public CustomSimpleAuthenticationInfo() {
    }


    public CustomSimpleAuthenticationInfo(Object primary, Object principal, Object credentials, String realmName) {
        this.principals = new CustomSimplePrincipalCollection(primary, principal, realmName);
        this.credentials = credentials;
    }


    public CustomSimpleAuthenticationInfo(Object principal, Object hashedCredentials, ByteSource credentialsSalt, String realmName) {
        this.principals = new CustomSimplePrincipalCollection(principal, realmName);
        this.credentials = hashedCredentials;
        this.credentialsSalt = credentialsSalt;
    }


    public CustomSimpleAuthenticationInfo(PrincipalCollection principals, Object credentials) {
        this.principals = new CustomSimplePrincipalCollection(principals);
        this.credentials = credentials;
    }

    public CustomSimpleAuthenticationInfo(PrincipalCollection principals, Object hashedCredentials, ByteSource credentialsSalt) {
        this.principals = new CustomSimplePrincipalCollection(principals);
        this.credentials = hashedCredentials;
        this.credentialsSalt = credentialsSalt;
    }


    public PrincipalCollection getPrincipals() {
        return principals;
    }


    public void setPrincipals(PrincipalCollection principals) {
        this.principals = principals;
    }

    public Object getCredentials() {
        return credentials;
    }


    public void setCredentials(Object credentials) {
        this.credentials = credentials;
    }


    public ByteSource getCredentialsSalt() {
        return credentialsSalt;
    }


    public void setCredentialsSalt(ByteSource salt) {
        this.credentialsSalt = salt;
    }


    @SuppressWarnings("unchecked")
    public void merge(AuthenticationInfo info) {
        if (info == null || info.getPrincipals() == null || info.getPrincipals().isEmpty()) {
            return;
        }

        if (this.principals == null) {
            this.principals = info.getPrincipals();
        } else {
            if (!(this.principals instanceof MutablePrincipalCollection)) {
                this.principals = new SimplePrincipalCollection(this.principals);
            }
            ((MutablePrincipalCollection) this.principals).addAll(info.getPrincipals());
        }

        //only mess with a salt value if we don't have one yet.  It doesn't make sense
        //to merge salt values from different realms because a salt is used only within
        //the realm's credential matching process.  But if the current instance's salt
        //is null, then it can't hurt to pull in a non-null value if one exists.
        //
        //since 1.1:
        if (this.credentialsSalt == null && info instanceof SaltedAuthenticationInfo) {
            this.credentialsSalt = ((SaltedAuthenticationInfo) info).getCredentialsSalt();
        }

        Object thisCredentials = getCredentials();
        Object otherCredentials = info.getCredentials();

        if (otherCredentials == null) {
            return;
        }

        if (thisCredentials == null) {
            this.credentials = otherCredentials;
            return;
        }

        if (!(thisCredentials instanceof Collection)) {
            Set newSet = new HashSet();
            newSet.add(thisCredentials);
            setCredentials(newSet);
        }

        // At this point, the credentials should be a collection
        Collection credentialCollection = (Collection) getCredentials();
        if (otherCredentials instanceof Collection) {
            credentialCollection.addAll((Collection) otherCredentials);
        } else {
            credentialCollection.add(otherCredentials);
        }
    }


    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof SimpleAuthenticationInfo)) return false;

        CustomSimpleAuthenticationInfo that = (CustomSimpleAuthenticationInfo) o;

        //noinspection RedundantIfStatement
        if (principals != null ? !principals.equals(that.principals) : that.principals != null) return false;

        return true;
    }


    public int hashCode() {
        return (principals != null ? principals.hashCode() : 0);
    }


    public String toString() {
        return principals.toString();
    }

3)然后就是进行调用

 return new CustomSimpleAuthenticationInfo(admin.getId(), list, admin.getPsd(), this.getClass().getName());

4)之后你在调用subject.getPrincipal()返回的都是同一个值 也就是id,也就是CustomSimpleAuthenticationInfo(admin.getId(), list, admin.getPsd(), this.getClass().getName())的第一个参数。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

关于shiro的 subject.getPrincipal()方法 的相关文章

  • ShiroFilter设计原理与实现

    Shiro提供了与Web集成的支持 其通过一个ShiroFilter入口来拦截需要安全控制的URL 然后进行相应的控制 ShiroFilter类似于如Strut2 SpringMVC这种web框架的前端控制器 其是安全控制的入口点 其负责读
  • SpringBoot整合shiro-spring-boot-web-starter启动报错

    最近在做一个SpringBoot整合常用框架的系统 在整合Shiro时启动就报错 现将解决办法总结如下 SpringBoot使用的是最新的2 3 4版本 Shiro使用的是shiro spring boot web starter1 6 0
  • Shiro实战学习笔记(2)-自定义Realm

    1 自定义realm package org tzb realm import org apache shiro authc AuthenticationException import org apache shiro authc Aut
  • Shiro之@RequiresPermissions注解原理详解

    前言 shiro为我们提供了几个权限注解 如下图 这几个注解原理都类似 这里我们讲解 RequiresPermissions的原理 铺垫 第一 首先要清楚 RequiresPermissions的基本用法 就是在Controller的方法里
  • Shiro权限框架-限制密码重试次数(8)

    1 实现原理 保证原子性 单系统 AtomicLong计数 集群系统 RedissionClient提供的RAtomicLong计数 1 获取系统中是否已有登录次数缓存 缓存对象结构预期为 用户名 登录次数 2 如果之前没有登录缓存 则创建
  • Shiro学习小记--身份验证得到principals

    项目使用shiro进行权限管理 Shiro国内目前资料极少 学习时完全就是根据张开涛的 跟我学Shiro 自己去摸索的 慢慢的开始入门 Shiro中有一个概念是principals 解释如下 principals 身份 即主体的标识属性 可
  • shiro多项目跳转用户身份失效问题排查

    shiro多项目跳转用户身份失效问题排查 1 身份失效问题 最近在项目中遇到过一个问题 统一登录系统中有各个子系统的模块 可点击子系统模块进行跳转 如下图所示 如上图 当用户点击子系统B新窗口打开时 实现跳转成功 当再回到原统一登录系统页面
  • SpringBoot 整合 Shiro 常见配置

    目录 一 Shiro 基础解释 过滤器 AOP 实现安全认证权限管理逻辑 了解 Shiro 的组织架构 二 SpringBoot 整合 Shiro 1 在项目中使用 Shiro 需要配置的地方 2 代码示例 引入依赖 请求接口 自定义 Re
  • shiro权限管理

    shiro ssm maven实现的权限管理 里面包含数据库文件 演示地址 登录 后台管理 包含角色管理 管理员可以对每个角色进行菜单分配 菜单管理 可以添加菜单 有子父级 用户管理 操作日志 系统日志 系统监控 在此基础上二次开发简直完美
  • Shiro权限框架-在线并发登录人数控制(9)

    1 实现原理 在实际开发中 我们可能会遇到这样的需求 一个账号只允许同时一个在线 当账号在其他地方登陆的时候 会踢出前面登陆的账号 那我们怎么实现 自定义过滤器 继承AccessControlFilter 使用redis队列控制账号在线数目
  • 用户登录的详细流程(二)JWT生成token登录

    JWT生成token登录 1 jwt的构成 1 header 2 payload 3 signature 2 token的登陆原理 3 在实际中如何应用token 1 设置token的生成代码 2 如何从token中获取有用的信息 3 验证
  • shiro实现基于redis的sessionDao

    shiro实现基于redis的sessionDao 将session持久化到数据库的一个关键步骤是对session对象的序列化和反序列化操作 另外在使用redis保存session时一定要设置过期时间 或在编码中检查过期并及时删除缓存 否则
  • shiro框架---关于用户登录退出接口的介绍

    接上一篇文章shiro框架 shiro配置用户名和密码的注意 项目已分享到GitHub上 如果需要的可以看下 springboot shiro项目Git下载地址 在我前几篇文章里有shiro配置的文件下载包 下载后里边有四个配置文件Shir
  • shiro-session-ehcache配置

    首先准备好jar包 shiro的主要四个 ehcache shiro xml 配置 首先securityManager配置 sessionManager配置
  • 无法自动装配字段:无法连接到 com.sun.proxy.$Proxy22

    Caused by org springframework beans factory BeanCreationException Could not autowire field protected com cms service Fol
  • 将 Apache Shiro 安全库与基于 Dropwizard 的 JAX-RS 应用程序集成

    我正在尝试改变 Dropwizard 以支持 Shiro 我已阅读文档并且有点困惑 我想将 Shiro 与表单登录身份验证和 Apache Shiro 注释结合使用 我认为我需要使用 Jersey Filters 来支持 Shiro 这是在
  • 非重放热可观察

    原问题 我有一个场景 我有多个IObservable我想要组合的序列Merge然后听 但是 如果其中之一产生错误 我不希望它使其他流的所有内容崩溃 也不希望重新订阅序列 这是一个 永远持久 的序列 我通过附加一个来做到这一点Retry 合并
  • 使用 ini 文件进行 Spring MVC 和 Shiro 配置

    我正在尝试使用 Spring MVC 和 Apache Shiro 建立一个环境 我正在关注 shiro apache org 中提到的文章 我在 web xml 中使用 Spring 的 DelegatingFilterProxy 作为
  • Shiro 使用 sessionId 或用户名+密码进行身份验证

    我在 Java 身份验证框架和身份验证工作流程方面没有太多经验 只有一些理论知识 因此出于教育目的 我尝试为我的 HTTP 应用程序创建这种类型的身份验证 客户端将登录名 密码发布到 login Shiro 通过给定的凭据登录用户 服务器返
  • 如何在grails shiro中使用缓存权限

    每次我打电话subject isPermitted 它向数据库发送一条sql 我怎样才能缓存它 有什么例子吗 谢谢 我阅读了 shiro grails 插件的文档 但无法解决它 数据源 hibernate cache use second

随机推荐

  • Arch 基本安装后的使用配置

    A 参考借用整理 1 Arch wiki https wiki archlinux org index php Installation guide B 注意 1 选择有很多 xff0c 可以根据自己需求来 xff0c 如速度 xff0c
  • 【IP技术】网络安全防护措施

    网络安全威胁造成的形式主要包含运用系统软件缺点或侧门 xff0c 运用网络防火墙安全隐患 xff0c 内部结构客户的泄密 泄露和毁坏 xff0c 动态口令进攻和拒绝服务式攻击等 针对该网络安全威胁 xff0c 现阶段的预防措施主要有五种 x
  • 如何搭建本地yum仓库

    一 yum简介 yum xff08 Yellow dog Updater Modified xff09 是一个在 Fedora 和 RedHat 以及 SUSE 中的 Shell 前端软件包管理器 基于 RPM 包管理 xff0c 能够从指
  • python_tweets.json (python数据挖掘入门与实践数据集下载)

    最近在看python数据挖掘入门与实践一书 xff0c 书不错 xff0c 有个不好的地方是 xff0c 书上所用的数据集 xff0c 有几个测试数据在网上非常不好找 下面几个资源是我自己整理出来的 xff0c 上传到CSDN xff0c
  • ios UILabel显示html文本

    let attrContent 61 try NSAttributedString data htmlContent options NSDocumentTypeDocumentAttribute NSHTMLTextDocumentTyp
  • 转行的辛苦

    我是2004年毕业的 xff0c 学的专业是市场营销 xff0c 毕业后来到深圳 xff0c 换了很多工作 xff0c 一直都无法找到令自己满意的工作 因为我非常喜欢计算机 xff0c 从中学到大学 xff0c 一直是班级里公认的计算机高手
  • 内存优化 和 性能优化 的总结

    从 检查内存 xff0c 减少使用 xff0c 复用 xff0c 以及及时释放几个维度去考虑 1 检查 可以ddms查看内存使用情况 xff0c 可以使用 adb shell dumpsys meminfo 查看 xff0c 也可以使用 l
  • ubuntu16.04 安装gnome经典桌面

    一直比较喜欢旧版本Ubuntu的Gnome风格的菜单栏 xff0c 在Ubuntu16 0 4中可以执行指令 xff1a sudo apt get install gnome session flashback 安装完成 xff0c 注销一
  • Gson在序列化反序列化中的TypeAdapter

    1 package waf json adatpter 2 3 import java io IOException 4 import java util ArrayList 5 import java util List 6 import
  • 技术泡妹子二:篡改百度首页,惊呆女神

    大多数网民上网的入口都是先打开百度 xff0c 然后再搜索xxx 进入 xff0c 为了给女神惊喜 xff0c 决定篡改百度首页让女神惊呆 xff0c 当然不是黑了百度 xff0c 目前没这个实力 xff0c 但是我们可以修改host文件
  • VC多线程中控制界面控件的几种方法

    转 http hi baidu com magicyang87 blog item 23bbf2fd72d6b81108244d73 html 为了保证界面的用户体验经常要把数据处理等放到子线程中进行 xff0c 然后把结果更新到主界面 x
  • 一次性打包学透 Spring

    不知从何时开始 xff0c Spring 这个词开始频繁地出现在 Java 服务端开发者的日常工作中 xff0c 很多 Java 开发者从工作的第一天开始就在使用 Spring Framework xff0c 甚至有人调侃 不会 Sprin
  • 关于产品的一些思考——写在前面的话

    自己是一个十足的Geek xff0c 喜欢使用各种新奇的东西 xff0c 包括软件 硬件 技术 xff0c 又因为自己一点点轻微的强迫症和完美主义 xff0c 在这个过程中总会有自己的一些思考 xff0c 又因为技术出身 xff0c 总会考
  • mybatis映射文件mapper.xml的写法。

    在学习mybatis的时候我们通常会在映射文件这样写 xff1a lt xml version 61 34 1 0 34 encoding 61 34 UTF 8 34 gt lt DOCTYPE mapper PUBLIC 34 myba
  • layer的弹出层的简单的例子

    如果不了级的基本的清楚官网查看api网址为 http layer layui com 我用的是iframe 如果是iframe层 layer open type 2 content 39 http sentsin com 39 这里cont
  • 左链接Column 'id' in field list is ambiguous

    如题错误如左链接Column 39 id 39 in field list is ambiguous 今天在写sm的时候 xff0c 用到两个表的联合查询出现的如下的错误 xff0c 仔细查找才发现原来两个表的id重复了 xff0c use
  • maven出现:Failed to execute goal on project ...: Could not resolve dependencies for project ...

    1 我的项目结构是一个父项目 xff0c 多个子项目目录如下 xff1a 2 我这里就举个例子 xff0c 所以应用的也就是core和domain这两个项目 3 两个项目都继承父项目 4 在模块中domain依赖于core xff0c 在c
  • EOS的CPU危机:BM的租赁模式或只是乌托邦

    摘要 xff1a 继RAM内存之后 xff0c EOS的CPU危机也爆发了 昨日 xff0c 由于BetDice和EOSBET为了保证游戏的运行 xff0c 占用了过多的主网CPU xff0c 导致用户资源紧张 xff0c 甚至无法转账 昔
  • 有关Shiro中Principal的使用

    1 定义 principal代表什么那 xff1f 如果阅读官方文档或者源码你会得到如下的定义 xff1a 解释 xff1a 1 xff09 可以是uuid 2 xff09 数据库中的主键 3 xff09 LDAP UUID或静态DN 4
  • 关于shiro的 subject.getPrincipal()方法

    1 说明 上一篇文章说明了 principal xff0c 而subject getPrincipal 是用来干嘛的 xff0c 他就是来获取你存储的principal xff0c 内部是怎么获取的那 xff0c 多个principal怎么