将 Shiro 作为应用的权限基础

认证就是验证用户身份的过程。在认证过程中,用户需要提交实体信息(Principals)和凭据信息(Credentials)以检验用户是否合法。最常见的“实体/凭证”组合便是“用户名/密码”组合。 

 

一、认证过程 

 

1、收集实体/凭据信息 

Java代码  

[java]   view plain  copy
  1. UsernamePasswordToken token = new UsernamePasswordToken(username, password);  
  2. token.setRememberMe(true);    

UsernamePasswordToken支持最常见的用户名/密码的认证机制。同时,由于它实现了RememberMeAuthenticationToken接口,我们可以通过令牌设置“记住我”的功能。 

但是,“已记住”和“已认证”是有区别的: 

已记住的用户仅仅是非匿名用户,你可以通过subject.getPrincipals()获取用户信息。但是它并非是认证通过的用户,当你访问需要认证用户的功能时,你仍然需要重新提交认证信息。 

这一区别可以参考淘宝网站,网站会默认记住登录的用户,再次访问网站时,对于非敏感的页面功能,页面上会显示记住的用户信息,但是当你访问网站账户信息时仍然需要再次进行登录认证。 

 

2、提交实体/凭据信息 

Java代码  

    

[java]   view plain  copy
  1. Subject currentUser = SecurityUtils.getSubject();    
  2. currentUser.login(token);   
 

收集了实体/凭据信息之后,我们可以通过SecurityUtils工具类,获取当前的用户,然后通过调用login方法提交认证。 

 

3、认证

如果我们自定义Realm实现,比如我后面的例子中,自定义了ShiroDbRealm类,当执行currentUser.login(token)时,会先执行ShiroDbRealm.doGetAuthenticationInfo()进行登录认证。

    

[java]   view plain  copy
  1. /** 
  2.      * 验证当前登录的Subject 
  3.      * @see经测试:本例中该方法的调用时机为LoginController.login()方法中执行Subject.login()时 
  4.      */   
  5. protectedAuthenticationInfo doGetAuthenticationInfo(  
  6. AuthenticationTokenauthcToken) throws AuthenticationException {  
  7. //获取基于用户名和密码的令牌   
  8.        //实际上这个authcToken是从LoginController里面currentUser.login(token)传过来的   
  9. UsernamePasswordTokentoken = (UsernamePasswordToken) authcToken;  
  10.    
  11. //从数据库中查询用户用信息  
  12. Useruser = userService.getByAccount(token.getUsername());  
  13. if(user != null) {  
  14.  //此处无需比对,比对的逻辑Shiro会做,我们只需返回一个和令牌相关的正确的验证信息   
  15. returnnew SimpleAuthenticationInfo(user.getAccount(), user  
  16. .getPassword(),getName());  
  17. }else {  
  18.  //没有返回登录用户名对应的SimpleAuthenticationInfo对象时,就会在LoginController中抛出UnknownAccountException异常   
  19. returnnull;  
  20. }  
  21. }  

 

 

4、认证处理 

Java代码  

收藏代码

    

