第一步:配置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?

main这样的 -->  

    <!-- 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(配解释)的更多相关文章

  1. SpringMVC整合Shiro——(3)

    SpringMVC整合Shiro,Shiro是一个强大易用的Java安全框架,提供了认证.授权.加密和会话管理等功能. 第一步:配置web.xml <!-- 配置Shiro过滤器,先让Shiro ...

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

    SpringMVC整合Shiro,Shiro是一个强大易用的Java安全框架,提供了认证.授权.加密和会话管理等功能. 第一步:配置web.xml <!-- 配置Shiro过滤器,先让Shiro ...

  3. SpringMVC整合Shiro权限框架

    尊重原创:http://blog.csdn.net/donggua3694857/article/details/52157313 最近在学习Shiro,首先非常感谢开涛大神的<跟我学Shiro ...

  4. SpringMVC整合Shiro

    首先是web.xml <?xml version="1.0" encoding="UTF-8"?> <web-app version=&quo ...

  5. 【转载,待整理】初学 springmvc整合shiro

    1. shiro认证流程理解 2. 整合过程 http://blog.csdn.net/dawangxiong123/article/details/53020424 http://blog.csdn ...

  6. SpringMVC整合Shiro安全框架(一)

    一. 准备工作 1. 本文参考自张开涛的 <跟我学Shiro> 二. 简介 1. Apache Shiro是Java的一个安全框架.可以帮助我们完成:认证.授权.加密.会话管理.与Web集 ...

  7. springmvc 整合shiro

    1.引用maven <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro ...

  8. 160408、SpringMVC整合Shiro

    第一步:配置web.xml 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 <!-- 配置Shiro过滤器,先让Shiro过滤系统接收到的请求 -->  ...

  9. SpringMVC+Apache Shiro+JPA(hibernate)整合配置

    序: 关于标题: 说是教学,实在愧不敢当,但苦与本人文笔有限,实在找不到更合理,谦逊的词语表达,只能先这样定义了. 其实最真实的想法,只是希望这个关键词能让更多的人浏览到这篇文章,也算是对于自己写文章 ...

随机推荐

  1. iOS项目开发实战——使用CoreLocation获取当前位置信息

    随着基于位置服务LBS和移动互联网的兴起,你的位置是越来越重要的一个信息.位置服务已经是当前的热门应用如微信.陌陌等社交应用的杀手锏.而在iOS开发中,苹果已经给我们提供了一个位置接口.CoreLoc ...

  2. 解决ios7.0 以后自己定义导航栏左边button靠右的问题

    1.自己定义button //左button UIButton *leftBtn = [[UIButton , , , )]; [leftBtn addTarget:self action:@sele ...

  3. VUE 数组更新

    1.数据方法分类: (1)原数组改变 push pop unshift shift reverse sort splice (2)原数组未变,生成新数组 slice concat filter map ...

  4. ES6 Reflect

    1.Reflect概述 ES6 为了操作对象而提供的新 API 2.Reflect设计目的 (1)将Object对象的一些明显属于语言内部的方法(比如Object.defineProperty),放到 ...

  5. IntelliJ IDEA15,PhpStorm10,WebStorm11激活破解

    此方法可用于激活IntelliJ IDEA15,PhpStorm10,WebStorm11等系列JetBrains产品.仅供参考,请支持正版. 最新方法:http://15.idea.lanyus.c ...

  6. Can report_aeroo_ooo work with Ubuntu 13.10?

    来 自 :https://www.odoo.com/forum/help-1/question/can-report-aeroo-ooo-work-with-ubuntu-13-10-34314 I ...

  7. MySQL的索引及其优化

    前言 索引对查询的速度有着至关重要的影响,理解索引也是进行数据库性能调优的起点.考虑如下情况,假设数据库中一个表有10^6条记录,DBMS的页面大小为4K,并存储100条记录.如果没有索引,查询将对整 ...

  8. Ubuntu 如何切换到root账户

    root账号问题 ubuntu默认禁用了root账号,所以当年试图使用su root命令切换到root用户时,尽管你已经输入了正确的密码,终端依旧会提示你密码错误.你需要执行以下命令解除root账号的 ...

  9. 随机验证码模块(random)

    1. 生成一个6位数字+字母的验证码 (面试题) import random l = []for i in range(6): alpha = chr(random.randint(65,90)) a ...

  10. 最全ASCII对应码表-键值

    OCT(八进制) 最全ASCII码对应表—与键盘按键对应值 (二进)Bin    (十进)Dec   (十六进)Hex         缩写/字符                            ...