您当前的位置: 首页 > 

科技D人生

暂无认证

  • 0浏览

    0关注

    1550博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

Shiro学习总结(4)——Shrio登陆验证实例详细解读

科技D人生 发布时间:2016-05-12 12:40:02 ,浏览量:0

最终效果如下:

工程整体的目录如下:

Java代码如下:

配置文件如下:

页面资源如下:

好了,下面来简单说下过程吧!

准备工作:

先建表:

[sql]  view plain  copy
  1. drop table if exists user;  
  2.  CREATE TABLE `user` (  
  3.   `id` int(11) primary key auto_increment,  
  4.   `name` varchar(20)  NOT NULL,  
  5.   `age` int(11) DEFAULT NULL,  
  6.   `birthday` date DEFAULT NULL,  
  7.   `password` varchar(20)  NOT NULL  
  8. ) ENGINE=InnoDB DEFAULT CHARSET=utf8;  
  9.   
  10.  insert into user values(1,'lin',12,'2013-12-01','123456');  
  11.  insert into user values(2,'apple',34,'1999-12-01','123456');  
  12.  insert into user values(3,'evankaka',23,'2017-12-01','123456');  
建好后,新建一个Maven的webApp的工程,记得把结构设置成上面的那样!

下面来看看一些代码和配置

1、POM文件

注意不要少导包了,如果项目出现红叉,一般都是JDK版本的设置问题,自己百度一下就可以解决

[html]  view plain  copy
  1.   
  2.     4.0.0  
  3.     com.lin  
  4.     ShiroLearn1  
  5.     war  
  6.     0.0.1-SNAPSHOT  
  7.     ShiroLearn1 Maven Webapp  
  8.     http://maven.apache.org  
  9.       
  10.           
  11.         3.2.8.RELEASE  
  12.           
  13.         1.6.6  
  14.         1.2.12  
  15.           
  16.         4.10  
  17.           
  18.         3.2.1  
  19.       
  20.       
  21.           
  22.           
  23.             org.springframework  
  24.             spring-core  
  25.             ${spring.version}  
  26.           
  27.           
  28.             org.springframework  
  29.             spring-webmvc  
  30.             ${spring.version}  
  31.           
  32.           
  33.             org.springframework  
  34.             spring-context  
  35.             ${spring.version}  
  36.           
  37.           
  38.             org.springframework  
  39.             spring-context-support  
  40.             ${spring.version}  
  41.           
  42.           
  43.             org.springframework  
  44.             spring-aop  
  45.             ${spring.version}  
  46.           
  47.           
  48.             org.springframework  
  49.             spring-aspects  
  50.             ${spring.version}  
  51.           
  52.           
  53.             org.springframework  
  54.             spring-tx  
  55.             ${spring.version}  
  56.           
  57.           
  58.             org.springframework  
  59.             spring-jdbc  
  60.             ${spring.version}  
  61.           
  62.           
  63.             org.springframework  
  64.             spring-web  
  65.             ${spring.version}  
  66.           
  67.   
  68.           
  69.           
  70.             junit  
  71.             junit  
  72.             ${junit.version}  
  73.             test  
  74.           
  75.   
  76.           
  77.           
  78.           
  79.             log4j  
  80.             log4j  
  81.             ${log4j.version}  
  82.           
  83.           
  84.             org.slf4j  
  85.             slf4j-api  
  86.             ${slf4j.version}  
  87.           
  88.           
  89.             org.slf4j  
  90.             slf4j-log4j12  
  91.             ${slf4j.version}  
  92.           
  93.           
  94.   
  95.           
  96.           
  97.             org.springframework  
  98.             spring-test  
  99.             ${spring.version}  
  100.             test  
  101.           
  102.   
  103.           
  104.           
  105.             org.mybatis  
  106.             mybatis  
  107.             ${mybatis.version}  
  108.           
  109.   
  110.           
  111.           
  112.             org.mybatis  
  113.             mybatis-spring  
  114.             1.2.0  
  115.           
  116.   
  117.           
  118.           
  119.             mysql  
  120.             mysql-connector-java  
  121.             5.1.29  
  122.           
  123.   
  124.                
  125.           
  126.             javax.servlet  
  127.             servlet-api  
  128.             3.0-alpha-1  
  129.           
  130.   
  131.           
  132.           
  133.             org.apache.shiro  
  134.             shiro-core  
  135.             1.2.1  
  136.           
  137.           
  138.             org.apache.shiro  
  139.             shiro-web  
  140.             1.2.1  
  141.           
  142.           
  143.             org.apache.shiro  
  144.             shiro-ehcache  
  145.             1.2.1  
  146.           
  147.           
  148.             org.apache.shiro  
  149.             shiro-spring  
  150.             1.2.1  
  151.           
  152.           
  153.   
  154.       
  155.       
  156.         ShiroLearn1  
  157.           
  158.               
  159.               
  160.                 maven-war-plugin  
  161.                   
  162.                     2.4  
  163.                   
  164.               
  165.               
  166.               
  167.                 org.apache.maven.plugins  
  168.                 maven-compiler-plugin  
  169.                 2.3.2  
  170.                   
  171.                     1.6  
  172.                     1.6  
  173.                   
  174.               
  175.           
  176.       
  177.   

