Shiro详解

一、什么是Shiro

Shiro是一个强大而灵活的开源安全框架,能够非常清晰的处理认证、授权、管理会话以及密码加密。

特点:

简单的身份认证(登录),

支持多种数据源(LDAP,JDBC,Kerberos,ActiveDirectory 等);

对角色的简单的授权控制,支持细粒度的签权;

支持一级缓存,以提升应用程序的性能;

内置的基于 POJO 企业会话管理,适用于 Web 以及非 Web 的环境;

不跟任何的框架或者容器捆绑,可以独立运行。  

Spring Security 目前是 Java安全框架领域当之无愧的老大,已经非常成熟了;如果使用 Spring框架,可以首选 Spring Security,但是对于单应用来说,Shiro更显简单方便。

 二、Shiro的架构介绍 

首先,来了解一下Shiro的三个核心组件:Subject,SecurityManager 和 Realms. 如下图:

   

Subject:即“当前操作用户”。但是,在Shiro中,Subject这一概念并不仅仅指人,也可以是第三方进程、后台帐户(DaemonAccount)或其他类似事物。它仅仅意味着“当前跟软件交互的东西”。但考虑到大多数目的和用途,你可以把它认为是Shiro的“用户”概念。 

Subject代表了当前用户的安全操作,SecurityManager则管理所有用户的安全操作。   

SecurityManager:它是Shiro框架的核心,这是一个 Façade接口,=Authenticator+ Authorizer +SessionFactory,Shiro通过SecurityManager来管理内部组件,并通过它来提供安全管理的各种服务。   

Realm:Realm充当了Shiro与应用安全数据间的“桥梁”。也就是说,当对用户执行认证(登录)和授权(访问控制)验证时,Shiro会从应用配置的Realm中查找用户及其权限信息。 

从这个意义上讲,Realm实质上是一个安全相关的DAO:它封装了数据源的连接细节,并在需要时将相关数据提供给Shiro。

所以在配置Shiro时,你必须至少指定一个Realm,用于认证和(或)授权。Shiro内置了可以连接大量安全数据源的Realm,如LDAP、关系数据库(JDBC)、类似INI的文本配置资源以及属性文件等。如果缺省的Realm不能满足需求,你还可以插入代表自定义数据源的自己的Realm实现。 

以常用的JdbcRealm 为例,其继承链如下:      

Shiro完整架构图:     

除前文所讲Subject、SecurityManager、Realm三个核心组件外,Shiro主要组件还包括: 

Authenticator :认证

认证就是核实用户身份的过程。对“Whoare you ?”进行核实。通常涉及用户名和密码。 这个组件负责收集principals 和 credentials,并将它们提交给应用系统。如果提交的 credentials 跟应用系统中提供的 credentials吻合,就能够继续访问,否则需要重新提交 principals 和 credentials,或者直接终止访问。  

Authorizer :授权

授权实质上就是访问控制。身份份验证通过后,由这个组件控制用户能够访问应用中的哪些内容,比如资源、Web页面等等。  Shiro采用“基于 Realm”的方法,即用户(又称 Subject)、用户组、角色和 permission 的聚合体。  

SessionManager:

Shiro为任何应用提供了一个会话编程范式,保证了独立性,对容器没有依赖。所以,对于使用会话的应用开发来说,不必被迫使用Servlet或EJB容器了。或者,如果正在使用这些容器,现在也可以选择在任何层统一一致的使用会话API,取代Servlet或EJB机制。   

CacheManager:

对Shiro的其他组件提供缓存支持。

实现流程:

1、配置Web.xml 

<!-- Shiro filter-->
<!-- 这里filter-name必须对应applicationContext.xml中定义的<beanid="shiroFilter"/> -->
<!-- 使用DelegatingFilterProxy时不需要配置任何参数,spring会根据filter-name的名字来查找bean,所以这里spring会查找id为springFilter的bean -->
<filter>
    <filter-name>shiroFilter</filter-name>
    <filter-class>
        org.springframework.web.filter.DelegatingFilterProxy
    </filter-class>
    <init-param>
        <!--该值缺省为false,表示生命周期由SpringApplicationContext管理,设置为true则表示由ServletContainer管理-->
        <param-name>targetFilterLifecycle</param-name>
        <param-value>true</param-value>
    </init-param>
</filter>

<filter-mapping>
    <filter-name>shiroFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

2、配置SecurityManager

