Shiro与Spring整合

1.导入jar包

与shiro相关的jar包

这里写图片描述

2.web.xml的配置

在web系统中,shiro也通过filter进行拦截。filter拦截后将操作权交给spring中配置的filterChain(过滤链儿)shiro提供很多filter。

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    id="WebApp_ID" version="2.5">
    <display-name>Shiro-Spring</display-name>
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring/applicationContext-*.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <!-- springmvc的前端控制器 -->
    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring/springmvc.xml</param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>*.action</url-pattern>
    </servlet-mapping>
    <!-- shiro的filter -->
    <filter>
        <filter-name>shiroFilter</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
        <!-- 设置true由servlet容器控制filter的生命周期 -->
        <init-param>
            <param-name>targetFilterLifecycle</param-name>
            <param-value>true</param-value>
        </init-param>
        <!-- 设置spring容器中filter的bean id,如果不设置则找与filter-name一致的bean -->
        <init-param>
            <param-name>targetBeanName</param-name>
            <param-value>shiroFilter</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>shiroFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <!-- 解决post乱码 -->
    <filter>
        <filter-name>characterEncodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>utf-8</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>characterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
        <welcome-file>index.htm</welcome-file>
        <welcome-file>index.jsp</welcome-file>
        <welcome-file>default.html</welcome-file>
        <welcome-file>default.htm</welcome-file>
        <welcome-file>default.jsp</welcome-file>
    </welcome-file-list>
</web-app>

3.配置applicationContext-shiro.xml

