shiro学习和使用实例(2)——登陆认证和授权

来源:互联网 发布:美术教程视频软件 编辑:程序博客网 时间:2024/06/01 09:15

技术背景, 控制转发用的是springMVC,持久化层使用Mybatis,缓存用redis,前台框架easyUI,自动化构建项目使用maven

一、导包

maven引入使用shiro所需的包

[java] view plain copy
  1. <dependency>  
  2.         <groupId>org.apache.shiro</groupId>  
  3.             <artifactId>shiro-core</artifactId>  
  4.             <version>1.2.1</version>  
  5.         </dependency>  
  6.         <dependency>  
  7.             <groupId>org.apache.shiro</groupId>  
  8.             <artifactId>shiro-web</artifactId>  
  9.             <version>1.2.1</version>  
  10.         </dependency>  
  11.         <dependency>  
  12.             <groupId>org.apache.shiro</groupId>  
  13.             <artifactId>shiro-spring</artifactId>  
  14.             <version>1.2.1</version>  
  15.         </dependency>  

二、登陆
[java] view plain copy
  1. @RequestMapping(value = "/login")  
  2.  OperationPrompt login(String userID, String password,boolean rememberMe)   
[java] view plain copy
  1.                throws NoSuchAlgorithmException {  
  2.     OperationPrompt op = null;  
  3.     String encodePassword = setEncrypting(password);//加密密码  
  4.     try{  
  5.         UsernamePasswordToken token = new UsernamePasswordToken(userID,encodePassword, false);  
  6.         token.setRememberMe(rememberMe);//设置记住我  自动登录  
  7.         SecurityUtils.getSubject().login(token);              
  8.         op = new OperationPrompt("用户登录成功"true);             
  9.     }catch(AuthenticationException ae){  
  10.         logger.error(ae);  
  11.         op = new OperationPrompt(ae.getMessage(), false);  
  12.         return op;  
  13.     }catch (Exception e) {  
  14.         // TODO Auto-generated catch block  
  15.         e.printStackTrace();  
  16.     }  
  17.     //查出用户所有角色的权限(包括会员等级的高级设置)  
  18.     List<Permission> permissions = new ArrayList<Permission>();  
  19.     com.isoftstone.securityframework.api.domain.Permission p = new com.isoftstone.securityframework.api.domain.Permission();  
  20.     p.setId(1);  
  21.     permissions.add(p);  
  22.     //避免空指针  
  23.     jedisPoolManager.set(SerializeUtils.serialize("permission:"+userID), SerializeUtils.serialize(permissions));  
  24.     //登陆成功后强制加载shiro权限缓存 避免懒加载 先清除   
  25.     restAuthRealm.forceShiroToReloadUserAuthorityCache();  
  26.     return op;  
  27. }  
      这是登陆的controller层方法,前台请求传入用户名和密码,还有是否记住我(shiro提供rememberMe功能),token携带用户名和密码交给SecurityUtils.getSubject()的主体,调用login登陆方法,调用login之后,shiro会委托SecurityManager进行身份认证,然后SecurityManager又会交给认证器Authenticator根据认证策略Authentication strategy进行认证逻辑,Authentication strategy认证策略就是有一个或者多个realm域来实现,因此最终的认证逻辑是写在我们自定义的realm域中,代码如下。
[java] view plain copy
  1.        /** 
  2.  * user login 
  3.  */  
  4. @Override  
  5. protected AuthenticationInfo doGetAuthenticationInfo(   AuthenticationToken token) throws AuthenticationException {  
  6.     UsernamePasswordToken authToken = (UsernamePasswordToken) token;  
  7.     String accountId =  authToken.getUsername();  
  8.     String password = String.valueOf(authToken.getPassword());  
  9.     // 登陆方法需要添加 平台参数  系统参数过滤  
  10.     AccountQuery query = new AccountQuery();  
  11.     query.setAccountId(accountId);  
  12.     query.setEmail(accountId);  
  13.     query.setMoblie(accountId);  
  14.     query.setPlatformId(platformLabel);  
  15.     query.setSubSystemId(systemLabel);  
  16.                //获取账户信息  
  17.                com.isoftstone.securityframework.api.domain.Account domainAccount =   
  18.                (com.isoftstone.securityframework.api.domain.Account)accountManagerImpl.getAccount(accountId,platformLabel,systemLabel);  
  19.     //判断用户是否存在  
  20.     if (null == domainAccount){  
  21.          throw new UnknownAccountException(String.format("账号[%s]不存在!", accountId));  
  22.     }  
  23.     //检查用户密码是否匹配  
  24.     if (!domainAccount.getPassword().equals(password)){  
  25.          throw new IncorrectCredentialsException (String.format("[%s]密码错误!", accountId));  
  26.     }  
  27.     //检查账号是否激活  
  28.     if(STATUS_NOTACTIVATED == domainAccount.getStatus()){  
  29.         throw new AuthenticationException (String.format("用户名[%s]未激活!", accountId));  
  30.     }  
  31.     //检查账号是否已冻结  
  32.     if(STATUS_FREEZEEXCED == domainAccount.getStatus()){  
  33.         throw new AuthenticationException (String.format("账号[%s]已冻结", accountId));  
  34.     }  
  35.     //检查账号身份是否冻结  
  36.     AccountCommon accountCommon = domainAccount.getAccCommon();  
  37.     if(accountCommon!=null){  
  38.         if(accountCommon.getIsBuyer()!=4 &&accountCommon.getIsSaler()!=4){  
  39.             throw new AuthenticationException (String.format("账号[%s]已经被冻结", accountId));  
  40.         }  
  41.     }  
  42.     //设置登录时间  
  43.     domainAccount.setLastLoginTime(DateUtils.getToday(DateUtils.TIMEF_FORMAT));  
  44.     accountManagerImpl.modify(domainAccount);  
  45.       
  46.     Account  authAccount = new Account();  
  47.     this.copyPropertiesToAuthAccount(domainAccount,authAccount);  
  48.               
  49.     //设置已认证的用户信息到用户对象中  
  50.     SimpleAuthenticationInfo simpleAuthInfo = new SimpleAuthenticationInfo(authAccount,authAccount.getPassword(),getName());  
  51.       
  52.     return simpleAuthInfo;  
  53. }  

      我们自定义的这个realm(restAuthRealm)继承AuthorizingRealm,认证逻辑写在doGetAuthenticationInfo方法中,根据前台传入的用户名和其他条件从数据库中查找出账号与前台传入的密码比对,判断是否为系统合法用法。当然还可以有其他的判断,比如这里的账号是否激活,是否冻结,是否存在。认证完成之后将已认证的用户信息返回。根据我的理解,返回的该用户信息应该存储在了redis的缓存中,以便系统其他地方用到当前登陆人的信息。

      接着,我们回到上面controller层的login方法,用户名、密码认证通过后,我们需要把原来缓存中的权限信息清除,也就是clear掉原来的授权信息SimpleAuthorizationInfo。

      //登陆成功后强制加载shiro权限缓存 避免懒加载 先清除 

     restAuthRealm.forceShiroToReloadUserAuthorityCache();

      完成这个操作,需要在我们自己定义的realm(restAuthRealm)中实现clearCachedAuthorizationInfo()方法,代码如下:

