java开发之shiro

来源:互联网 发布:淘宝天猫怎么申请 编辑:程序博客网 时间:2024/06/05 05:11

在我们开发项目的过程中,一般对于请求会做过滤,有些页面或者数据在没有权限的时候是不允许随意访问的。以前呢,我的理解是会用Filter来对请求做过滤,然后做权限检查。然而,在开发项目的时候,发现dalao做好了这个用户登录的模块,我却找不到Filter。最后定为到shiro,说实话看着挺懵,但是慢慢研究发现确实好用。

Shiro,可以简单理解为,把系统的权限管理都交给他来处理。管理过程我们就可以忽略的,权限验证我们重写它定义好的回调方法写下怎么算验证通过,通过这种方式做权限验证。
大家可以参考http://jinnianshilongnian.iteye.com/blog/2018936/做一个初步了解,看完前两章基本就个大概概念了。

现在只简单聊聊怎么使用,因为深挖是有很多内容的,后面有时间再了解。
1、在maven中依赖shiro

<!-- shiro相关 -->    <dependency>          <groupId>junit</groupId>          <artifactId>junit</artifactId>          <version>4.9</version>      </dependency>      <dependency>          <groupId>commons-logging</groupId>          <artifactId>commons-logging</artifactId>          <version>1.1.3</version>      </dependency>      <dependency>      <groupId>org.apache.shiro</groupId>      <artifactId>shiro-core</artifactId>      <version>${shiro.version}</version>    </dependency>    <dependency>      <groupId>org.apache.shiro</groupId>      <artifactId>shiro-web</artifactId>      <version>${shiro.version}</version>    </dependency>    <dependency>      <groupId>org.apache.shiro</groupId>      <artifactId>shiro-spring</artifactId>      <version>${shiro.version}</version>    </dependency>     <dependency>      <groupId>org.apache.shiro</groupId>      <artifactId>shiro-ehcache</artifactId>      <version>${shiro.version}</version>    </dependency>

很明显有个shiro核心包,shiro-spring对接包,shiro-ehcache缓存包

2.然后在src/main/resource下提供spring-shiro.xml

<beans xmlns="http://www.springframework.org/schema/beans"    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"    xmlns:context="http://www.springframework.org/schema/context"    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"    xsi:schemaLocation="http://www.springframework.org/schema/beans         http://www.springframework.org/schema/beans/spring-beans.xsd         http://www.springframework.org/schema/mvc         http://www.springframework.org/schema/mvc/spring-mvc.xsd         http://www.springframework.org/schema/context         http://www.springframework.org/schema/context/spring-context.xsd         http://www.springframework.org/schema/aop         http://www.springframework.org/schema/aop/spring-aop.xsd         http://www.springframework.org/schema/tx         http://www.springframework.org/schema/tx/spring-tx.xsd ">    <!-- 配置shiroFilter,它是一个工厂,可以生产很多过滤器 -->    <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">        <!-- 安全管理器 -->        <property name="securityManager" ref="securityManager"></property>        <!-- loginUrl认证提交地址,如果没有认证将会请求此地址认证,请求此地址将由authc进行表单认证,如果不配置loginUrl,默认使用/login.jsp,            强调:当请求/login.action时,由anthc拦截后并且进行认证,login.action必须要提交账号和密码authc方可认证 -->        <property name="loginUrl" value="/login" />        <!-- 认证成功后统一跳转到index.jsp,建议不配置,shiro认证成功后自动到上一个路径 -->        <!--<property name="successUrl" value="/pages/home.jsp"></property>-->        <!-- 没有权限跳转的地址 -->          <property name="unauthorizedUrl" value="/refuse.jsp" />          <!-- 自定义filter配置,将自定义 的FormAuthenticationFilter注入shiroFilter中 -->        <!--  <property name="filters">              <map>                  <entry key="authc" value-ref="formAuthenticationFilter" />              </map>          </property>  -->          <!-- 过虑器链定义,从上向下顺序执行,最上边配置anon匿名过虑器一般将/** = authc放在最下边 -->        <property name="filterChainDefinitions">            <value>                <!-- 对静态资源设置匿名访问 -->                /myres/** = anon                <!-- 登陆提交 -->                /login = anon                <!-- 退出拦截,请求logout.mv执行退出操作 -->                /logout = logout                <!-- /** = authc 所有url都必须认证通过才可以访问 -->                /** = authc            </value>        </property>    </bean>    <!-- 安全管理器 -->    <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">        <!--加载realm-->        <property name="realm" ref="authRealm"></property>        <!--添加缓存管理器-->        <property name="cacheManager" ref="cacheManager"></property>        <!--会话管理器-->        <!--<property name="sessionManager" ref="sessionManager"></property>-->    </bean>    <!--自定义realm-->    <bean id="authRealm" class="com.vzr.VShow.web.controller.AuthRealm">        <!-- 将凭证匹配器设置到realm中,realm按照凭证匹配器的要求进行散列 realm从数据库查询md5加密后的密码,需要将明文按照md5加密,将md5的凭证匹配器credentialsMatcher注入给realm -->        <!--<property name="credentialsMatcher" ref="credentialsMatcher"></property>-->    </bean>    <!--凭证匹配器-->    <bean id="credentialsMatcher" class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">        <!--指定散列算法为MD5-->        <property name="hashAlgorithmName" value="md5"></property>    </bean>    <!--缓存管理器-->    <bean id="cacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager">        <property name="cacheManagerConfigFile" value="classpath:shiro-ehcache.xml"></property>    </bean>    <!--会话管理器-->    <bean id="sessionManager" class="org.apache.shiro.web.session.mgt.DefaultWebSessionManager">        <!--session的失效时长,单位为毫秒-->        <property name="globalSessionTimeout" value="1800000"></property>        <!--删除失效的session-->        <property name="deleteInvalidSessions" value="true"></property>        <!--更改默认的JSESSIONID标识为sid,避免shiro的session和普通的session冲突-->        <property name="sessionIdCookie.name" value="sid"></property>    </bean></beans>