在applicationContext-shiro.xml 中配置web.xml中fitler对应spring容器中的bean。

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
    http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
    http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">
    <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
        <property name="securityManager" ref="securityManager"></property>
        <!--loginUrl认证提交地址,如果没有认证将会请求此地址,请求此地址将由formAuthenticationFilter进行表单验证 -->
        <property name="loginUrl" value="/login.action" />
        <!-- 认证成功统一跳转到的页面,建议不配置,shiro认证成功后自动跳转到上一个请求路径 -->
        <property name="successUrl" value="/welcome.action" />
        <!--通过unauthorizedUrl指定,当没有权限时跳转的页面 -->
        <property name="unauthorizedUrl" value="/refuse.jsp" />
        <!-- 自定义filter配置 -->
        <property name="filters">
            <map>
                <entry key="authc" value-ref="formAuthenticationFilter"></entry>
            </map>
        </property>
        <!-- 过滤链定义,从上向下执行,一般将/**放在最下面 -->
        <property name="filterChainDefinitions">
            <value>
                <!-- 对静态资源设置匿名访问 -->
                /images/** = anon
                /js/** = anon
                /images/** = anon
                <!-- /item/query.action = perms["item:query,item:update"] -->
                <!-- 请求 logout.action地址,shiro去清除session -->
                /logout.action = logout
                /anon.action = anon
                <!--配置记住我或认证通过后可以访问的url  -->
                /welcome.action = user
                /** = authc
            </value>
        </property>
    </bean>
    <!-- 配置SecurityManager -->
    <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
        <property name="realm" ref="customRealm"></property>
        <property name="cacheManager" ref="cacheManager"></property>
        <!-- <property name="sessionManager" ref="sessionManager"></property> -->
        <property name="rememberMeManager" ref="rememberMeManager"></property>
    </bean>
    <!-- 配置自定义的realm -->
    <bean id="customRealm" class="com.ak.shiro.CustomRealm">
        <property name="credentialsMatcher" ref="credentialsMatcher"></property>
    </bean>
    <!-- 配置凭证匹配器,注入md5算法和散列次数 -->
    <bean id="credentialsMatcher"
        class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
        <property name="hashAlgorithmName" value="md5"></property>
        <property name="hashIterations" value="1"></property>
    </bean>
    <!-- 配置缓存 cacheManager -->
    <bean id="cacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager">
        <property name="cacheManagerConfigFile" value="classpath:shiro/shiro-ehcache.xml"></property>
    </bean>
    <!-- 配置sessionManager -->
    <bean id="sessionManager" class="org.apache.shiro.web.session.mgt.DefaultWebSessionManager">
        <!-- 设置失效时长  单位毫秒--> 
        <property name="globalSessionTimeout" value="20000"></property> 
        <!-- 删除失效的session -->
        <property name="deleteInvalidSessions" value="true"></property>
     </bean>
    <!-- 配置自定义的form认证过滤器  不配置也会注册FormAuthenticationFilter,不过采用默认值-->
    <bean id="formAuthenticationFilter" class="com.ak.shiro.MyFormAuthenticationFilter">
        <!--表单中帐号对应input的name  -->
        <property name="usernameParam" value="username"></property>
        <!--表单中密码对应input的name  -->
        <property name="passwordParam" value="password"></property>
        <!--表单中记住我对应input的name  -->
        <property name="rememberMeParam" value="rememberMe"></property>
    </bean>
    <!-- 配置rememberMeManager -->
    <bean id="rememberMeManager" class="org.apache.shiro.web.mgt.CookieRememberMeManager">
        <property name="cookie" ref="rememberMeCookie"></property>
    </bean>
    <!--记住我cookie -->
    <bean id="rememberMeCookie" class="org.apache.shiro.web.servlet.SimpleCookie">
        <!--设置cookie的名字 -->
        <constructor-arg value="rememberMe" />
        <!-- 设置缓存的有效时间 单位:秒 -->
        <property name="maxAge" value="2592000"></property>
    </bean>
</beans>

注意:shiro中successUrl不跳转问题

  默认情况下,shiro认证成功后自动跳转到上一个请求路径。不跳转的主要原因是successUrl配置只是做为一种附加配置,只有session中没有用户请求地址时才会使用successUrl。即使设置了successUrl,当认证前存在访问路径,则认证后跳转的还是上一个访问路径。要想看到successUrl跳转效果,可以在停留表单页面时,清空浏览器缓存,再实现认证。

4.认证

4.1 FormAuthenticationFilter过虑器原理

使用FormAuthenticationFilter过虑器实现 ,原理如下:
  将用户没有认证时,请求任意url时,都会跳转到loginUrl中设置的url。
此时只是跳转,不会调用realm进行认证。
这里写图片描述

这里写图片描述
  当浏览器请求loginUrl对应的url时,会进行认证,用户身份和用户密码提交数据到loginurl。
FormAuthenticationFilter拦截住取出request中的username和password(默认的,两个参数名称是可以配置的)。
FormAuthenticationFilter调用realm传入一个token(username和password)。
realm认证时根据username查询用户信息。
如果查询不到,realm返回null,FormAuthenticationFilter向request域中自动填充一个参数(记录了异常信息)。取该参数(shiroLoginFailure是固定的):
String exceptionClassName =(String) request.getAttribute("shiroLoginFailure");

4.2 登录代码

//登录提交地址必须和loginUrl中的值一致
    @RequestMapping("/login")
    public String login(HttpServletRequest request){
        //如果登录失败,就从request域中取认证异常信息,shiroLoginFailure就是shiro异常类的全限定类名
        String exceptionClassName =(String) request.getAttribute("shiroLoginFailure");
        //根据shiro返回的异常路径判断
        if(exceptionClassName!=null){
            if(UnknownAccountException.class.getName().equals(exceptionClassName)){
                throw new RuntimeException("帐号不存在");
            }else if(IncorrectCredentialsException.class.getName().equals(exceptionClassName)){
                throw new RuntimeException("帐号或密码错误");
            }else if("randomCodeError".equals(exceptionClassName)){
                throw new RuntimeException("验证码错误");
            }
        }
        //此方法不处理认证成功,认证成功shiro会自动跳转到上一个请求路径
        //实际开发中,认证失败应回到登录页面
        return "login";
    }

4.3 设置凭证匹配器

  数据库中存储到的md5的散列值,在realm中需要设置数据库中的散列值它使用散列算法及散列次数,让shiro进行散列对比时和原始数据库中的散列值使用的算法 一致。
这里写图片描述

4.4 利用LogoutFilter实现退出

  不用我们去实现退出,只要去访问一个退出的url(该 url是可以不存在),由LogoutFilter拦截住,自动清除session。
  这里写图片描述

4.5 显示认证信息

@RequestMapping("/welcome")
    public String welcome(Model model){
        //从shiro的session中去身份信息
        Subject subject = SecurityUtils.getSubject();
        String username = (String) subject.getPrincipal();
        model.addAttribute("msg", username);
        return "welcome";
    }

5.授权

5.1 PermissionsAuthorizationFilter的使用

 在applicationContext-shiro.xml中配置url所对应的权限
流程:
1. 在applicationContext-shiro.xml中配置filter规则
  商品查询需要商品查询权限
  /items/queryItems.action = perms[item:query]
2. 用户在认证通过后,请求/items/queryItems.action
3. 被PermissionsAuthorizationFilter拦截,发现需要“item:query”权限
4. PermissionsAuthorizationFilter调用realm中的doGetAuthorizationInfo获取数据库中正确的权限
5. PermissionsAuthorizationFilter对item:query 和从realm中获取权限进行对比,如果“item:query”在realm返回的权限列表中,授权通过。

如果授权失败,跳转到refuse.jsp,需要在spring容器中配置:
这里写图片描述

5.2 使用注解式授权方法

开启controller类的aop支持
对系统中类的方法给用户授权,建议在controller层进行方法授权。
springmvc.xml中加入如下代码:

<!-- 开启aop,对类进行代理 -->
    <aop:config expose-proxy="true"></aop:config>
    <!-- 开启shiro注解支持,可以在controller方法中使用注解进行权限配置 -->
    <bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
        <property name="securityManager" ref="securityManager"></property>
    </bean>

在controller方法中添加注解

@RequiresPermissions("item:query")
    @RequestMapping("/item/query")
    public String itemQuery(Model model){
        model.addAttribute("item", "大西瓜");
        return "showItem";
    }

5.3 使用jsp标签授权方法

Jsp页面添加:
<%@ tagliburi="http://shiro.apache.org/tags" prefix="shiro" %>

标签名称    标签条件(均是显示标签内容)
<shiro:authenticated>   登录之后
<shiro:notAuthenticated>    不在登录状态时
<shiro:guest>   用户在没有RememberMe时
<shiro:user>    用户在RememberMe时
<shiro:hasAnyRoles name="abc,123" > 在有abc或者123角色时
<shiro:hasRole name="abc">  拥有角色abc
<shiro:lacksRole name="abc">    没有角色abc
<shiro:hasPermission name="abc">    拥有权限资源abc
<shiro:lacksPermission name="abc">  没有abc权限资源
<shiro:principal>   显示用户身份名称
 <shiro:principal property="username"/>     显示用户身份中的属性值

这里写图片描述

注解、jsp授权原理

当调用controller的一个方法,由于该方法加了@RequiresPermissions("item:query") ,shiro调用realm
获取数据库中的权限信息,看"item:query"是否在权限数据中存在,如果不存在就拒绝访问,如果存在就授权通过。

当展示一个jsp页面时,页面中如果遇到<shiro:hasPermission name="item:update">,shiro调用realm
获取数据库中的权限信息,看item:update是否在权限数据中存在,如果不存在就拒绝访问,如果存在就授权通过。

问题:只要遇到注解或jsp标签的授权,都会调用realm方法查询数据库,需要使用缓存解决此问题。

6.shiro过滤器

过滤器简称       对应的java类
anon          org.apache.shiro.web.filter.authc.AnonymousFilter
authc         org.apache.shiro.web.filter.authc.FormAuthenticationFilter
authcBasic    org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter   
perms         org.apache.shiro.web.filter.authz.PermissionsAuthorizationFilter
port          org.apache.shiro.web.filter.authz.PortFilter
rest          org.apache.shiro.web.filter.authz.HttpMethodPermissionFilter
roles         org.apache.shiro.web.filter.authz.RolesAuthorizationFilter  
ssl           org.apache.shiro.web.filter.authz.SslFilter
user          org.apache.shiro.web.filter.authc.UserFilter
logout        org.apache.shiro.web.filter.authc.LogoutFilter
anon:例子/admins/**=anon 没有参数,表示可以匿名使用。
authc:例如/admins/user/**=authc表示需要认证(登录)才能使用,FormAuthenticationFilter是表单认证,没有参数 
roles:例子/admins/user/**=roles[admin],参数可以写多个,多个时必须加上引号,并且参数之间用逗号分割,当有多个参数时,例如admins/user/**=roles["admin,guest"],每个参数通过才算通过,相当于hasAllRoles()方法。
perms:例子/admins/user/**=perms[user:add:*],参数可以写多个,多个时必须加上引号,并且参数之间用逗号分割,例如/admins/user/**=perms["user:add:*,user:modify:*"],当有多个参数时必须每个参数都通过才通过,想当于isPermitedAll()方法。
rest:例子/admins/user/**=rest[user],根据请求的方法,相当于/admins/user/**=perms[user:method] ,其中method为post,get,delete等。
port:例子/admins/user/**=port[8081],当请求的url的端口不是8081是跳转到schemal://serverName:8081?queryString,其中schmal是协议http或https等,serverName是你访问的host,8081是url配置里port的端口,queryString
是你访问的url里的?后面的参数。
authcBasic:例如/admins/user/**=authcBasic没有参数表示httpBasic认证

ssl:例子/admins/user/**=ssl没有参数,表示安全的url请求,协议为https
user:例如/admins/user/**=user没有参数表示必须存在用户, 身份认证通过或通过记住我认证通过的可以访问,当登入操作时不做检查
注:
anon,authcBasic,auchc,user是认证过滤器,
perms,roles,ssl,rest,port是授权过滤器

7.shiro缓存

7.1缓存流程

shiro中提供了对认证信息和授权信息的缓存。shiro默认是关闭认证信息缓存的,对于授权信息的缓存shiro默认开启的。主要研究授权信息缓存,因为授权的数据量大。

用户认证通过。
该 用户第一次授权:调用realm查询数据库
该 用户第二次授权:不调用realm查询数据库,直接从缓存中取出授权信息(权限标识符)。

7.2 jar包

这里写图片描述

7.3 配置cacheManager

这里写图片描述
需注入到securityManager中

7.4 配置shiro-ehcache.xml

<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:noNamespaceSchemaLocation="../config/ehcache.xsd">
    <!--diskStore:缓存数据持久化的目录 地址  -->
    <diskStore path="d:\shiro\ehcache" />
    <defaultCache 
        maxElementsInMemory="1000" 
        maxElementsOnDisk="10000000"
        eternal="false" 
        overflowToDisk="false" 
        diskPersistent="false"
        timeToIdleSeconds="120"
        timeToLiveSeconds="120" 
        diskExpiryThreadIntervalSeconds="120"
        memoryStoreEvictionPolicy="LRU">
    </defaultCache>
</ehcache>

7.5 缓存清空

如果用户正常退出,缓存自动清空。

如果用户非正常退出,缓存自动清空。

如果修改了用户的权限,而用户不退出系统,修改的权限无法立即生效。
需要手动进行编程实现:
  在权限修改后调用realm的clearCache方法清除缓存。
 下边的代码正常开发时要放在service中调用。在service中,权限修改后调用realm的方法。
  在realm中添加clearCached方法

    //自定义方法,清除缓存
    public void clearCache(){
        PrincipalCollection principals = SecurityUtils.getSubject().getPrincipals();
        super.clearCache(principals);
    }

测试清除缓存controller方法:

    @RequestMapping("/clearCache")
    public String clearCache(){
        customRealm.clearCache();
        return "clearCache";
    }

8.sessionManager

和shiro整合后,使用shiro的session管理,shiro提供sessionDao操作 会话数据。
这里写图片描述
需要注入到securityManager

9.验证码

9.1 思路

  shiro使用FormAuthenticationFilter进行表单认证,验证校验的功能应该加在FormAuthenticationFilter中,在认证之前进行验证码校验。
  需要写FormAuthenticationFilter的子类,继承FormAuthenticationFilter,改写它的认证方法,在认证之前进行验证码校验。

9.2 自定义FormAuthenticationFilter

public class MyFormAuthenticationFilter extends FormAuthenticationFilter {

    protected boolean onAccessDenied(ServletRequest request,
            ServletResponse response) throws Exception {
        HttpSession session = ((HttpServletRequest)request).getSession();
        //获取表单的验证码
        String randomCode = request.getParameter("randomCode");
        //获取session中的验证码
        String validateCode = (String) session.getAttribute("validateCode");
        validateCode="abc";
        if(randomCode!=null && validateCode!=null){
            if(!randomCode.equals(validateCode)){
                //当且仅当表单的验证码和session中的验证码不同时,返回true,即不进行帐号和密码认证
                request.setAttribute("shiroLoginFailure", "randomCodeError");
                return true;
            }
        }
        return super.onAccessDenied(request, response);
    }
}

注意:
1. 当且仅当表单的验证码和session中的验证码不同时,返回true,即不进行帐号和密码认证.
2. 上面的方法中在验证码不同时,对request域写入了参数shiroLoginFailure。
3. onAccessDenied方法在认证方法执行前执行,但请求的ur不管是不是loginUrl,onAccessDenied方法都会执行到。

9.3 配置自定义FormAuthenticationFilter

这里写图片描述

这里写图片描述

10.记住我

  用户登陆选择“自动登陆”本次登陆成功会向cookie写身份信息,下次登陆从cookie中取出身份信息实现自动登陆。

10.1 POJO序列化

  向cookie记录身份信息需要用户身份信息对象实现序列化接口,即pojo(如:User)要实现java.io.Serializable接口。

10.2 配置rememeberMeManager

这里写图片描述
需要注入到securityManager中

10.3 登录界面

这里写图片描述

10.4 自定义form过滤器

这里写图片描述
以上注入的三个参数其实都是默认值。

10.5 测试

自动登陆后,需要查看 cookei是否有rememberMe
这里写图片描述

10.6 使用shiro的UserFilter实现自动登录

这里写图片描述

补充:

问题:Shiro中,对已登陆用户再次访问loginUrl的控制

对已经登录的用户,当再次访问loginUrl时,利用filter重定向到首页。在配置web.xml时,该filter应放于shiroFilter之后。

public class LoginPageFilter implements Filter {

    public void init(FilterConfig filterConfig) throws ServletException {

    }

    public void doFilter(ServletRequest req, ServletResponse resp,
            FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        String user = request.getRemoteUser();
        if (user != null) {
            response.sendRedirect(request.getContextPath() + "/index.jsp");
        } else {
            chain.doFilter(request, response);
        }
    }

    public void destroy() {

    }

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值