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)整合配置
序: 关于标题: 说是教学,实在愧不敢当,但苦与本人文笔有限,实在找不到更合理,谦逊的词语表达,只能先这样定义了. 其实最真实的想法,只是希望这个关键词能让更多的人浏览到这篇文章,也算是对于自己写文章 ...
随机推荐
- UITableView Scroll to top 手动设置tableview 滚动到 顶部
UITableView Scroll to top 手动设置tableview 滚动到 顶部 [mainTableView scrollRectToVisible:CGRectMake(0,0,1,1 ...
- SpringMVC响应Restful风格请求404
在学习Springmvc时,使用Restful风格的url,页面提示404错误.为找到原因,编写一个简单的Restful测试用例如下: jsp页面: <a href="user/tes ...
- 解决树莓派新内核无法使用18B20和没有声音的问题
现在新版的树莓派内核由于为了兼容树莓派2和树莓派B+等以前的版本,采用了和原来不同的内核运行方式,使用了设备树的方式,更加灵活.但是由于可能不习惯这样的方式以及没太多相关这方面的介绍,导致很多用户更新 ...
- 南阳OJ 背包问题
/*背包问题 时间限制:3000 ms | 内存限制:65535 KB 难度:3 描写叙述 如今有非常多物品(它们是能够切割的),我们知道它们每一个物品的单位重量的价值v和 重量w(1< ...
- MYSQL AND OR的联用
MYSQL中"AND"和"OR"都是条件控制符."AND"是求交集,而"OR"则是求并集,非常多情况下,须要联用它们两个 ...
- hibernate 映射实例 学生 课程 成绩
学生和课程是多对多,一个学生的一个课程只能对应一个成绩. 所以学生和课程多对多,其中间表多了一个成绩字段. 可以这样设计: 学生和课程通过中间表--成绩,多对多映射. 手动建中间表语句: cr ...
- 【转载】C#根据当前时间获取周,月,季度,年度等时间段的起止时间
DateTime dt = DateTime.Now; //当前时间 DateTime startWeek = dt.AddDays(1 - Convert.ToInt32(dt.DayOfWeek. ...
- vue TypeError: Cannot read property 'length' of undefined 问题解决思路
上图中是我在接手一个项目的时候,出现的一个关于数组的 bug,但是从上图来看,其实报错是不清楚的,只能从报错信息上看出来是 /src/page/waybill/waybill_form.vue 这个 ...
- 解决nginx到后端服务器Connection: close问题
以下是官方原文: By default, NGINX redefines two header fields in proxied requests, “Host” and “Connection”, ...
- Mongodb更新数组$pull修饰符
http://blog.csdn.net/yaomingyang/article/details/78701643 一.$pull修饰符会删除掉数组中符合条件的元素,使用的格式是: { $pull: ...