2、自定义Shiro拦截器

   这里这个拦截器完成了用户名和密码的验证,验证成功后又给用赋角色和权限(注意,这里赋角色和权限我直接写进去了,没有使用数据库,一般都是要通过service层找到用户名后,再去数据库查该用户对应的角色以及权限,然后再加入到shiro中去)

代码如下:

[java]  view plain  copy
  1. package com.lin.realm;  
  2.   
  3. import java.util.HashSet;  
  4. import java.util.Set;  
  5.   
  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.authc.UsernamePasswordToken;  
  11. import org.apache.shiro.authz.AuthorizationInfo;  
  12. import org.apache.shiro.authz.SimpleAuthorizationInfo;  
  13. import org.apache.shiro.cache.Cache;  
  14. import org.apache.shiro.realm.AuthorizingRealm;  
  15. import org.apache.shiro.subject.PrincipalCollection;  
  16. import org.apache.shiro.subject.SimplePrincipalCollection;  
  17. import org.slf4j.Logger;  
  18. import org.slf4j.LoggerFactory;  
  19. import org.springframework.beans.factory.annotation.Autowired;  
  20.   
  21. import com.lin.domain.User;  
  22. import com.lin.service.UserService;  
  23. import com.lin.utils.CipherUtil;  
  24.   
  25. public class ShiroDbRealm extends AuthorizingRealm {  
  26.     private static Logger logger = LoggerFactory.getLogger(ShiroDbRealm.class);  
  27.     private static final String ALGORITHM = "MD5";  
  28.       
  29.     @Autowired  
  30.     private UserService userService;  
  31.   
  32.     public ShiroDbRealm() {  
  33.         super();  
  34.     }  
  35.       
  36.     /** 
  37.      * 验证登陆 
  38.      */  
  39.     @Override  
  40.     protected AuthenticationInfo doGetAuthenticationInfo(  
  41.             AuthenticationToken authcToken) throws AuthenticationException {  
  42.         UsernamePasswordToken token = (UsernamePasswordToken) authcToken;  
  43.         System.out.println(token.getUsername());  
  44.         User user = userService.findUserByLoginName(token.getUsername());  
  45.         System.out.println(user);  
  46.         CipherUtil cipher = new CipherUtil();//MD5加密  
  47.         if (user != null) {  
  48.             return new SimpleAuthenticationInfo(user.getName(), cipher.generatePassword(user.getPassword()), getName());  
  49.         }else{  
  50.             throw new AuthenticationException();  
  51.         }  
  52.     }  
  53.   
  54.     /** 
  55.      * 登陆成功之后,进行角色和权限验证 
  56.      */  
  57.     @Override  
  58.     protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {  
  59.         /*这里应该根据userName使用role和permission 的serive层来做判断,并将对应 的权限加进来,下面简化了这一步*/  
  60.         Set roleNames = new HashSet();  
  61.         Set permissions = new HashSet();  
  62.         roleNames.add("admin");//添加角色。对应到index.jsp  
  63.         roleNames.add("administrator");  
  64.         permissions.add("create");//添加权限,对应到index.jsp  
  65.         permissions.add("login.do?main");  
  66.         permissions.add("login.do?logout");  
  67.         SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(roleNames);  
  68.         info.setStringPermissions(permissions);  
  69.         return info;  
  70.     }  
  71.   
  72.   
  73.     /** 
  74.      * 清除所有用户授权信息缓存. 
  75.      */  
  76.     public void clearCachedAuthorizationInfo(String principal) {  
  77.         SimplePrincipalCollection principals = new SimplePrincipalCollection(principal, getName());  
  78.         clearCachedAuthorizationInfo(principals);  
  79.     }  
  80.   
  81.   
  82.     /** 
  83.      * 清除所有用户授权信息缓存. 
  84.      */  
  85.     public void clearAllCachedAuthorizationInfo() {  
  86.         Cache cache = getAuthorizationCache();  
  87.         if (cache != null) {  
  88.             for (Object key : cache.keys()) {  
  89.                 cache.remove(key);  
  90.             }  
  91.         }  
  92.     }  
  93.   
  94. //  @PostConstruct  
  95. //  public void initCredentialsMatcher() {//MD5鍔犲瘑  
  96. //      HashedCredentialsMatcher matcher = new HashedCredentialsMatcher(ALGORITHM);  
  97. //      setCredentialsMatcher(matcher);  
  98. //  }  
  99. }  

