多了不说了,进入正题,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. PHP函数之HTMLSPECIALCHARS_DECODE

    PHP函数之htmlspecialchars_decode   htmlspecialchars_decode :将特殊的 HTML 实体转换回普通字符   htmlspecialchars: 将普通 ...

  2. Android开发之Is Library篇

    一.生活场景描述 由于公司有一个项目开发的时间比较长,项目里堆砌的代码也比较多,并且有些功能在给不同客户发布的时候有些功能还不需要,这样功能模块分离就很有必要了. 所以,Library就被推到了前台, ...

  3. 【Python3 爬虫】12_代理IP的使用

    我们在爬取页面的时候,如果长时间使用一个网址去爬取某个网站,就会受爬去限制,此时,我们引用了代理IP,IP随时在变化,也就不会被限制了 一下是国内提供免费代理IP的地址:http://www.xici ...

  4. mysql 5.6的安装

    MySQL安装   yum install -y perl-Module-Install.noarch cd /usr/local/src wget http://mirrors.sohu.com/m ...

  5. html 5 中的 6位 十六进制颜色码 代表的意思180313

    人的眼睛看到的颜色有两种: ⒈ 一种是发光体发出的颜色,比如计算机显示器屏幕显示的颜色: ⒉ 另一种是物体本身不发光,而是反射的光产生   的颜色,比如看报纸和杂志上的颜色. 我们又知道任何颜色都是由 ...

  6. 你应该将应用迁移到Spring 4的五个原因

    本文来源于我在InfoQ中文站翻译的文章,原文地址是:http://www.infoq.com/cn/news/2015/12/five-reasons-to-migrate-spring4 Rafa ...

  7. ajaxform 提交,返回JSON时,IE提示下载的问题解决

    在使用AJAXform提交表单时,返回的数据格式为JSON,头文件是application/json 时,在 火狐.ie9和谷歌下都能正常解析,在ie7下会提示下载. 解决方法:指定返回页的头文件为& ...

  8. SpringCloud系列十:使用Feign实现声明式REST调用

    1. 回顾 前文的示例中是使用RestTemplate实现REST API调用的,代码大致如下: @GetMapping("/user/{id}") public User fin ...

  9. windows下使用python2.7.6 安装django

    1) 安装python2.7.6 2) 由于 python2.7.6 中没有安装setuptools,需要先从官网下载setuptools,下载zip包然后解压,运行 python setup.py ...

  10. js中级系列三:前端性能优化

    原文链接:http://www.cnblogs.com/xxcanghai/p/5205998.html 链接:http://www.zhihu.com/question/21658448/answe ...