spring mvc整合shiro登录 权限验证

1、需要用到的shiro相关包

[html]  view plain  copy
 
  1.   
  2. <dependency>  
  3. <groupId>org.apache.shirogroupId>  
  4. <artifactId>shiro-coreartifactId>  
  5. <version>1.2.3version>  
  6. dependency>  
  7. <dependency>  
  8. <groupId>org.apache.shirogroupId>  
  9. <artifactId>shiro-webartifactId>  
  10. <version>1.2.3version>  
  11. dependency>  
  12. <dependency>  
  13. <groupId>org.apache.shirogroupId>  
  14. <artifactId>shiro-ehcacheartifactId>  
  15. <version>1.2.3version>  
  16. dependency>  
  17. <dependency>  
  18. <groupId>org.apache.shirogroupId>  
  19. <artifactId>shiro-springartifactId>  
  20. <version>1.2.3version>  
  21. dependency>  
  22.   

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

[html]  view plain  copy
 
  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 Applicationdisplay-name>  
  7.        
  8.        
  9.      <context-param>  
  10.         <param-name>contextConfigLocationparam-name>  
  11.         <param-value>  
  12.                  classpath:applicationContext.xml  
  13.         param-value>  
  14.     context-param>  
  15.       
  16.       
  17.     <listener>  
  18.         <listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>  
  19.     listener>  
  20.       
  21.       
  22.     <listener>  
  23.        <listener-class>org.springframework.web.util.WebAppRootListenerlistener-class>  
  24.     listener>  
  25.       
  26.         
  27.         
  28.     <filter>    
  29.         <filter-name>shiroFilterfilter-name>    
  30.         <filter-class>org.springframework.web.filter.DelegatingFilterProxyfilter-class>    
  31.         <init-param>    
  32.               
  33.             <param-name>targetFilterLifecycleparam-name>    
  34.             <param-value>trueparam-value>    
  35.         init-param>    
  36.     filter>    
  37.     <filter-mapping>    
  38.         <filter-name>shiroFilterfilter-name>    
  39.         <url-pattern>/*url-pattern>    
  40.     filter-mapping>  
  41.     
  42.        
  43.      <servlet>  
  44.         <servlet-name>springservlet-name>  
  45.         <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>  
  46.         <init-param>  
  47.             <param-name>contextConfigLocationparam-name>  
  48.             <param-value>/WEB-INF/spring-shiro.xmlparam-value>  
  49.         init-param>  
  50.           
  51.         <load-on-startup>1load-on-startup>  
  52.     servlet>  
  53.       
  54.     <servlet-mapping>  
  55.         <servlet-name>springservlet-name>  
  56.         <url-pattern>/url-pattern>  
  57.             
  58.     <bean id="systemAuthorizingRealm" class="com.abel.shiro.security.SystemAuthorizingRealm">   
  59.           
  60.         <property name="credentialsMatcher">    
  61.             <bean class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">    
  62.                 <property name="hashAlgorithmName" value="MD5" />  
  63.             bean>    
  64.         property>    
  65.     bean>   
  66.     
  67.         
  68.         
  69.         
  70.     <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">    
  71.         <property name="realm" ref="systemAuthorizingRealm"/>    
  72.     bean>    
  73.     
  74.         
  75.         
  76.     <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">    
  77.             
  78.         <property name="securityManager" ref="securityManager"/>    
  79.             
  80.         <property name="loginUrl" value="/login"/>    
  81.             
  82.         <property name="successUrl" value="/admin/index"/>  
  83.             
  84.             
  85.         <property name="unauthorizedUrl" value="/403"/>    
  86.           
  87.           
  88.         <property name="filterChainDefinitions">  
  89.             <ref bean="shiroFilterChainDefinitions"/>  
  90.         property>   
  91.     bean>    
  92.       
  93.       
  94.     <bean name="shiroFilterChainDefinitions" class="java.lang.String">  
  95.         <constructor-arg>  
  96.             <value>  
  97.                 /login=anon    
  98.                 /dologin=anon  
  99.                 /logout=anon  
  100.                 /getVerifyCodeImage=anon    
  101.                 /admin/channel/** = authc,perms[admin:channel]  
  102.                 /admin/content/** = authc,perms[admin:content]  
  103.                 /admin/sys/** = authc,perms[admin:sys]  
  104.                 /admin/**=authc   
  105.             value>  
  106.         constructor-arg>  
  107.     bean>  
  108.     
  109.         
  110.     <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>    
  111.     
  112.         
  113.     <bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator" depends-on="lifecycleBeanPostProcessor"/>    
  114.     <bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">    
  115.         <property name="securityManager" ref="securityManager"/>    
  116.     bean>    
  117.           
  118. beans>  

4、SystemAuthorizingRealm的实现

[java]  view plain  copy
 
  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 roleList = memberService.selectRoleByMemberId(member.getId());  
  46.         List 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
 
  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
 
  1. >  
  2. <html>  
  3. <head>  
  4. <meta charset="UTF-8">  
  5. <title>Shiro logintitle>  
  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

你可能感兴趣的:(spring学习)