<!--shiro securityManager -->
<!--Shiro默认会使用Servlet容器的Session,可通过sessionMode属性来指定使用Shiro原生Session -->
<!-- 即<propertyname="sessionMode" value="native"/>,详细说明见官方文档-->
<!--这里主要是设置自定义的单Realm应用,若有多个Realm,可使用'realms'属性代替 -->
<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
    <property name="realm" ref="shiroDbRealm"/>
    <!--<property name="cacheManager"ref="myShiroEhcacheManager" /> -->
    <!-- <property name="sessionMode" value="native"/>
     <property name="sessionManager" ref="sessionManager"/>
    -->
</bean>

<!-- 用户授权信息Cache,采用EhCache -->
<bean id="myShiroEhcacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager">
    <property name="cacheManagerConfigFile" value="classpath:ehcache-shiro.xml"/>
</bean>

<!--继承自AuthorizingRealm的自定义Realm,即指定Shiro验证用户的认证和授权 -->
<bean id="shiroDbRealm" class="org.shiro.demo.service.realm.ShiroDbRealm" depends-on="baseService">
    <property name="userService" ref="userService"/>
</bean>

3、配置URL过滤器

<!-- Shiro主过滤器本身功能十分强大,其强大之处就在于它支持任何基于URL路径表达式的、自定义的过滤器的执行-->
<!-- Shiro Filter -->
<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
    <!-- Shiro的核心安全接口,这个属性是必须的 -->
    <property name="securityManager" ref="securityManager" />
    <!-- 要求登录时的链接,非必须的属性,默认会自动寻找Web工程根目录下的"/login.jsp"页面-->
    <property name="loginUrl" value="/" />
    <!--登录成功后要跳转的连接(本例中此属性用不到,因为登录成功后的处理逻辑在LoginController里硬编码为main.jsp了) -->
    <property name="successUrl" value="/system/main" />
    <!-- 用户访问未对其授权的资源时,所显示的连接 -->
    <property name="unauthorizedUrl" value="/system/error" />
    <!-- Shiro 过滤链的定义-->
    <!--此处可配合这篇文章来理解各个过滤连的作用http://blog.csdn.net/jadyer/article/details/12172839-->
    <!--下面value值的第一个'/'代表的路径是相对于HttpServletRequest.getContextPath()的值来的 -->
    <!--anon:它对应的过滤器里面是空的,什么都没做,这里.do和.jsp后面的*表示参数,比方说login.jsp?main这种 -->
    <!--authc:该过滤器下的页面必须验证后才能访问,它是Shiro内置的一个拦截器org.apache.shiro.web.filter.authc.FormAuthenticationFilter-->
    <property name="filterChainDefinitions">
        <value>
            /login = anon
            /validateCode = anon
            /** = authc
        </value>
    </property>
</bean>

4、开启shiro注解

<!-- 保证实现了Shiro内部lifecycle函数的bean执行 -->
<bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>

<!--开启Shiro的注解,实现对Controller的方法级权限检查(如@RequiresRoles,@RequiresPermissions),需借助SpringAOP扫描使用Shiro注解的类,并在必要时进行安全逻辑验证-->
<!--配置以下两个bean即可实现此功能 -->
<!--Enable Shiro Annotations for Spring-configured beans. Only run after thelifecycleBeanProcessor has run -->
<bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator" depends-on="lifecycleBeanPostProcessor" >
    <property name="proxyTargetClass" value="true" />
</bean>

<bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
    <property name="securityManager" ref="securityManager" />
</bean>

5、在程序Service层中自定义一个Realm(用户和权限相关的DAO)

package org.shiro.demo.service.realm;

import ...

/**
 * 自定义的指定Shiro验证用户登录的类
 * @author TCH
 *
 */
public class ShiroDbRealm extends AuthorizingRealm{

    // @Resource(name="userService")
    private IUserService userService;

    public void setUserService(IUserService userService) {
        this.userService = userService;
    }
    