这里面需要配置的一些内容是:
1> loginUrl,当发现没有登录的时候会跳转到这里,比如我配置了/login,到时候就会跳转ip:port/login
2> unauthorizedUrl类似
3> 然后比较重要的是filterChainDefinitions,从字面上看,它就是一堆filter,形成了链条,依次做过滤。它定义了过滤的顺序和规则,我们简单用下,/myres/** = anon代表这些资源是可以随意访问的,/logout = logout绑定了/logout为退出操作,此时会让session失效, /** = authc表示其他都需要权限过滤
4>authRealm就是前面所说需要重写shiro的回调方法的类,告诉shiro怎么算验证通过
5>cacheManager指定缓存类即配置,会用到shiro-ehcache.xml。

3.同样添加shiro-ehcache.xml

<?xml version="1.1" encoding="UTF-8"?><ehcache name="shirocache">    <diskStore path="java.io.tmpdir"/>     <defaultCache         maxElementsInMemory="2000"        eternal="true"        timeToIdleSeconds="120"        timeToLiveSeconds="120"        overflowToDisk="true"/>    <cache name="passwordRetryCache"           maxElementsInMemory="2000"           eternal="false"           timeToIdleSeconds="300"           timeToLiveSeconds="0"           overflowToDisk="false">    </cache>    <cache name="authorizationCache"           maxElementsInMemory="2000"           eternal="false"           timeToIdleSeconds="1800"           timeToLiveSeconds="0"           overflowToDisk="false">    </cache>    <cache name="authenticationCache"           maxElementsInMemory="2000"           eternal="false"           timeToIdleSeconds="1800"           timeToLiveSeconds="0"           overflowToDisk="false">    </cache>    <cache name="shiro-activeSessionCache"           maxElementsInMemory="2000"           eternal="false"           timeToIdleSeconds="1800"           timeToLiveSeconds="0"           overflowToDisk="false">    </cache></ehcache>

从字面上也不难猜出这些配置的作用。

4.让配置生效,同样也是通过定义spring的bean,方式是一样的。
web.xml的这个配置会让其生效

<context-param>        <param-name>contextConfigLocation</param-name>        <param-value>            classpath:spring-*.xml;        </param-value>    </context-param>

5.使用方法。由于看起来采用的是托管方式,所以呢,我们在页面登录的时候,同时提交给shiro做一次登录。

// 调用工具类得到与当前线程绑定的用户(模拟用户)        Subject subject = SecurityUtils.getSubject();        // 提供token令牌进行认证        UsernamePasswordToken token = new UsernamePasswordToken(company.getAccount(),                MD5Tools.MD5(company.getPassword()));        subject.login(token);

并把登录信息保存到shiro,也就是这个token,当用户发起一个请求时,通过前面说的filter链条开始过滤,如果声明为anon的资源直接放行不管,如果声明为authc的资源,shiro就会做登录验证,依据就是这个token。如果声明为logout的资源,那shiro就会释放这个token,这个时候再请求资源时会被认定为未登录状态。同时shiro对会话还有管理,比如一段时间后失效等。

6.shiro通过我们自定义的AuthRealm完成验证。简单点用

package com.vzr.VShow.web.controller;import org.apache.shiro.authc.AuthenticationException;import org.apache.shiro.authc.AuthenticationInfo;import org.apache.shiro.authc.AuthenticationToken;import org.apache.shiro.authc.IncorrectCredentialsException;import org.apache.shiro.authc.SimpleAuthenticationInfo;import org.apache.shiro.authc.UnknownAccountException;import org.apache.shiro.authz.AuthorizationInfo;import org.apache.shiro.realm.AuthorizingRealm;import org.apache.shiro.subject.PrincipalCollection;import org.springframework.beans.factory.annotation.Autowired;import com.vzr.VShow.model.Company;import com.vzr.VShow.service.CompanyService;/** *  * 自定义realm * @author Administrator * */public class AuthRealm extends AuthorizingRealm {    @Autowired    private CompanyService companyService;    //身份认证    @Override    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {        //获取token中的账号        String account = (String) token.getPrincipal();        String password = new String((char[])token.getCredentials()); //得到密码          //根据账号查询用户        Company company = companyService.findCompanyByAccount(account);        if(company == null) {            throw new UnknownAccountException(); //如果用户名错误         }        if(!company.getPassword().equals(password)) {              throw new IncorrectCredentialsException(); //如果密码错误          }          //如果身份认证验证成功,返回一个AuthenticationInfo实现;          return new SimpleAuthenticationInfo(company, password, getName());    }    //授权认证    @Override    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {        return null;    }}

到此,简单的使用shiro做登录验证就完成了。

原创粉丝点击