多了不说了,进入正题,shiro是个权限框架提供权限管理等功能,网上的教程一般都是互相抄,比如<shiro:principal property="xxx"/>这个标签,网上教程告诉你可以用来获取登录用户的任何属性,但现实中如果你这么写,并且按照开涛教程上写的登陆逻辑,肯定百分百报错,这是为什么呢?因为网上教程的登录部分一般这么写:

这是重写authorizingrealm的dogetAuthenticationinfo方法:

protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
// TODO Auto-generated method stub
String username=(String) token.getPrincipal();
User user=userService.getUserByUsername(username);
if(user==null){
throw new UnknownAccountException();
}
if(user.getUserState()==4){
throw new LockedAccountException();
}
SimpleAuthenticationInfo info=new SimpleAuthenticationInfo(
user.getUsername(),
user.getPassword(),
ByteSource.Util.bytes(user.getCredentialsSalt()),
this.getName()
);
 
return info;


网上很多教程都是这么教给大家的, 然后在controller里用:
UsernameAndPasswordToken token=new UsernameAndPasswordToken(username,password);
subject.login(token);
....
这一系列逻辑来进行登陆,登陆成功后在页面通过<shiro:principal property="username"/>来获取登录用户属性,然后你这么做了就报错了。
为什么?来看源码,源码一是一手鞋,官方文档是二手鞋,网上教程是三手鞋,鞋都穿三手了,兴许会有脚气。。。

    public SimpleAuthenticationInfo(Object principal, Object hashedCredentials, ByteSource credentialsSalt, String realmName) {
        this.principals = new SimplePrincipalCollection(principal, realmName);
        this.credentials = hashedCredentials;
        this.credentialsSalt = credentialsSalt;

}
上面是SimpleAuthenticationInfo源码的一个构造方法,这里第一个参数就是你刚才传入的用户名,第二个参数就是你传入的密码,但是方法定义中这两个参数都是Object类型,尤其是第一个principal参数,它的意义远远不止用户名那么简单,它是用户的所有认证信息集合,登陆成功后,<shiro:principal/>标签一旦有property属性,PrincipalTag类也就是标签的支持类,会从Subject的principalcollection里将principal取出,取出的就是你传入的第一个参数,如果你传了个string类型的用户名,那么你只能获取用户名。
仔细看那个this.principals=new SimplePrincipalCollection,这一行,这一行构造了一个新的对象并将引用给了principals,而principals就是principalcollection。
再来看Principal那个标签<shiro:principal property=""/>那个,打开PrincipalTag类,看到onDoStartTag方法:

    public int onDoStartTag() throws JspException {
        String strValue = null;
 
        if (getSubject() != null) {
 
            // Get the principal to print out
            Object principal;
 
            if (type == null) {
                principal = getSubject().getPrincipal();
            } else {
                principal = getPrincipalFromClassName();
            }
 
            // Get the string value of the principal
            if (principal != null) {
                if (property == null) {
                    strValue = principal.toString();
                } else {
                    strValue = getPrincipalProperty(principal, property);
                }
            }
 
        }
 
        // Print out the principal value if not null
        if (strValue != null) {
            try {
                pageContext.getOut().write(strValue);
            } catch (IOException e) {
                throw new JspTagException("Error writing [" + strValue + "] to JSP.", e);
            }
        }
 
        return SKIP_BODY;


看到那个Object principal这个方法变量了么?如果标签里没有type属性,那么就直接调用getPrincipal方法,再打开这个方法,看到subject里是这么写的:

    public Object getPrincipal() {
        return getPrimaryPrincipal(getPrincipals());


getPrincipals是获取principalcollection,getprimaryprincipal就是获取这个principalcollection的第一个元素,用的是迭代器的方式获取。具体的我不列出来了,请参见SimplePrincipalcollection的源代码。
第一个元素你最初放的是用户名,所以你可以取得这个用户名。 如果type不为空,就会去principalcollection中找和这个type类型一致的一个对象,看源码:

    private Object getPrincipalFromClassName() {
        Object principal = null;
 
        try {
            Class cls = Class.forName(type);
            principal = getSubject().getPrincipals().oneByType(cls);
        } catch (ClassNotFoundException e) {
            if (log.isErrorEnabled()) {
                log.error("Unable to find class for name [" + type + "]");
            }
        }
        return principal;


那个oneByType方法就是在principalcollection中找和type属性一致的那个类的对象,将其作为principal,如果<shiro:property/>标签有了property属性,然后用java内省机制获取bean的属性,参见getPrincipalProperty方法,因为方法体太长我就不列出了。 
所以你现在知道该怎么做了吧?
在你的realm里这么写:

List<Object> principals=new ArrayList<Object>();
principals.add(user.getUsername());
principals.add(user);
SimpleAuthenticationInfo info=new SimpleAuthenticationInfo(
principals,
user.getPassword(),
ByteSource.Util.bytes(user.getCredentialsSalt()),
this.getName()

);
构建一个list,第一个元素是用户名,第二个元素是user对象。第一个元素用来登陆,第二个元素用来获取登陆后user对象的属性。
他们到底怎么判断登陆的呢?
先参见HashedCredentialsMatcher类的这个方法,这是用来判断是否可以登录成功的方法:  
  public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) {

        Object tokenHashedCredentials = hashProvidedCredentials(token, info);
        Object accountCredentials = getCredentials(info);
        return equals(tokenHashedCredentials, accountCredentials);


其中第一个参数token就是controller里封装的token,第二个参数info就是你刚才的simpleauthenticationinfo,因为源码层次比较深所以简单点说,这个方法就是再判断两个密码是否相等,因为两个用户名肯定是相等的info的用户名是token传过来的,所以只对比密码就可以了。 
就写这么多吧,希望大家看了能有启发。

   不是我写的,是我在开发中遇到问题,特此复制别人解决办法的博客  附上 大牛的链接  http://blog.csdn.net/ccdust/article/details/52300287

关于Apache Shiro权限框架的一些使用误区的解释的更多相关文章

  1. Apache Shiro权限框架在SpringMVC+Hibernate中的应用

    在做网站开发中,用户权限必须要考虑的,权限这个东西很重要,它规定了用户在使用中能进行哪 些操作,和不能进行哪些操作:我们完全可以使用过滤器来进行权限的操作,但是有了权限框架之后,使用起来会非常的方便, ...

  2. Apache Shiro 权限框架

    分享一个视屏教程集合 http://www.tudou.com/home/konghao/item 1.Shiro Apache Shiro是一个强大且易用的Java安全框架,执行身份验证.授权.密码 ...

  3. Shiro权限框架简介

    http://blog.csdn.net/xiaoxian8023/article/details/17892041   Shiro权限框架简介 2014-01-05 23:51 3111人阅读 评论 ...

  4. (转) shiro权限框架详解06-shiro与web项目整合(上)

    http://blog.csdn.net/facekbook/article/details/54947730 shiro和web项目整合,实现类似真实项目的应用 本文中使用的项目架构是springM ...

  5. 在前后端分离的SpringBoot项目中集成Shiro权限框架

    参考[1].在前后端分离的SpringBoot项目中集成Shiro权限框架 参考[2]. Springboot + Vue + shiro 实现前后端分离.权限控制   以及跨域的问题也有涉及

  6. SpringBoot整合Apache Shiro权限验证框架

    比较常见的权限框架有两种,一种是Spring Security,另一种是Apache Shiro,两种框架各有优劣,个人感觉Shiro更容易使用,更加灵活,也更符合RABC规则,而且是java官方更推 ...

  7. Apache Shiro(安全框架)

    当前常用流行的安全框架主要有两种:一个是Apache Shiro:另一个是Springsource. 现在介绍一下apache shiro: 既然是安全框架,解决的肯定是权限的 控制.所谓权限是指:用 ...

  8. Shiro 权限框架使用总结

    我们首先了解下什么是shiro ,Shiro 是 JAVA 世界中新近出现的权限框架,较之 JAAS 和 Spring Security,Shiro 在保持强大功能的同时,还在简单性和灵活性方面拥有巨 ...

  9. shiro权限框架

    权限的组成部分:用户 资源 角色 权限 数据库关系表设计是根据自己项目需求设计的 account表role表(id,rolename)account_role(id,aid,rid)permissio ...

随机推荐

  1. 【Python3 爬虫】01_简单页面抓取

    运行平台:Winodows 10 Python版本:Python 3.4.2 IDE:Sublime text3 网络爬虫 网络爬虫,也叫网络蜘蛛(Web Spider),如果把互联网比喻成一个蜘蛛网 ...

  2. Altium Designer 10 | 常用库及部分元件名中英文对照表

    ———————————————————————————————————————————— 常用库及部分元件名中英文对照表 - - - - - - - - - - - - - - - - - - - - ...

  3. sql server 循环

    declare @i int declare @a int declare @b int set @i=0 while(@i<=20) begin set @a=@i*1000+1; set @ ...

  4. IDEA 找不到maven编译命令操作

    找到idea左上角菜单View>Tool Windows>Maven projects.

  5. nodejs 命令行获取入参

    安装:npm install yargs --save-dev Example index.js const argv = yargs.alias('n', 'name').alias('p', 'p ...

  6. FPGA+DSP SRIO通信(一)——DSP端参数设置(通道)

    FPGA+DSP SRIO通信(一)——DSP端参数设置(通道) 原创 2017年04月19日 18:56:45 标签: SRIO-C66x 1217 经过漫长的探索之后,博主发现关于TI的板子调试和 ...

  7. 迁移TFS 2012服务至新的电脑硬件

    迁移TFS 2012的时候碰到一些问题, 中文记录很少, 英文的记录也比较零散. 这里记录最直接和简单的方法. 环境: 1. 公司域环境, 所有TFS用户都是公司域帐户. 2. TFS从一台服务器转移 ...

  8. Linux学习之tune2fs

    这是Linux系统用于文件系统自检的工具. 常用选项 -l 查看文件系统信息 -c max-mount-counts 设置强制自检的挂载次数,如果开启,每挂载一次mount conut就会加1,超过次 ...

  9. Window安装Anaconda后,conda不是内部或者外部命令

    今天在安装Theano的时候,需要看一下,anaconda已经安装了哪些包.使用命令如下,在控制台,cmd回车输入即可: conda list 但是,显示出错,“conda不是内部或者外部命令”,第一 ...

  10. Spring4 MVC+Hibernate4+MySQL+Maven使用注解集成实例

    在本教程中,我们将使用基于注解的配置集成Spring和Hibernate. 我们将开发包含表单要求用户输入一个简单的CRUD为导向Web应用程序,使用Hibernate保存输入的数据到 MySQL 数 ...