    /** 
     * 为当前登录的Subject授予角色和权限 
     * @see 经测试:本例中该方法的调用时机为需授权资源被访问时 
     * @see 经测试:并且每次访问需授权资源时都会执行该方法中的逻辑,这表明本例未启用AuthorizationCache 
     * @see web层可以有shiro的缓存,dao层可以配有hibernate的缓存(后面介绍)
     */ 
    protected AuthorizationInfo doGetAuthorizationInfo(
            PrincipalCollection principals) {
        
        //获取当前登录的用户名,等价于(String)principals.fromRealm(this.getName()).iterator().next()  
        String account = (String) super.getAvailablePrincipal(principals);
        
        List<String> roles = new ArrayList<String>();  
        List<String> permissions = new ArrayList<String>();
        
        //从数据库中获取当前登录用户的详细信息  
        User user = userService.getByAccount(account);
        
        if(user != null){
            //实体类User中包含有用户角色的实体类信息  
            if (user.getRoles() != null && user.getRoles().size() > 0) {
                //获取当前登录用户的角色 
                for (Role role : user.getRoles()) {
                    roles.add(role.getName());
                     //实体类Role中包含有角色权限的实体类信息  
                    if (role.getPmss() != null && role.getPmss().size() > 0) {
                         //获取权限  
                        for (Permission pmss : role.getPmss()) {
                            if(!StringUtils.isEmpty(pmss.getPermission())){
                                permissions.add(pmss.getPermission());
                            }
                        }
                    }
                }
            }
        }else{
            throw new AuthorizationException();
        }
        
        //为当前用户设置角色和权限
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.addRoles(roles);
        info.addStringPermissions(permissions); 
        
        return info;
        
    }

    /** 
     * 验证当前登录的Subject 
     * @see 经测试:本例中该方法的调用时机为LoginController.login()方法中执行Subject.login()时 
     */  
    protected AuthenticationInfo doGetAuthenticationInfo(
            AuthenticationToken authcToken) throws AuthenticationException {
        //获取基于用户名和密码的令牌  
        //实际上这个authcToken是从LoginController里面currentUser.login(token)传过来的  
        UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
        
        //从数据库中查询用户用信息
        User user = userService.getByAccount(token.getUsername());
        if (user != null) {
             //此处无需比对,比对的逻辑Shiro会做,我们只需返回一个和令牌相关的正确的验证信息  
            return new SimpleAuthenticationInfo(user.getAccount(), user
                    .getPassword(), getName());
        } else {
             //没有返回登录用户名对应的SimpleAuthenticationInfo对象时,就会在LoginController中抛出UnknownAccountException异常  
            return null;
        }
    }
}

 6、实现权限验证

代码方式验证权限:

Subject currentUser = SecurityUtils.getSubject();
//使用冒号分隔的权限表达式是org.apache.shiro.authz.permission.WildcardPermission默认支持的实现方式。 
//这里分别代表了 资源类型:操作:资源ID
if(currentUser.isPermitted("printer:print:laserjet4400n")){
        //show the Print button
        }else{
        //don't show the button?  Grey it out?
        }

基于注解的权限验证:

@RequiresAuthentication
public void updateAccount(Account userAccount) {
        //this method will only be invoked by a
        //Subject that is guaranteed authenticated
        ...
        }

@RequiresPermissions("account:create")
public void createAccount(Account account) {
        //this method will only be invoked by a Subject  
        //that is permitted to create an account  
        ...
        }

使用JSP TAG控制权限:

<%@ taglib prefix="shiro" uri="http://shiro.apache.org/tags" %>

<shiro:hasRole name="administrator">
    <a href="admin.jsp">Administer the system</a>
</shiro:hasRole>

<shiro:hasPermission name="user:create">
    <a href="createUser.jsp">Create a new User</a>
</shiro:hasPermission>

7、用户登录

@RequestMapping(value = "/login")
    public String login(User user,HttpSession session, HttpServletRequest request){
        // 判断验证码
        String code = (String) session.getAttribute("validateCode");
        String submitCode = WebUtils.getCleanParam(request, "validateCode");
        
        if (StringUtils.isEmpty(submitCode) || !StringUtils.equals(code,submitCode.toLowerCase())) {
            return "redirect:/";
        }
        
        //获取当前的Subject  
        Subject curUser = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(user.getAccount(),user.getPassword());
        token.setRememberMe(true);
        try {
             //在调用了login方法后,SecurityManager会收到AuthenticationToken,并将其发送给已配置的Realm执行必须的认证检查  
            //每个Realm都能在必要时对提交的AuthenticationTokens作出反应  
            //所以这一步在调用login(token)方法时,它会走到ShiroDbRealm.doGetAuthenticationInfo()方法中
            curUser.login(token);
            
            return "/system/main";
        }catch (AuthenticationException e) {
            //通过处理Shiro的运行时AuthenticationException就可以控制用户登录失败或密码错误时的情景
            token.clear();
            return "redirect:/";
        }
    }

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值