JAVA语言之springmvc整合shiro权限控制的实例教程
小标 2018-12-04 来源 : 阅读 1278 评论 0

摘要:本文主要向大家介绍了JAVA语言之springmvc整合shiro权限控制的实例教程,通过具体的内容向大家展示,希望对大家学习JAVA语言有所帮助。

本文主要向大家介绍了JAVA语言之springmvc整合shiro权限控制的实例教程,通过具体的内容向大家展示,希望对大家学习JAVA语言有所帮助。


一、什么是Shiro 


Apache Shiro是一个强大易用的Java安全框架,提供了认证、授权、加密和会话管理等功能: 


认证 - 用户身份识别,常被称为用户“登录”;


授权 - 访问控制;


密码加密 - 保护或隐藏数据防止被偷窥;


会话管理 - 每用户相关的时间敏感的状态。


对于任何一个应用程序,Shiro都可以提供全面的安全管理服务。并且相对于其他安全框架,Shiro要简单的多。


二:springmvc整合shiro


    1,在web.xml中加入如下配置


   


<!-- 配置Shiro过滤器,先让Shiro过滤系统接收到的请求 -->  


<!-- 这里filter-name必须对应applicationContext.xml中定义的<bean id="shiroFilter"/> -->  


<!-- 使用[/*]匹配所有请求,保证所有的可控请求都经过Shiro的过滤 -->  


<!-- 通常会将此filter-mapping放置到最前面(即其他filter-mapping前面),以保证它是过滤器链中第一个起作用的 -->  


 <!-- targetFilterLifecycle值缺省为false,表示生命周期由SpringApplicationContext管理,设置为true则表示由ServletContainer管理 -->  


    


[html] view plain copy


<!-- shiro start安全过滤器 -->  


    <filter>  


        <filter-name>shiroFilter</filter-name>  


        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>  


        <async-supported>true</async-supported>  


        <init-param>  


            <param-name>targetFilterLifecycle</param-name>  


            <param-value>true</param-value>  


        </init-param>  


    </filter>  


  


    <filter-mapping>  


        <filter-name>shiroFilter</filter-name>  


        <url-pattern>/*</url-pattern>  


        <dispatcher>REQUEST</dispatcher>  


    </filter-mapping>  


    <!-- shiro end -->  


2,配置applicationContext.xml


<!-- Shiro主过滤器本身功能十分强大,其强大之处就在于它支持任何基于URL路径表达式的、自定义的过滤器的执行 -->  


<!-- Web应用中,Shiro可控制的Web请求必须经过Shiro主过滤器的拦截,Shiro对基于Spring的Web应用提供了完美的支持 -->  


[html] view plain copy


<!-- 缓存管理器 -->  


    <bean id="cacheManager" class="com.www.admin.spring.SpringCacheManagerWrapper">  


        <property name="cacheManager" ref="springCacheManager"/>  


    </bean>  


  


    <!-- 凭证匹配器 -->  


    <bean id="credentialsMatcher" class="com.www.admin.user.credentials.RetryLimitHashedCredentialsMatcher">  


        <constructor-arg ref="cacheManager"/>  


        <property name="hashAlgorithmName" value="md5"/>  


        <property name="hashIterations" value="2"/>  


        <property name="storedCredentialsHexEncoded" value="true"/>  


    </bean>  


  


    <!-- Realm实现 -->  


    <bean id="userRealm" class="com.www.admin.user.realm.UserRealm">  


        <property name="credentialsMatcher" ref="credentialsMatcher"/>  


        <property name="cachingEnabled" value="true"/>  


        <property name="authenticationCachingEnabled" value="true"/>  


        <property name="authenticationCacheName" value="authenticationCache"/>  


        <property name="authorizationCachingEnabled" value="true"/>  


        <property name="authorizationCacheName" value="authorizationCache"/>  


    </bean>  


  


    <!-- 会话ID生成器 -->  


    <bean id="sessionIdGenerator" class="org.apache.shiro.session.mgt.eis.JavaUuidSessionIdGenerator"/>  


  


    <!-- 会话Cookie模板 -->  


    <bean id="sessionIdCookie" class="org.apache.shiro.web.servlet.SimpleCookie">  


        <constructor-arg value="sid"/>  


        <property name="httpOnly" value="true"/>  


        <property name="maxAge" value="-1"/>  


    </bean>  


  


    <bean id="rememberMeCookie" class="org.apache.shiro.web.servlet.SimpleCookie">  


        <constructor-arg value="rememberMe"/>  


        <property name="httpOnly" value="true"/>  


        <property name="maxAge" value="2592000"/><!-- 30天 -->  


    </bean>  


  


    <!-- rememberMe管理器 -->  


    <bean id="rememberMeManager" class="org.apache.shiro.web.mgt.CookieRememberMeManager">  


        <!-- rememberMe cookie加密的密钥 建议每个项目都不一样 默认AES算法 密钥长度(128 256 512 位)-->  


        <property name="cipherKey"  


                  value="#{T(org.apache.shiro.codec.Base64).decode('4AvVhmFLUs0KTA3Kprsdag==')}"/>  


        <property name="cookie" ref="rememberMeCookie"/>  


    </bean>  


  


    <!-- 会话DAO -->  


    <bean id="sessionDAO" class="org.apache.shiro.session.mgt.eis.EnterpriseCacheSessionDAO">  


        <property name="activeSessionsCacheName" value="shiro-activeSessionCache"/>  


        <property name="sessionIdGenerator" ref="sessionIdGenerator"/>  


    </bean>  


  


    <!-- 会话验证调度器 -->  


    <bean id="sessionValidationScheduler" class="org.apache.shiro.session.mgt.quartz.QuartzSessionValidationScheduler">  


        <property name="sessionValidationInterval" value="1800000"/>  


        <property name="sessionManager" ref="sessionManager"/>  


    </bean>  


  


    <!-- 会话管理器 -->  


    <bean id="sessionManager" class="org.apache.shiro.web.session.mgt.DefaultWebSessionManager">  


        <property name="globalSessionTimeout" value="1800000"/>  


        <property name="deleteInvalidSessions" value="true"/>  


        <property name="sessionValidationSchedulerEnabled" value="true"/>  


        <property name="sessionValidationScheduler" ref="sessionValidationScheduler"/>  


        <property name="sessionDAO" ref="sessionDAO"/>  


        <property name="sessionIdCookieEnabled" value="true"/>  


        <property name="sessionIdCookie" ref="sessionIdCookie"/>  


    </bean>  


  


    <!-- 安全管理器 -->  


    <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">  


        <property name="realm" ref="userRealm"/>  


        <property name="sessionManager" ref="sessionManager"/>  


        <property name="cacheManager" ref="cacheManager"/>  


        <property name="rememberMeManager" ref="rememberMeManager"/>  


    </bean>  


  


    <!-- 相当于调用SecurityUtils.setSecurityManager(securityManager) -->  


    <bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">  


        <property name="staticMethod" value="org.apache.shiro.SecurityUtils.setSecurityManager"/>  


        <property name="arguments" ref="securityManager"/>  


    </bean>  


  


    <!-- 基于Form表单的身份验证过滤器  -->  


    <bean id="loginFormAuthenticationFilter" class="com.www.admin.filter.shiro.LoginFormAuthenticationFilter"/>  


  


    <bean id="logoutFilter" class="org.apache.shiro.web.filter.authc.LogoutFilter">   


        <property name="redirectUrl" value="/admin/login.do" />   


    </bean>   


    <bean id="sysUserFilter" class="com.www.admin.filter.shiro.SysUserFilter"/>  


  


    <!-- Shiro的Web过滤器 -->  


    <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">  


        <property name="securityManager" ref="securityManager"/>  


        <property name="loginUrl" value="/admin/login.do"/>  


        <property name="successUrl" value="/admin/index.do"/>  


        <property name="filters">  


            <util:map>  


                <entry key="authc" value-ref="loginFormAuthenticationFilter"/>  


                <entry key="sysUser" value-ref="sysUserFilter"/>  


                <entry key="logout" value-ref="logoutFilter"/>  


            </util:map>  


        </property>  


        <property name="filterChainDefinitions">  


            <value>                 


                /**/*.js=anon  


                /**/*.img=anon  


                /**/*.css=anon  


                /**/*.png=anon  


                /**/*.gif=anon  


                /**/*.jpg=anon  


                /static/**=anon  


                /admin/logout.do = logout  


                /admin/login.do = authc  


                /authenticated = authc  


                /** = authc,user,sysUser           


            </value>  


        </property>  


    </bean>  


  


    <!-- Shiro生命周期处理器-->  


    <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>  


       


securityManager:这个属性是必须的。


loginUrl:没有登录的用户请求需要登录的页面时自动跳转到登录页面,不是必须的属性,不输入地址的话会自动寻找项目web项目的根目录下的”/login.jsp”页面。


successUrl:登录成功默认跳转页面,不配置则跳转至”/”。如果登陆前点击的一个需要登录的页面,则在登录自动跳转到那个需要登录的页面。不跳转到此。


unauthorizedUrl:没有权限默认跳转的页面。


3,自定义的Realm类


    


     


[java] view plain copy


import java.util.HashSet;  


import java.util.Set;  


  


import javax.annotation.Resource;  


  


import org.apache.shiro.authc.AuthenticationException;  


import org.apache.shiro.authc.AuthenticationInfo;  


import org.apache.shiro.authc.AuthenticationToken;  


import org.apache.shiro.authc.LockedAccountException;  


import org.apache.shiro.authc.SimpleAuthenticationInfo;  


import org.apache.shiro.authc.UnknownAccountException;  


import org.apache.shiro.authz.AuthorizationInfo;  


import org.apache.shiro.authz.SimpleAuthorizationInfo;  


import org.apache.shiro.realm.AuthorizingRealm;  


import org.apache.shiro.subject.PrincipalCollection;  


import org.apache.shiro.util.ByteSource;  


  


  


public class UserRealm extends AuthorizingRealm {  


  


    @Resource  


    private UserService userService;  


          


        //这是授权方法    


    @Override  


    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {  


        String username = (String)principals.getPrimaryPrincipal();  


        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();  


        Set<String> permissionsSet = null;  


        Set<String> permissionsSetStr = new HashSet<String>();  


        try {  


              


            authorizationInfo.setRoles(userService.findRoles(username));  


            permissionsSet = userService.findPermissions(username);  


            for(String perStr:permissionsSet) {  


                if(perStr.indexOf("*")<0) {  


                    permissionsSetStr.add(perStr);  


                }  


            }  


            authorizationInfo.setStringPermissions(permissionsSetStr);  


        } catch (Exception e) {  


            e.printStackTrace();  


        }  


        return authorizationInfo;  


    }  


  


    //这是认证方法   


    @Override  


    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {  


  


        String username = (String)token.getPrincipal();  


        UserVo userVo = null;  


        SimpleAuthenticationInfo authenticationInfo = null;  


        try {  


            userVo = userService.findByUsername(username);  


            if(userVo == null) {  


                throw new UnknownAccountException();//没找到帐号  


            }  


            if(userVo.getLocked()==0) {  


                throw new LockedAccountException(); //帐号锁定  


            }  


            //交给AuthenticatingRealm使用CredentialsMatcher进行密码匹配  


            authenticationInfo = new SimpleAuthenticationInfo(  


                    userVo.getUsername(), //用户名  


                    userVo.getPassword(), //密码  


                    ByteSource.Util.bytes(userVo.getCredentialsSalt()),//salt=username+salt  


                    getName()  //realm name  


            );  


        } catch (Exception e) {  


            e.printStackTrace();  


        }  


       


        return authenticationInfo;  


    }  


  


    @Override  


    public void clearCachedAuthorizationInfo(PrincipalCollection principals) {  


        super.clearCachedAuthorizationInfo(principals);  


    }  


  


    @Override  


    public void clearCachedAuthenticationInfo(PrincipalCollection principals) {  


        super.clearCachedAuthenticationInfo(principals);  


    }  


  


    @Override  


    public void clearCache(PrincipalCollection principals) {  


        super.clearCache(principals);  


    }  


  


    public void clearAllCachedAuthorizationInfo() {  


        getAuthorizationCache().clear();  


    }  


  


    public void clearAllCachedAuthenticationInfo() {  


        getAuthenticationCache().clear();  


    }  


  


    public void clearAllCache() {  


        clearAllCachedAuthenticationInfo();  


        clearAllCachedAuthorizationInfo();  


    }  


  


}  


4,controller层实例   


@RequiresPermissions


例如: @RequiresPermissions({"file:read", "write:aFile.txt"} )


  void someMethod();


要求subject中必须同时含有file:read和write:aFile.txt的权限才能执行方法someMethod()。否则抛出异常AuthorizationException。


  


[java] view plain copy


@RequiresPermissions("sys:user:add")//此处就是控制权限的注解  


@RequestMapping(value = "/add", method = RequestMethod.POST)  


public ModelAndView addUser(){  


    ModelAndView mav = new ModelAndView("user/add");  


    List<RoleVo> roleList = userService.add();  


    mav.addObject("roleList", roleList);  


    return mav;  


}  


5,jsp处控制


  <%@ taglib prefix="shiro" uri="https://shiro.apache.org/tags" %>//引入标签


[javascript] view plain copy


<p class="progess_btn" style=" text-align: left;margin-left: 120px;margin-top: -50px;">  


             <shiro:hasPermission name="sys:user:add">  


                 <a class="btn_sure" href="javascript:void(0);"  style=" margin-right: 58px; width: 100px;" onclick="addSubmit()">添加</a>  


             </shiro:hasPermission>                 


                <a class="btn_sure" href="javascript:history.back(-1);"  style=" margin-right: 58px; width: 100px;">返回</a>  


 </p>  


6.


默认,添加或删除用户的角色 或资源 ,系统不需要重启,但是需要用户重新登录。


即用户的授权是首次登录后第一次访问需要权限页面时进行加载。


但是需要进行控制的权限资源,是在启动时就进行加载,如果要新增一个权限资源需要重启系统。


7.


Springsecurity 与apache shiro差别:


a)shiro配置更加容易理解,容易上手;security配置相对比较难懂。


b)在spring的环境下,security整合性更好。Shiro对很多其他的框架兼容性更好,号称是无缝集成。


c)shiro不仅仅可以使用在web中,它可以工作在任何应用环境中。


d)在集群会话时Shiro最重要的一个好处或许就是它的会话是独立于容器的。


e)Shiro提供的密码加密使用起来非常方便。


8.


控制精度:


注解方式控制权限只能是在方法上控制,无法控制类级别访问。


过滤器方式控制是根据访问的URL进行控制。允许使用*匹配URL,所以可以进行粗粒度,也可以进行细粒度控制。


          

本文由职坐标整理并发布,希望对同学们有所帮助。了解更多详情请关注编程语言JAVA频道!


本文由 @小标 发布于职坐标。未经许可,禁止转载。
喜欢 | 1 不喜欢 | 0
看完这篇文章有何感觉?已经有1人表态,100%的人喜欢 快给朋友分享吧~
评论(0)
后参与评论

您输入的评论内容中包含违禁敏感词

我知道了

助您圆梦职场 匹配合适岗位
验证码手机号,获得海同独家IT培训资料
选择就业方向:
人工智能物联网
大数据开发/分析
人工智能Python
Java全栈开发
WEB前端+H5

请输入正确的手机号码

请输入正确的验证码

获取验证码

您今天的短信下发次数太多了,明天再试试吧!

提交

我们会在第一时间安排职业规划师联系您!

您也可以联系我们的职业规划师咨询:

小职老师的微信号:z_zhizuobiao
小职老师的微信号:z_zhizuobiao

版权所有 职坐标-一站式AI+学习就业服务平台 沪ICP备13042190号-4
上海海同信息科技有限公司 Copyright ©2015 www.zhizuobiao.com,All Rights Reserved.
 沪公网安备 31011502005948号    

©2015 www.zhizuobiao.com All Rights Reserved