spring mvc整合shiro登录 权限验证

1、需要用到的shiro相关包

[html]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. <!-- shiro begin -->  
  2. <dependency>  
  3. <groupId>org.apache.shiro</groupId>  
  4. <artifactId>shiro-core</artifactId>  
  5. <version>1.2.3</version>  
  6. </dependency>  
  7. <dependency>  
  8. <groupId>org.apache.shiro</groupId>  
  9. <artifactId>shiro-web</artifactId>  
  10. <version>1.2.3</version>  
  11. </dependency>  
  12. <dependency>  
  13. <groupId>org.apache.shiro</groupId>  
  14. <artifactId>shiro-ehcache</artifactId>  
  15. <version>1.2.3</version>  
  16. </dependency>  
  17. <dependency>  
  18. <groupId>org.apache.shiro</groupId>  
  19. <artifactId>shiro-spring</artifactId>  
  20. <version>1.2.3</version>  
  21. </dependency>  
  22. <!-- shiro end -->  

2、首先在web.xml中添加shiro过滤器

[html]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  3.     xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"  
  4.     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"  
  5.     version="2.5">  
  6.      <display-name>abel-shiro Application</display-name>  
  7.        
  8.      <!-- 指定上下文配置文件 -->  
  9.      <context-param>  
  10.         <param-name>contextConfigLocation</param-name>  
  11.         <param-value>  
  12.                  classpath:applicationContext.xml  
  13.         </param-value>  
  14.     </context-param>  
  15.       
  16.     <!-- spring监听器,监听springMvc环境 -->  
  17.     <listener>  
  18.         <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  
  19.     </listener>  
  20.       
  21.     <!-- 压入项目路径 -->  
  22.     <listener>  
  23.        <listener-class>org.springframework.web.util.WebAppRootListener</listener-class>  
  24.     </listener>  
  25.       
  26.     <!-- 配置Shiro过滤器,先让Shiro过滤系统接收到的请求 -->    
  27.     <!-- 通常将这段代码中的filter-mapping放在所有filter-mapping之前,以达到shiro是第一个对web请求进行拦截过滤之目的。  
  28.         这里的fileter-name(shiroFilter) 对应下面applicationContext.xml中的<bean id="shiroFilter" />   
  29.         DelegatingFilterProxy会自动到Spring容器中查找名字为shiroFilter的bean并把filter请求交给它处理-->    
  30.     <!-- 使用[/*]匹配所有请求,保证所有的可控请求都经过Shiro的过滤 -->    
  31.     <filter>    
  32.         <filter-name>shiroFilter</filter-name>    
  33.         <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>    
  34.         <init-param>    
  35.             <!-- 该值缺省为false,表示生命周期由SpringApplicationContext管理,设置为true则表示由ServletContainer管理   -->  
  36.             <param-name>targetFilterLifecycle</param-name>    
  37.             <param-value>true</param-value>    
  38.         </init-param>    
  39.     </filter>    
  40.     <filter-mapping>    
  41.         <filter-name>shiroFilter</filter-name>    
  42.         <url-pattern>/*</url-pattern>    
  43.     </filter-mapping>  
  44.     
  45.      <!-- springMvc前置总控制器,在分发其它的控制器前都要经过这个总控制器 -->  
  46.      <servlet>  
  47.         <servlet-name>spring</servlet-name>  
  48.         <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>  
  49.         <init-param>  
  50.             <param-name>contextConfigLocation</param-name>  
  51.             <param-value>/WEB-INF/spring-shiro.xml</param-value>  
  52.         </init-param>  
  53.         <!-- 启动顺序 -->  
  54.         <load-on-startup>1</load-on-startup>  
  55.     </servlet>  
  56.       
  57.     <servlet-mapping>  
  58.         <servlet-name>spring</servlet-name>  
  59.         <url-pattern>/</url-pattern>  
  60.         <!--   
  61.         <url-pattern>/</url-pattern>  会匹配到/login这样的路径型url,不会匹配到模式为*.jsp这样的后缀型url  
  62.         <url-pattern>/*</url-pattern> 会匹配所有url:路径型的和后缀型的url(包括/login,*.jsp,*.js和*.html等)  
  63.          -->  
  64.     </servlet-mapping>  
  65.       
  66. </web-app>  

3、shiro相关配置

[html]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  3.     xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="  
  4.         http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd  
  5.         http://www.springframework.org/schema/context  http://www.springframework.org/schema/context/spring-context-4.0.xsd"  
  6.     default-lazy-init="true">  
  7.   
  8.     <description>Shiro Configuration</description>  
  9.       
  10.     <!-- 继承自AuthorizingRealm的自定义Realm,即指定Shiro验证用户登录的类为自定义的ShiroDbRealm.java -->    
  11.     <bean id="systemAuthorizingRealm" class="com.abel.shiro.security.SystemAuthorizingRealm">   
  12.         <!-- 密码加密验证方式 -->  
  13.         <property name="credentialsMatcher">    
  14.             <bean class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">    
  15.                 <property name="hashAlgorithmName" value="MD5" />  
  16.             </bean>    
  17.         </property>    
  18.     </bean>   
  19.     
  20.     <!-- Shiro默认会使用Servlet容器的Session,可通过sessionMode属性来指定使用Shiro原生Session -->    
  21.     <!-- 即<property name="sessionMode" value="native"/>,详细说明见官方文档 -->    
  22.     <!-- 这里主要是设置自定义的单Realm应用,若有多个Realm,可使用'realms'属性代替 -->    
  23.     <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">    
  24.         <property name="realm" ref="systemAuthorizingRealm"/>    
  25.     </bean>    
  26.     
  27.     <!-- Shiro主过滤器本身功能十分强大,其强大之处就在于它支持任何基于URL路径表达式的、自定义的过滤器的执行 -->    
  28.     <!-- Web应用中,Shiro可控制的Web请求必须经过Shiro主过滤器的拦截,Shiro对基于Spring的Web应用提供了完美的支持 -->    
  29.     <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">    
  30.         <!-- Shiro的核心安全接口,这个属性是必须的 -->    
  31.         <property name="securityManager" ref="securityManager"/>    
  32.         <!-- 要求登录时的链接(可根据项目的URL进行替换),非必须的属性,默认会自动寻找Web工程根目录下的"/login.jsp"页面 -->    
  33.         <property name="loginUrl" value="/login"/>    
  34.         <!-- 登录成功后要跳转的连接 -->    
  35.         <property name="successUrl" value="/admin/index"/>  
  36.         <!-- 用户访问未对其授权的资源时,所显示的连接 -->    
  37.         <!-- 若想更明显的测试此属性可以修改它的值,如unauthor.jsp,然后用[玄玉]登录后访问/admin/listUser.jsp就看见浏览器会显示unauthor.jsp -->    
  38.         <property name="unauthorizedUrl" value="/403"/>    
  39.           
  40.         <!-- Shiro权限过滤过滤器定义 -->  
  41.         <property name="filterChainDefinitions">  
  42.             <ref bean="shiroFilterChainDefinitions"/>  
  43.         </property>   
  44.     </bean>    
  45.       
  46.     <!--   
  47.     filterChainDefinitions参数说明,注意其验证顺序是自上而下  
  48.     =================================================================================================  
  49.     anon        org.apache.shiro.web.filter.authc.AnonymousFilter  
  50.     authc       org.apache.shiro.web.filter.authc.FormAuthenticationFilter  
  51.     authcBasic  org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter  
  52.     perms       org.apache.shiro.web.filter.authz.PermissionsAuthorizationFilter  
  53.     port        org.apache.shiro.web.filter.authz.PortFilter  
  54.     rest        org.apache.shiro.web.filter.authz.HttpMethodPermissionFilter  
  55.     roles       org.apache.shiro.web.filter.authz.RolesAuthorizationFilter  
  56.     ssl         org.apache.shiro.web.filter.authz.SslFilter  
  57.     user        org.apache.shiro.web.filter.authc.UserFilter  
  58.     =================================================================================================  
  59.     anon: 例子/admins/**=anon 没有参数,表示可以匿名使用。  
  60.     authc: 例如/admins/user/**=authc表示需要认证(登录)才能使用,没有参数  
  61.     roles: 例子/admins/user/**=roles[admin],参数可以写多个,多个时必须加上引号,  
  62.                     并且参数之间用逗号分割,当有多个参数时,例如admins/user/**=roles["admin,guest"],  
  63.                     每个参数通过才算通过,相当于hasAllRoles()方法。  
  64.     perms: 例子/admins/user/**=perms[user:add:*],参数可以写多个,多个时必须加上引号,并且参数之间用逗号分割,  
  65.                     例如/admins/user/**=perms["user:add:*,user:modify:*"],当有多个参数时必须每个参数都通过才通过,  
  66.                     想当于isPermitedAll()方法。  
  67.     rest:  例子/admins/user/**=rest[user],根据请求的方法,相当于/admins/user/**=perms[user:method] ,  
  68.                    其中method为post,get,delete等。  
  69.     port:  例子/admins/user/**=port[8081],当请求的url的端口不是8081是跳转到schemal://serverName:8081?queryString,  
  70.                    其中schmal是协议http或https等,serverName是你访问的host,8081是url配置里port的端口,queryString是你访问的url里的?后面的参数。  
  71.     authcBasic:例如/admins/user/**=authcBasic没有参数表示httpBasic认证  
  72.     ssl:  例子/admins/user/**=ssl没有参数,表示安全的url请求,协议为https  
  73.     user: 例如/admins/user/**=user没有参数表示必须存在用户,当登入操作时不做检查  
  74.     注:anon,authcBasic,auchc,user是认证过滤器,  
  75.     perms,roles,ssl,rest,port是授权过滤器  
  76.     =================================================================================================  
  77.     -->   
  78.     <!-- 下面value值的第一个'/'代表的路径是相对于HttpServletRequest.getContextPath()的值来的 -->  
  79.     <bean name="shiroFilterChainDefinitions" class="java.lang.String">  
  80.         <constructor-arg>  
  81.             <value>  
  82.                 /login=anon    
  83.                 /dologin=anon  
  84.                 /logout=anon  
  85.                 /getVerifyCodeImage=anon    
  86.                 /admin/channel/** = authc,perms[admin:channel]  
  87.                 /admin/content/** = authc,perms[admin:content]  
  88.                 /admin/sys/** = authc,perms[admin:sys]  
  89.                 /admin/**=authc   
  90.             </value>  
  91.         </constructor-arg>  
  92.     </bean>  
  93.     
  94.     <!-- 保证实现了Shiro内部lifecycle函数的bean执行 -->    
  95.     <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>    
  96.     
  97.     <!-- AOP式方法级权限检查,开启Shiro的注解(如@RequiresRoles,@RequiresPermissions),需借助SpringAOP扫描使用Shiro注解的类,并在必要时进行安全逻辑验证 -->    
  98.     <bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator" depends-on="lifecycleBeanPostProcessor"/>    
  99.     <bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">    
  100.         <property name="securityManager" ref="securityManager"/>    
  101.     </bean>    
  102.           
  103. </beans>  

4、SystemAuthorizingRealm的实现

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. package com.abel.shiro.security;  
  2.   
  3. import java.util.List;  
  4.   
  5. import org.apache.shiro.SecurityUtils;  
  6. import org.apache.shiro.authc.AuthenticationException;  
  7. import org.apache.shiro.authc.AuthenticationInfo;  
  8. import org.apache.shiro.authc.AuthenticationToken;  
  9. import org.apache.shiro.authc.SimpleAuthenticationInfo;  
  10. import org.apache.shiro.authz.AuthorizationInfo;  
  11. import org.apache.shiro.authz.SimpleAuthorizationInfo;  
  12. import org.apache.shiro.realm.AuthorizingRealm;  
  13. import org.apache.shiro.session.InvalidSessionException;  
  14. import org.apache.shiro.session.Session;  
  15. import org.apache.shiro.subject.PrincipalCollection;  
  16. import org.apache.shiro.subject.Subject;  
  17. import org.springframework.beans.factory.annotation.Autowired;  
  18.   
  19. import com.abel.shiro.Constants;  
  20. import com.abel.shiro.model.MemberModel;  
  21. import com.abel.shiro.model.PermissionModel;  
  22. import com.abel.shiro.model.RoleModel;  
  23. import com.abel.shiro.services.MemberService;  
  24.   
  25. /** 
  26.  * 自定义的指定Shiro验证用户登录的类 
  27.  * @author abel.lin 
  28.  */  
  29. public class SystemAuthorizingRealm extends AuthorizingRealm {  
  30.     @Autowired  
  31.     private MemberService memberService;  
  32.     /** 
  33.      * 授权查询回调函数, 进行鉴权但缓存中无用户的授权信息时调用 
  34.      */  
  35.     @Override  
  36.     protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals){  
  37.         //获取当前登录的用户名,等价于(String)principals.fromRealm(this.getName()).iterator().next()  
  38.         String currentUsername = (String)super.getAvailablePrincipal(principals);  
  39.         MemberModel member = memberService.getMemberByName(currentUsername);  
  40.         if(member == null){  
  41.             throw new AuthenticationException("msg:用户不存在。");  
  42.         }  
  43.         SimpleAuthorizationInfo simpleAuthorInfo = new SimpleAuthorizationInfo();  
  44.           
  45.         List<RoleModel> roleList = memberService.selectRoleByMemberId(member.getId());  
  46.         List<PermissionModel> permList = memberService.selectPermissionByMemberId(member.getId());  
  47.           
  48.         if(roleList != null && roleList.size() > 0){  
  49.             for(RoleModel role : roleList){  
  50.                 if(role.getRoleCode() != null){  
  51.                     simpleAuthorInfo.addRole(role.getRoleCode());  
  52.                 }  
  53.             }  
  54.         }  
  55.           
  56.         if(permList != null && permList.size() > 0){  
  57.             for(PermissionModel perm : permList){  
  58.                 if(perm.getCode() != null){  
  59.                     simpleAuthorInfo.addStringPermission(perm.getCode());  
  60.                 }  
  61.             }  
  62.         }  
  63.         return simpleAuthorInfo;  
  64.           
  65.     }  
  66.   
  67.       
  68.     /** 
  69.      * 认证回调函数, 登录时调用 
  70.      */  
  71.     @Override  
  72.     protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {  
  73.         //获取基于用户名和密码的令牌  
  74.         //实际上这个authcToken是从LoginController里面currentUser.login(token)传过来的  
  75.         UsernamePasswordToken token = (UsernamePasswordToken)authcToken;  
  76.           
  77.         Session session = getSession();  
  78.         String code = (String)session.getAttribute(Constants.VALIDATE_CODE);  
  79.         if (token.getCaptcha() == null || !token.getCaptcha().toUpperCase().equals(code)){  
  80.             throw new AuthenticationException("msg:验证码错误, 请重试.");  
  81.         }  
  82.         MemberModel member = memberService.getMemberByName(token.getUsername());  
  83.         if(member != null){  
  84.             if(member.getIslock() !=null && member.getIslock() == 1){  
  85.                 throw new AuthenticationException("msg:该已帐号禁止登录.");  
  86.             }  
  87.             AuthenticationInfo authcInfo = new SimpleAuthenticationInfo(member.getLoginName(), member.getPwd(), this.getName());  
  88.             this.setSession("currentUser", member.getLoginName());  
  89.               
  90.             return authcInfo;  
  91.         }  
  92.         return null;  
  93.           
  94.     }  
  95.       
  96.     /** 
  97.      * 保存登录名 
  98.      */  
  99.     private void setSession(Object key, Object value){  
  100.         Session session = getSession();  
  101.         System.out.println("Session默认超时时间为[" + session.getTimeout() + "]毫秒");  
  102.         if(null != session){  
  103.             session.setAttribute(key, value);  
  104.         }  
  105.     }  
  106.       
  107.     private Session getSession(){  
  108.         try{  
  109.             Subject subject = SecurityUtils.getSubject();  
  110.             Session session = subject.getSession(false);  
  111.             if (session == null){  
  112.                 session = subject.getSession();  
  113.             }  
  114.             if (session != null){  
  115.                 return session;  
  116.             }  
  117.         }catch (InvalidSessionException e){  
  118.               
  119.         }  
  120.         return null;  
  121.     }  
  122. }  

