SpringMVC整合Shiro(配解释)
第一步:配置web.xml
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
<!-- 配置Shiro过滤器,先让Shiro过滤系统接收到的请求 --> <!-- 这里filter-name必须相应applicationContext.xml中定义的<bean id="shiroFilter"/> --> <!-- 使用[/*]匹配全部请求,保证全部的可控请求都经过Shiro的过滤 --> <!-- 一般会将此filter-mapping放置到最前面(即其它filter-mapping前面),以保证它是过滤器链中第一个起作用的 --> <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> |
第二步:配置applicationContext.xml
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
|
<!-- 继承自AuthorizingRealm的自己定义Realm,即指定Shiro验证用户登录的类为自己定义的ShiroDbRealm.java --> <bean id="myRealm" class="com.jadyer.realm.MyRealm"/> <!-- Shiro默认会使用Servlet容器的Session,可通过sessionMode属性来指定使用Shiro原生Session --> <!-- 即<property name="sessionMode" value="native"/>,具体说明见官方文档 --> <!-- 这里主要是设置自己定义的单Realm应用,若有多个Realm,可使用'realms'属性取代 --> <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager"> <property name="realm" ref="myRealm"/> </bean> <!-- Shiro主过滤器本身功能十分强大,其强大之处就在于它支持不论什么基于URL路径表达式的、自己定义的过滤器的运行 --> <!-- Web应用中,Shiro可控制的Web请求必须经过Shiro主过滤器的拦截,Shiro对基于Spring的Web应用提供了完美的支持 --> <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean"> <!-- Shiro的核心安全接口,这个属性是必须的 --> <property name="securityManager" ref="securityManager"/> <!-- 要求登录时的链接(可依据项目的URL进行替换),非必须的属性,默认会自己主动寻找Webproject根文件夹下的"/login.jsp"页面 --> <property name="loginUrl" value="/"/> <!-- 登录成功后要跳转的连接(本例中此属性用不到,由于登录成功后的处理逻辑在LoginController里硬编码为main.jsp了) --> <!-- <property name="successUrl" value="/system/main"/> --> <!-- 用户訪问未对其授权的资源时,所显示的连接 --> <!-- 若想更明显的測试此属性能够改动它的值,如unauthor.jsp,然后用[玄玉]登录后訪问/admin/listUser.jsp就看见浏览器会显示unauthor.jsp --> <property name="unauthorizedUrl" value="/"/> <!-- Shiro连接约束配置,即过滤链的定义 --> <!-- 此处可配合我的这篇文章来理解各个过滤连的作用http://blog.csdn.net/jadyer/article/details/12172839 --> <!-- 以下value值的第一个'/'代表的路径是相对于HttpServletRequest.getContextPath()的值来的 --> <!-- anon:它相应的过滤器里面是空的,什么都没做,这里.do和.jsp后面的*表示參数,例如说login.jsp?
<!-- authc:该过滤器下的页面必须验证后才干訪问,它是Shiro内置的一个拦截器org.apache.shiro.web.filter.authc.FormAuthenticationFilter --> <property name="filterChainDefinitions"> <value> /mydemo/login=anon /mydemo/getVerifyCodeImage=anon /main**=authc /user/info**=authc /admin/listUser**=authc,perms[admin:manage] </value> </property></bean> <!-- 保证实现了Shiro内部lifecycle函数的bean运行 --> <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/> <!-- 开启Shiro的注解(如@RequiresRoles,@RequiresPermissions),需借助SpringAOP扫描使用Shiro注解的类,并在必要时进行安全逻辑验证 --> <!-- 配置下面两个bean就可以实现此功能 --> <!-- Enable Shiro Annotations for Spring-configured beans. Only run after the lifecycleBeanProcessor has run --> <!-- 因为本例中并未使用Shiro注解,故凝视掉这两个bean(个人认为将权限通过注解的方式硬编码在程序中,查看起来不是非常方便,不是必需使用) --> <!-- <bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator" depends-on="lifecycleBeanPostProcessor"/> <bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor"> <property name="securityManager" ref="securityManager"/> </bean> --> |
第三步:自己定义的Realm类
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
|
public class MyRealm extends AuthorizingRealm { /** * 为当前登录的Subject授予角色和权限 * @see 经測试:本例中该方法的调用时机为需授权资源被訪问时 * @see 经測试:而且每次訪问需授权资源时都会运行该方法中的逻辑,这表明本例中默认并未启用AuthorizationCache * @see 个人感觉若使用了Spring3.1開始提供的ConcurrentMapCache支持,则可灵活决定是否启用AuthorizationCache * @see 比方说这里从数据库获取权限信息时,先去訪问Spring3.1提供的缓存,而不使用Shior提供的AuthorizationCache */ @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals){ //获取当前登录的username,等价于(String)principals.fromRealm(this.getName()).iterator().next() String currentUsername = (String)super.getAvailablePrincipal(principals); // List<String> roleList = new ArrayList<String>(); // List<String> permissionList = new ArrayList<String>(); // //从数据库中获取当前登录用户的具体信息 // User user = userService.getByUsername(currentUsername); // if(null != user){ // //实体类User中包括实用户角色的实体类信息 // if(null!=user.getRoles() && user.getRoles().size()>0){ // //获取当前登录用户的角色 // for(Role role : user.getRoles()){ // roleList.add(role.getName()); // //实体类Role中包括有角色权限的实体类信息 // if(null!=role.getPermissions() && role.getPermissions().size()>0){ // //获取权限 // for(Permission pmss : role.getPermissions()){ // if(!StringUtils.isEmpty(pmss.getPermission())){ // permissionList.add(pmss.getPermission()); // } // } // } // } // } // }else{ // throw new AuthorizationException(); // } // //为当前用户设置角色和权限 // SimpleAuthorizationInfo simpleAuthorInfo = new SimpleAuthorizationInfo(); // simpleAuthorInfo.addRoles(roleList); // simpleAuthorInfo.addStringPermissions(permissionList); SimpleAuthorizationInfo simpleAuthorInfo = new SimpleAuthorizationInfo(); //实际中可能会像上面凝视的那样从数据库取得 if(null!=currentUsername && "mike".equals(currentUsername)){ //加入一个角色,不是配置意义上的加入,而是证明该用户拥有admin角色 simpleAuthorInfo.addRole("admin"); //加入权限 simpleAuthorInfo.addStringPermission("admin:manage"); System.out.println("已为用户[mike]赋予了[admin]角色和[admin:manage]权限"); return simpleAuthorInfo; } //若该方法什么都不做直接返回null的话,就会导致不论什么用户訪问/admin/listUser.jsp时都会自己主动跳转到unauthorizedUrl指定的地址 //详见applicationContext.xml中的<bean id="shiroFilter">的配置 return null; } /** * 验证当前登录的Subject * @see 经測试:本例中该方法的调用时机为LoginController.login()方法中运行Subject.login()时 */ @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException { //获取基于username和password的令牌 //实际上这个authcToken是从LoginController里面currentUser.login(token)传过来的 //两个token的引用都是一样的 UsernamePasswordToken token = (UsernamePasswordToken)authcToken; System.out.println("验证当前Subject时获取到token为" + ReflectionToStringBuilder.toString(token, ToStringStyle.MULTI_LINE_STYLE)); // User user = userService.getByUsername(token.getUsername()); // if(null != user){ // AuthenticationInfo authcInfo = new SimpleAuthenticationInfo(user.getUsername(), user.getPassword(), user.getNickname()); // this.setSession("currentUser", user); // return authcInfo; // }else{ // return null; // } //此处无需比对,比对的逻辑Shiro会做,我们仅仅需返回一个和令牌相关的正确的验证信息 //说白了就是第一个參数填登录username,第二个參数填合法的登录password(能够是从数据库中取到的,本例中为了演示就硬编码了) //这样一来,在随后的登录页面上就仅仅有这里指定的用户和password才干通过验证 if("mike".equals(token.getUsername())){ AuthenticationInfo authcInfo = new SimpleAuthenticationInfo("mike", "mike", this.getName()); this.setSession("currentUser", "mike"); return authcInfo; } //没有返回登录username相应的SimpleAuthenticationInfo对象时,就会在LoginController中抛出UnknownAccountException异常 return null; } /** * 将一些数据放到ShiroSession中,以便于其他地方使用 * @see 比方Controller,使用时直接用HttpSession.getAttribute(key)就能够取到 */ private void setSession(Object key, Object value){ Subject currentUser = SecurityUtils.getSubject(); if(null != currentUser){ Session session = currentUser.getSession(); System.out.println("Session默认超时时间为[" + session.getTimeout() + "]毫秒"); if(null != session){ session.setAttribute(key, value); } } } } |
SpringMVC整合Shiro(配解释)的更多相关文章
- SpringMVC整合Shiro——(3)
SpringMVC整合Shiro,Shiro是一个强大易用的Java安全框架,提供了认证.授权.加密和会话管理等功能. 第一步:配置web.xml <!-- 配置Shiro过滤器,先让Shiro ...
- SpringMVC整合Shiro,Shiro是一个强大易用的Java安全框架,提供了认证、授权、加密和会话管理等功能
SpringMVC整合Shiro,Shiro是一个强大易用的Java安全框架,提供了认证.授权.加密和会话管理等功能. 第一步:配置web.xml <!-- 配置Shiro过滤器,先让Shiro ...
- SpringMVC整合Shiro权限框架
尊重原创:http://blog.csdn.net/donggua3694857/article/details/52157313 最近在学习Shiro,首先非常感谢开涛大神的<跟我学Shiro ...
- SpringMVC整合Shiro
首先是web.xml <?xml version="1.0" encoding="UTF-8"?> <web-app version=&quo ...
- 【转载,待整理】初学 springmvc整合shiro
1. shiro认证流程理解 2. 整合过程 http://blog.csdn.net/dawangxiong123/article/details/53020424 http://blog.csdn ...
- SpringMVC整合Shiro安全框架(一)
一. 准备工作 1. 本文参考自张开涛的 <跟我学Shiro> 二. 简介 1. Apache Shiro是Java的一个安全框架.可以帮助我们完成:认证.授权.加密.会话管理.与Web集 ...
- springmvc 整合shiro
1.引用maven <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro ...
- 160408、SpringMVC整合Shiro
第一步:配置web.xml 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 <!-- 配置Shiro过滤器,先让Shiro过滤系统接收到的请求 --> ...
- SpringMVC+Apache Shiro+JPA(hibernate)整合配置
序: 关于标题: 说是教学,实在愧不敢当,但苦与本人文笔有限,实在找不到更合理,谦逊的词语表达,只能先这样定义了. 其实最真实的想法,只是希望这个关键词能让更多的人浏览到这篇文章,也算是对于自己写文章 ...
随机推荐
- GObject对象系统
http://www.ibm.com/developerworks/cn/linux/l-gobject/ 简单的说,GObject对象系统是一个建立在GLIB基础上的,用C语言完成的,具有跨平台特色 ...
- js中字符串转换为数字
js 字符串转化成数字的三种方法主要有 转换函数.强制类型转换.利用js变量弱类型转换. 1. 转换函数: js提供了parseInt()和parseFloat()两个转换函数.前者把值转换成整数,后 ...
- vue - webpack.dev.conf.js for node-portfinder
描述:获取当前可用的port. (vue-cli配置好了,一旦端口被占用,报错,再次运行时会打开:8080+1,依次类推...8080+n) 官网地址:https://www.npmjs.com/pa ...
- javaweb开发所需的技术需求
本文仅为新手想学习javaWeb的提供一些参考,有不足或错误之处可以修改或添加,另希望以后学习者可以同样将自己的心得发来和大家分享...谢谢 1 前台:html,css,javascript 这是最 ...
- mysql,给每一条数据的某一个字段生成不同的随机数
UPDATE t_article ta-- 利用LEFT JOIN的方式进行关联修改 LEFT JOIN(-- 先通过查询的方式给每一条数据生成对应的10-500之间随机数 SELECT articl ...
- leetcode第一刷_Combination Sum Combination Sum II
啊啊啊啊.好怀念这样的用递归保存路径然后打印出来的题目啊.好久没遇到了. 分了两种,一种是能够反复使用数组中数字的,一种是每一个数字仅仅能用一次的.事实上没有多大差别,第一种每次进入递归的时候都要从头 ...
- Linux-进程基础
计算机实际上可以做的事情实质上非常简单,比如计算两个数的和,再比如在内存中寻找到某个地址等等.这些最基础的计算机动作被称为指令 (instruction).所谓的程序(program),就是这样一系列 ...
- c#金额转换成中文大写金额 .Net开发Windows服务
c#金额转换成中文大写金额 2018-08-24 转别人 c#金额转换成中文大写金额 /// <summary> /// 金额转换成中文大写金额 /// </summary> ...
- 使用intelliJ IDE开发java web项目
<!-- spring版本号 --> <spring.version>4.3.0.RELEASE</spring.version> <!-- mybatis版 ...
- atitit..国富论 在现代it企业项目管理中的作用attialx 总结---国富论读后感 attialx
atitit..国富论 在现代it企业项目管理中的作用attialx 总结---国富论读后感 attialx 1. 国民财富的性质和原因的研究(简称:<国富论>) 1 2. 蕴含的重要管理 ...