3、shiro的配置文件 :spring-shiro.xml

内容如下:

[html]  view plain  copy
  1.   
  2.   
  3.   
  4.     Shiro Configuration  
  5.   
  6.       
  7.       
  8.           
  9.           
  10.       
  11.   
  12.       
  13.       
  14.           
  15.       
  16.   
  17.       
  18.       
  19.           
  20.           
  21.           
  22.           
  23.           
  24.               
  25.                 /index.html = authc  
  26.                 /checkLogin.do = anon  
  27.                 /login.do = anon  
  28.                 /logout.html = anon  
  29.                 /** = authc  
  30.               
  31.           
  32.       
  33.   
  34.       
  35.       
  36.   
  37.       
  38.       
  39.   
  40.       
  41.       
  42.           
  43.       
  44.   
  45.       
  46.           
  47.       
  48.   

这里简要说明下:

(1)

securityManager:这个属性是必须的。 loginUrl:没有登录的用户请求需要登录的页面时自动跳转到登录页面,不是必须的属性,不输入地址的话会自动寻找项目web项目的根目录下的”/login.jsp”页面。 successUrl:登录成功默认跳转页面,不配置则跳转至”/”。如果登陆前点击的一个需要登录的页面,则在登录自动跳转到那个需要登录的页面。不跳转到此。 unauthorizedUrl:没有权限默认跳转的页面。

(2)

anon:例子/admins/**=anon 没有参数,表示可以匿名使用。 authc:例如/admins/user/**=authc表示需要认证(登录)才能使用,没有参数 roles:例子/admins/user/**=roles[admin],参数可以写多个,多个时必须加上引号,并且参数之间用逗号分割,当有多个参数时,例如admins/user/**=roles["admin,guest"],每个参数通过才算通过,相当于hasAllRoles()方法。 perms:例子/admins/user/**=perms[user:add:*],参数可以写多个,多个时必须加上引号,并且参数之间用逗号分割,例如/admins/user/**=perms["user:add:*,user:modify:*"],当有多个参数时必须每个参数都通过才通过,想当于isPermitedAll()方法。 rest:例子/admins/user/**=rest[user],根据请求的方法,相当于/admins/user/**=perms[user:method] ,其中method为post,get,delete等。 port:例子/admins/user/**=port[8081],当请求的url的端口不是8081是跳转到schemal://serverName:8081?queryString,其中schmal是协议http或https等,serverName是你访问的host,8081是url配置里port的端口,queryString 是你访问的url里的?后面的参数。 authcBasic:例如/admins/user/**=authcBasic没有参数表示httpBasic认证 ssl:例子/admins/user/**=ssl没有参数,表示安全的url请求,协议为https user:例如/admins/user/**=user没有参数表示必须存在用户,当登入操作时不做检查 注:anon,authcBasic,auchc,user是认证过滤器, perms,roles,ssl,rest,port是授权过滤器

4、web.xml配置解读shiro的配置文件(上面的)

[html]  view plain  copy
  1.   
  2.   
  3.     Archetype Created Web Application  
  4.       
  5.       
  6.         /login.do  
  7.       
  8.   
  9.       
  10.       
  11.         contextConfigLocation  
  12.         classpath:application.xml,classpath:shiro/spring-shiro.xml  
  13.       
  14.       
  15.       
  16.         webAppRootKey  
  17.         springmvc.root  
  18.       
  19.   
  20.   
  21.       
  22.       
  23.         SpringEncodingFilter  
  24.         org.springframework.web.filter.CharacterEncodingFilter  
  25.           
  26.             encoding  
  27.             UTF-8  
  28.           
  29.           
  30.             forceEncoding  
  31.             true  
  32.           
  33.       
  34.       
  35.         SpringEncodingFilter  
  36.         /*  
  37.       
  38.       
  39.       
  40.         shiroFilter  
  41.         org.springframework.web.filter.DelegatingFilterProxy  
  42.           
  43.             targetFilterLifecycle  
  44.             true  
  45.           
  46.       
  47.       
  48.         shiroFilter  
  49.         /*  
  50.       
  51.   
  52.       
  53.       
  54.           
  55.         log4jConfigLocation  
  56.         classpath:log4j.properties  
  57.       
  58.       
  59.           
  60.         log4jRefreshInterval  
  61.         6000  
  62.       
  63.       
  64.         org.springframework.web.util.Log4jConfigListener  
  65.       
  66.   
  67.       
  68.         org.springframework.web.context.ContextLoaderListener  
  69.       
  70.       
  71.       
  72.       
  73.         org.springframework.web.util.IntrospectorCleanupListener  
  74.       
  75.   
  76.       
  77.       
  78.         dispatcherServlet  
  79.         org.springframework.web.servlet.DispatcherServlet  
  80.           
  81.             contextConfigLocation  
  82.               
  83.             classpath:springmvc/spring-mvc.xml  
  84.           
  85.         1  
  86.       
  87.       
  88.       
  89.         dispatcherServlet  
  90.         /  
  91.       
  92.   
  93.       
  94.       
  95.         15  
  96.       
  97.       
  98.         404  
  99.         /WEB-INF/views/error/404.jsp  
  100.       
  101.       
  102.         401  
  103.         /WEB-INF/views/error/401.jsp  
  104.       
  105.   

这里不仅配置了SpringMVC还要配置Shiro!

5、登陆页面login.jsp

以下是默认登陆的界面

[html]  view plain  copy
  1.   
  2.   
  3.   
  4.   
  5.   
  6.   
  7. Insert title here  
  8.   
  9.   
  10.       
  11.         username:   
  12.         password:   
  13.           
  14.       
  15.   
  16.   

6、验证成功页面index.jsp

如果用户名和密码正确后,跳转到的页面

[html]  view plain  copy
  1.   
  2.   
  3.   
  4.   
  5.   
  6.   
  7.   
  8. Shiro登陆实例  
  9.   
  10.   
  11.     Shiro登陆实例退出  
  12.     一、验证当前用户是否为"访客",即未认证(包含未记住)的用户  
  13.         
  14.         Hi there!  Please Login or Signup today!    
  15.       
  16.     二、认证通过或已记住的用户  
  17.         
  18.         Welcome back John!  Not John? Click here to login.   
  19.       
  20.     三、已认证通过的用户。不包含已记住的用户,这是与user标签的区别所在。  
  21.         
  22.         Update your contact information.    
  23.       
  24.     四、未认证通过用户,与authenticated标签相对应。与guest标签的区别是,该标签包含已记住用户。  
  25.         
  26.         Please login in order to update your credit card information.    
  27.         
  28.     五、输出当前用户信息,通常为登录帐号信息  
  29.     Hello, , how are you today?    
  30.     六、验证当前用户是否属于该角色  
  31.         
  32.         Administer the system    
  33.         
  34.     七、与hasRole标签逻辑相反,当用户不属于该角色时验证通过  
  35.         
  36.         Sorry, you are not allowed to administer the system.    
  37.         
  38.     八、验证当前用户是否属于以下任意一个角色。  
  39.       
  40.         You are either a developer,manager, or administrator.    
  41.       
  42.    九、验证当前用户权限。  
  43.         
  44.       当前用户拥有增加的权限!!!!!!!!!!!!!  
  45.         
  46.   
  47.         
  48.        当前用户拥有删除的权限!!!!!!!!!!!!!  
  49.         
  50.   
  51.   
其它页面就不说了,具体看工程吧!

7、controller层来看看

这里/{id}/showUser主要是来验证是否连接成功(现在无法测试了),当然在工程里你也可以到src/test/java里的包com.lin.service下的UserServiceTest.java,那里我也写了一个单元测试的类。

[java]  view plain  copy
  1. package com.lin.controller;  
  2.   
  3. import javax.servlet.http.HttpServletRequest;  
  4. import javax.servlet.http.HttpServletResponse;  
  5.   
  6. import org.apache.shiro.SecurityUtils;  
  7. import org.apache.shiro.authc.UsernamePasswordToken;  
  8. import org.apache.shiro.subject.Subject;  
  9. import org.slf4j.Logger;  
  10. import org.slf4j.LoggerFactory;  
  11. import org.springframework.beans.factory.annotation.Autowired;  
  12. import org.springframework.stereotype.Controller;  
  13. import org.springframework.ui.Model;  
  14. import org.springframework.web.bind.annotation.PathVariable;  
  15. import org.springframework.web.bind.annotation.RequestMapping;  
  16. import org.springframework.web.bind.annotation.RequestMethod;  
  17. import org.springframework.web.bind.annotation.ResponseBody;  
  18.   
  19. import com.lin.domain.User;  
  20. import com.lin.realm.ShiroDbRealm;  
  21. import com.lin.service.UserService;  
  22. import com.lin.utils.CipherUtil;  
  23.   
  24. @Controller  
  25. public class UserControler {  
  26.     private static Logger logger = LoggerFactory.getLogger(ShiroDbRealm.class);  
  27.     @Autowired  
  28.     private UserService userService;  
  29.       
  30.     /** 
  31.      * 验证springmvc与batis连接成功 
  32.      * @param id 
  33.      * @param request 
  34.      * @return 
  35.      */  
  36.     @RequestMapping("/{id}/showUser")  
  37.     public String showUser(@PathVariable int id, HttpServletRequest request) {  
  38.         User user = userService.getUserById(id);  
  39.         System.out.println(user.getName());  
  40.         request.setAttribute("user", user);  
  41.         return "showUser";  
  42.     }  
  43.       
  44.     /** 
  45.      * 初始登陆界面 
  46.      * @param request 
  47.      * @return 
  48.      */  
  49.     @RequestMapping("/login.do")  
  50.     public String tologin(HttpServletRequest request, HttpServletResponse response, Model model){  
  51.         logger.debug("来自IP[" + request.getRemoteHost() + "]的访问");  
  52.         return "login";  
  53.     }  
  54.       
  55.     /** 
  56.      * 验证用户名和密码 
  57.      * @param request 
  58.      * @return 
  59.      */  
  60.     @RequestMapping("/checkLogin.do")  
  61.     public String login(HttpServletRequest request) {  
  62.         String result = "login.do";  
  63.         // 取得用户名  
  64.         String username = request.getParameter("username");  
  65.         //取得 密码,并用MD5加密  
  66.         String password = CipherUtil.generatePassword(request.getParameter("password"));  
  67.         //String password = request.getParameter("password");  
  68.         UsernamePasswordToken token = new UsernamePasswordToken(username, password);  
  69.           
  70.         Subject currentUser = SecurityUtils.getSubject();  
  71.         try {  
  72.             System.out.println("----------------------------");  
  73.             if (!currentUser.isAuthenticated()){//使用shiro来验证  
  74.                 token.setRememberMe(true);  
  75.                 currentUser.login(token);//验证角色和权限  
  76.             }  
  77.             System.out.println("result: " + result);  
  78.             result = "index";//验证成功  
  79.         } catch (Exception e) {  
  80.             logger.error(e.getMessage());  
  81.             result = "login。do";//验证失败  
  82.         }  
  83.         return result;  
  84.     }  
  85.     
  86.     /** 
  87.      * 退出 
  88.      * @return 
  89.      */  
  90.     @RequestMapping(value = "/logout")    
  91.     @ResponseBody    
  92.     public String logout() {    
  93.     
  94.         Subject currentUser = SecurityUtils.getSubject();    
  95.         String result = "logout";    
  96.         currentUser.logout();    
  97.         return result;    
  98.     }    
  99.        
  100. }  
再来看看效果吧!
关注
打赏
1662604032
查看更多评论
立即登录/注册

微信扫码登录

0.0705s