5、登录操作LoginController

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. package com.abel.shiro.controller;  
  2.   
  3. import java.awt.Color;  
  4. import java.awt.image.BufferedImage;  
  5. import java.io.IOException;  
  6.   
  7. import javax.imageio.ImageIO;  
  8. import javax.servlet.http.HttpServletRequest;  
  9. import javax.servlet.http.HttpServletResponse;  
  10.   
  11. import org.apache.shiro.SecurityUtils;  
  12. import org.apache.shiro.subject.Subject;  
  13. import org.springframework.stereotype.Controller;  
  14. import org.springframework.web.bind.annotation.RequestMapping;  
  15. import org.springframework.web.bind.annotation.ResponseBody;  
  16.   
  17. import com.abel.shiro.Constants;  
  18. import com.abel.shiro.security.UsernamePasswordToken;  
  19.   
  20. /** 
  21.  * @author abel.lin 
  22.  */  
  23. @Controller  
  24. public class LoginController {  
  25.   
  26.     @RequestMapping("login")  
  27.     public String login(HttpServletRequest request){  
  28.           
  29.         return "login";  
  30.     }  
  31.       
  32.     @RequestMapping("login/auth")  
  33.     public String doLogin(HttpServletRequest request){  
  34.         String username = request.getParameter("loginname");  
  35.         String pwd = request.getParameter("password");  
  36.         String captcha = request.getParameter("captcha");  
  37.         UsernamePasswordToken token = new UsernamePasswordToken(username, pwd, captcha);   
  38.         Subject currentUser = SecurityUtils.getSubject();   
  39.         currentUser.login(token);    
  40.         return "redirect:/admin/index";  
  41.     }  
  42.       
  43.     @ResponseBody  
  44.     @RequestMapping("admin/index")  
  45.     public String index(HttpServletRequest request){  
  46.         return "wellcome index";  
  47.     }  
  48.     @ResponseBody  
  49.     @RequestMapping("admin/channel")  
  50.     public String channel(HttpServletRequest request){  
  51.         return "wellcome channel";  
  52.     }  
  53.     @ResponseBody  
  54.     @RequestMapping("admin/content")  
  55.     public String content(HttpServletRequest request){  
  56.         return "wellcome content";  
  57.     }  
  58.     @ResponseBody  
  59.     @RequestMapping("admin/sys")  
  60.     public String sys(HttpServletRequest request){  
  61.         return "wellcome sys";  
  62.     }  
  63.       
  64.     @RequestMapping("logout")  
  65.     public String logout(HttpServletRequest request){  
  66.         SecurityUtils.getSubject().logout();    
  67.         return "redirect:/login";  
  68.     }  
  69.       
  70.     /**  
  71.      * 获取验证码图片和文本(验证码文本会保存在HttpSession中)  
  72.      */    
  73.     @RequestMapping("/genCaptcha")    
  74.     public void genCaptcha(HttpServletRequest request, HttpServletResponse response) throws IOException {    
  75.         //设置页面不缓存    
  76.         response.setHeader("Pragma""no-cache");    
  77.         response.setHeader("Cache-Control""no-cache");    
  78.         response.setDateHeader("Expires"0);    
  79.         String verifyCode = VerifyCodeUtil.generateTextCode(VerifyCodeUtil.TYPE_NUM_ONLY, 4null);    
  80.         //将验证码放到HttpSession里面    
  81.         request.getSession().setAttribute(Constants.VALIDATE_CODE, verifyCode);    
  82.         System.out.println("本次生成的验证码为[" + verifyCode + "],已存放到HttpSession中");    
  83.         //设置输出的内容的类型为JPEG图像    
  84.         response.setContentType("image/jpeg");    
  85.         BufferedImage bufferedImage = VerifyCodeUtil.generateImageCode(verifyCode, 90305true, Color.WHITE, nullnull);    
  86.         //写给浏览器    
  87.         ImageIO.write(bufferedImage, "JPEG", response.getOutputStream());    
  88.     }    
  89.       
  90. }  

6、登录页面

[html]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. <!DOCTYPE html>  
  2. <html>  
  3. <head>  
  4. <meta charset="UTF-8">  
  5. <title>Shiro login</title>  
  6. </head>  
  7. <body>  
  8. <form action="/login/auth" method="post">  
  9. <div><label>用户名</label><input type="text" name="loginname" /></div>  
  10. <div><label>密 码</label><input type="text" name="password" /></div>  
  11. <div><label>验证码</label><input type="text" name="captcha" /><img src="/genCaptcha" /></div>  
  12. <div><input type="submit" value="登录" /></div>  
  13. </form>  
  14. </body>  
  15. </html>  

项目源码下载(包含数据库): http://download.csdn.net/detail/rongku/9513091
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值