[java] view plain copy
  1. /**  
  2.      * 更新用户授权信息缓存.  
  3.      */    
  4.     public void clearCachedAuthorizationInfo(Object principal) {    
  5.         SimplePrincipalCollection principals = new SimplePrincipalCollection(principal, getName());    
  6.         clearCachedAuthorizationInfo(principals);    
  7.     }   
  8.       
  9.     //登陆成功后强制加载shiro权限缓存 避免懒加载 先清除     
  10.     public void forceShiroToReloadUserAuthorityCache(){  
  11.         this.clearCachedAuthorizationInfo(SecurityUtils.getSubject().getPrincipal());  
  12.         this.isPermitted(SecurityUtils.getSubject().getPrincipals(),"强制加载缓存,避免懒加载"+ System.currentTimeMillis());  
  13.     }  
      登陆成功后,清除原来的缓存授权信息。这里还调用了this.isPermitted()这个方法,它的作用是鉴权时用来判断是否有权限,那为什么会在清除缓存时调用?翻阅源码,原来isPermitted()的执行是这样的,它会先去缓存中获取授权信息(一般是权限信息),如果缓存中没有,那么它会调用doGetAuthenticationInfo(AuthenticationToken token)获取授权信息,然后用获取到的授权信息(权限)和传进来的权限标识比较,相等则表示具有该权限。由于我们在登陆成功后,首先是清理掉了原来的缓存授权信息(权限信息),因此我们又得往缓存中加入最新的授权信息以保证每次登陆进系统时都是最新的权限。根据isPermitted()的这个特点,这里一调用它,shiro就会去执行doGetAuthenticationInfo(AuthenticationToken token)方法(因为缓存中已经没有授权信息了),我们在自定义的realm(restAuthRealm)中重写了这个方法,代码如下:
[java] view plain copy
  1. /** 
  2.      * user permission query(Get authorization info from Cache first or get info from remote service )  
  3.      */  
  4.     @SuppressWarnings("unchecked")  
  5.     @Override  
  6.     protected AuthorizationInfo doGetAuthorizationInfo(  
  7.             PrincipalCollection principals) {  
  8.         Account  account1 = (Account)getAvailablePrincipal(principals);  
  9.         com.isoftstone.securityframework.api.domain.Account account = (com.isoftstone.securityframework.api.domain.Account) accountManagerImpl.get(account1.getId());  
  10.         List<com.isoftstone.securityframework.api.Permission> perms = new ArrayList<Permission>();  
  11.         //从数据库中查询权限  
  12.         perms = rolePermissionRealm.getSubjectPermission(account);  
  13.         Set<String> permSet = new HashSet<String>();  
  14.         if(null != perms){  
  15.             for (Permission perm : perms) {  
  16.                 String permissionName = perm.getPermissionName();  
  17.                 //将前缀去掉   
  18.                 int beginIndex = platformLabel.length() +systemLabel.length()+2;  
  19.                 permissionName = permissionName.substring(beginIndex);  
  20.                 permSet.add(permissionName);  
  21.             }  
  22.         }  
  23.         SimpleAuthorizationInfo simpleAuthInfo = new SimpleAuthorizationInfo();  
  24.         simpleAuthInfo.setStringPermissions(permSet);  
  25.         return simpleAuthInfo;  
  26.     }  
      doGetAuthenticationInfo(AuthenticationToken token)其实就是shiro的授权,它从数据库中获取当前登陆用户的权限,并把它放在授权信息SimpleAuthorizationInfo当中返回,存储到缓存中以便鉴权时使用。

      至此,登陆成功,shiro完成了两件事,其一,前台传过来的用户名和密码认证通过,其二,清除了原来缓存(redis)中的授权信息(权限),加上了当前用户最新的权限信息,方便后面的鉴权。

      鉴权方面,我会另外再写一篇博客来和大家讨论。

      存在不足:1、登陆时记住我这个功能没有详细描述 

                          2、isPermitted鉴权判断,权限标识未做说明
0 0