[java]   view plain  copy
  1. try {    
  2.     currentUser.login(token);    
  3. catch ( UnknownAccountException uae ) { ...    
  4. catch ( IncorrectCredentialsException ice ) { ...    
  5. catch ( LockedAccountException lae ) { ...    
  6. catch ( ExcessiveAttemptsException eae ) { ...    
  7. } ... catch your own ...    
  8. catch ( AuthenticationException ae ) {    
  9.     //unexpected error?    
  10. }    

如果login方法执行完毕且没有抛出任何异常信息,那么便认为用户认证通过。之后在应用程序任意地方调用SecurityUtils.getSubject()都可以获取到当前认证通过的用户实例,使用subject.isAuthenticated()判断用户是否已验证都将返回true. 

相反,如果login方法执行过程中抛出异常,那么将认为认证失败。Shiro有着丰富的层次鲜明的异常类来描述认证失败的原因,如代码示例。 

 

二、登出操作 

登出操作可以通过调用subject.logout()来删除你的登录信息,如: 

Java代码  

 currentUser.logout(); //removes all identifying information and invalidates their session too.  收藏代码

当执行完登出操作后,Session信息将被清空,subject将被视作为匿名用户。 

 

三、认证内部处理机制 

以上,是Shiro认证在应用程序中的处理过程,下面将详细解说Shiro认证的内部处理机制。 


 

 

如上图,我们通过Shiro架构图的认证部分,来说明Shiro认证内部的处理顺序: 

1、应用程序构建了一个终端用户认证信息的AuthenticationToken实例后,调用Subject.login方法。 

2、Sbuject会委托应用程序设置的securityManager实例调用securityManager.login(token)方法。 


3、SecurityManager接受到token(令牌)信息后会委托内置的Authenticator的实例(通常都是ModularRealmAuthenticator类的实例)调用authenticator.authenticate(token).ModularRealmAuthenticator在认证过程中会对设置的一个或多个Realm实例进行适配,它实际上为Shiro提供了一个可拔插的认证机制。

 

4、如果在应用程序中配置了多个Realm,ModularRealmAuthenticator会根据配置的AuthenticationStrategy(认证策略)来进行多Realm的认证过程。在Realm被调用后,AuthenticationStrategy将对每一个Realm的结果作出响应。 

注:如果应用程序中仅配置了一个Realm,Realm将被直接调用而无需再配置认证策略。 


5、Realm将调用getAuthenticationInfo(token);getAuthenticationInfo方法就是实际认证处理,我们通过覆盖Realm的doGetAuthenticationInfo方法来编写我们自定义的认证处理。 

 

 

四、使用多个Realm的处理机制: 

AuthenticationStrategy(认证策略) 

当应用程序配置了多个Realm时,ModularRealmAuthenticator将根据认证策略来判断认证成功或是失败。 

例如,如果只有一个Realm验证成功,而其他Realm验证失败,那么这次认证是否成功呢?如果大多数的Realm验证成功了,认证是否就认为成功呢?或者,一个Realm验证成功后,是否还需要判断其他Realm的结果?认证策略就是根据应用程序的需要对这些问题作出决断。 

认证策略是一个无状态的组件,在认证过程中会经过4次的调用: 

  • 在所有Realm被调用之前
  • 在调用RealmgetAuthenticationInfo方法之前
  • 在调用RealmgetAuthenticationInfo方法之后
  • 在所有Realm被调用之后

认证策略的另外一项工作就是聚合所有Realm的结果信息封装至一个AuthenticationInfo实例中,并将此信息返回,以此作为Subject的身份信息。 

Shiro有3中认证策略的具体实现: 

 

AtLeastOneSuccessfulStrategy

只要有一个(或更多)的Realm验证成功,那么认证将被视为成功

FirstSuccessfulStrategy

第一个Realm验证成功,整体认证将被视为成功,且后续Realm将被忽略

AllSuccessfulStrategy

所有Realm成功,认证才视为成功

ModularRealmAuthenticator内置的认证策略默认实现是AtLeastOneSuccessfulStrategy 方式,因为这种方式也是被广泛使用的一种认证策略。

 

五、认证的代码示例

LoginController:处理登录请求的Controller类

[java]   view plain  copy
  1. <span style="font-size:18px">packageorg.shiro.demo.controller;  
  2.    
  3. importjava.awt.Color;  
  4. importjava.awt.image.BufferedImage;  
  5. importjava.io.IOException;  
  6.    
  7. importjavax.imageio.ImageIO;  
  8. importjavax.servlet.http.HttpServletRequest;  
  9. importjavax.servlet.http.HttpServletResponse;  
  10. importjavax.servlet.http.HttpSession;  
  11.    
  12. importorg.apache.commons.lang.StringUtils;  
  13. importorg.apache.shiro.SecurityUtils;  
  14. importorg.apache.shiro.authc.AuthenticationException;  
  15. importorg.apache.shiro.authc.UsernamePasswordToken;  
  16. importorg.apache.shiro.subject.Subject;  
  17. importorg.apache.shiro.web.util.WebUtils;  
  18. importorg.shiro.demo.entity.User;  
  19. importorg.shiro.demo.util.ValidateCode;  
  20. importorg.springframework.stereotype.Controller;  
  21. importorg.springframework.web.bind.annotation.RequestMapping;  
  22. importorg.springframework.web.bind.annotation.RequestMethod;  
  23.    
  24. @Controller  
  25. publicclass LoginController {  
  26.    
  27. @RequestMapping(value= "/login")  
  28. publicString login(User user,HttpSession session, HttpServletRequest request){  
  29. //判断验证码  
  30. Stringcode = (String) session.getAttribute("validateCode");  
  31. StringsubmitCode = WebUtils.getCleanParam(request, "validateCode");  
  32.    
  33. if(StringUtils.isEmpty(submitCode) ||!StringUtils.equals(code,submitCode.toLowerCase())) {  
  34. return"redirect:/";  
  35. }  
  36.    
  37. //获取当前的Subject   
  38. SubjectcurUser = SecurityUtils.getSubject();  
  39. UsernamePasswordTokentoken = new UsernamePasswordToken(user.getAccount(),user.getPassword());  
  40. token.setRememberMe(true);  
  41. try {  
  42.  //在调用了login方法后,SecurityManager会收到AuthenticationToken,并将其发送给已配置的Realm执行必须的认证检查   
  43.            //每个Realm都能在必要时对提交的AuthenticationTokens作出反应   
  44.            //所以这一步在调用login(token)方法时,它会走到ShiroDbRealm.doGetAuthenticationInfo()方法中  
  45. curUser.login(token);  
  46.    
  47. return"/system/main";  
  48. }catch(AuthenticationException e) {  
  49. //通过处理Shiro的运行时AuthenticationException就可以控制用户登录失败或密码错误时的情景  
  50. token.clear();  
  51. return"redirect:/";  
  52. }  
  53. }  
  54.    
  55. }</span>  


 

 

ShiroDbRealm:自定义的指定Shiro验证用户登录的类

[java]   view plain  copy
  1. <span style="font-size:18px">packageorg.shiro.demo.service.realm;  
  2.    
  3. importjava.util.ArrayList;  
  4. importjava.util.List;  
  5.    
  6. importjavax.annotation.Resource;  
  7.    
  8. importorg.apache.commons.lang.StringUtils;  
  9. importorg.apache.shiro.authc.AuthenticationException;  
  10. importorg.apache.shiro.authc.AuthenticationInfo;  
  11. importorg.apache.shiro.authc.AuthenticationToken;  
  12. importorg.apache.shiro.authc.SimpleAuthenticationInfo;  
  13. importorg.apache.shiro.authc.UsernamePasswordToken;  
  14. importorg.apache.shiro.authz.AuthorizationException;  
  15. importorg.apache.shiro.authz.AuthorizationInfo;  
  16. importorg.apache.shiro.authz.SimpleAuthorizationInfo;  
  17. importorg.apache.shiro.realm.AuthorizingRealm;  
  18. importorg.apache.shiro.subject.PrincipalCollection;  
  19. importorg.shiro.demo.service.IUserService;  
  20.    
  21. /** 
  22.  * 自定义的指定Shiro验证用户登录的类 
  23.  * @author TCH 
  24.  * 
  25.  */  
  26. publicclass ShiroDbRealm extends AuthorizingRealm{  
  27.    
  28. //@Resource(name="userService")  
  29. privateIUserService userService;  
  30.    
  31. publicvoid setUserService(IUserService userService) {  
  32. this.userService= userService;  
  33. }  
  34.    
  35.      
  36.     /** 
  37.      * 验证当前登录的Subject 
  38.      * @see经测试:本例中该方法的调用时机为LoginController.login()方法中执行Subject.login()时 
  39.      */   
  40. protectedAuthenticationInfo doGetAuthenticationInfo(  
  41. AuthenticationTokenauthcToken) throws AuthenticationException {  
  42. //获取基于用户名和密码的令牌   
  43.        //实际上这个authcToken是从LoginController里面currentUser.login(token)传过来的   
  44. UsernamePasswordTokentoken = (UsernamePasswordToken) authcToken;  
  45.    
  46. //从数据库中查询用户用信息  
  47. Useruser = userService.getByAccount(token.getUsername());  
  48. if(user != null) {  
  49.  //此处无需比对,比对的逻辑Shiro会做,我们只需返回一个和令牌相关的正确的验证信息   
  50. returnnew SimpleAuthenticationInfo(user.getAccount(), user  
  51. .getPassword(),getName());  
  52. }else {  
  53.  //没有返回登录用户名对应的SimpleAuthenticationInfo对象时,就会在LoginController中抛出UnknownAccountException异常   
  54. returnnull;  
  55. }  
  56. }  
  57. }</span>  


Shiro学习的系列文章

将 Shiro 作为应用的权限基础 一:shiro的整体架构

将 Shiro 作为应用的权限基础 二:shiro认证

将 Shiro 作为应用的权限基础 三:shiro授权

将 Shiro 作为应用的权限基础 四:配置说明

将 Shiro 作为应用的权限基础 五:SpringMVC+Apache Shiro+JPAhibernate)整合配置

将 Shiro 作为应用的权限基础 六:源码以及下载地址

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值