下面讲解基于实战系列一,所以相关的java文件获取pom.xml及其log4j文件同样适用于本次讲解。

一、Using Shiro

Using Shiro 现在我们的 SecurityManager 已经设置好并可以使用了,现在我们能够开始做一些我们真正关心的事情——执行安 全操作。   当保护我们的应用程序时,我们对自己可能提出的最为相关的问题是“当前用户是谁”或“当前用户是否被允许做 XXX”。当我们编写代码或设计用户接口时,问这些问题是很常见的:应用程序通常是基于用户的背景情况建立的, 且你想基于每个用户标准体现(保障)功能。因此,对于我们考虑应用程序安全的最自然的方式是基于当前用户。 Shiro 的 API 使用它的 Subject 概念从根本上代表了“当前用户”的概念。

几乎在所有的环境中,你可以通过下面的调用获取当前正在执行的用户:

  1. Subject currentUser=SecurityUtils.getSubject();

使用 SecurityUtils.getSubject(),我们可以获得当前正在执行的 Subject。Subject 是一个安全术语,它基本上的意思是 “当前正在执行的用户的特定的安全视图”。它并没有被称为"User"是因为"User"一词通常和人类相关联。在安全 界,术语"Subject"可以表示为人类,而且可是第三方进程,cron job,daemon account,或其他类似的东西。它仅仅 意味着“该事物目前正与软件交互”。对于大多数的意图和目的,你可以把 Subject 看成是 Shiro 的"User"概念。

getSubject()在一个独立的应用程序中调用,可以返回一个在应用程序特定位置的基于用户数据的 Subject,并且在服 务器环境中(例如,Web 应用程序),它获取的 Subject 是基于关联了当前线程或传入请求的用户数据的。

二、现在你拥有了一个 Subject,你能拿它来做什么?

如果你想在应用程序的当前会话中使事物对于用户可用,你可以获得他们的会话:

  1. Session session = currentUser.getSession();
  2.  
  3. session.setAttribute("someKey", "aValue");

Session 是一个 Shiro 的特定实例,它提供了大部分你经常与 HttpSessoins 使用的东西,除了一些额外的好处以及一 个巨大的区别:它不需要一个 HTTP 环境!   如果在一个 Web 应用程序内部部署,默认的 Session 将会是基于 HttpSession 的。但在一个非 Web 环境中,像这个简单的教程应用程序,Shiro 将会默认自动地使用它的 Enterprise Session Management。这意味着你会使用相同的 API 在你的应用程序,在任何层,不论部署环境!这开辟了应用程序的新世界,由于任何需要会话的应用程序不必 再被强制使用 HttpSession 或 EJB Stateful Session Beans。并且,任何客户端技术现在能够共享会话数据。

三、因此,现在你能获取一个 Subject 以及他们的 Session。如果他们被允许做某些事,如对角色和权限的检查,像“检 查”真正有用的地方在哪呢?

嗯,我们只能为一个已知的用户做这些检查。我们上面的 Subject 实例代表了当前用户,但谁又是当前用户?呃, 他们是匿名的——也就是说,直到直到他们至少登录一次。那么,让我像下面这样做:

  1. if(!currentUser.isAuthenticated()) {
  2. UsernamePasswordToken token = new UsernamePasswordToken("lonestarr","vespa");
  3. token.setRememberMe(true);
  4.  
  5. try {
  6. currentUser.login(token);
  7. } catch (UnknownAccountException e) {
  8. // TODO: handle exception
  9. log.info("there is no user with username of"+token.getPrincipal());
  10. }catch (IncorrectCredentialsException e) {
  11. // TODO: handle exception
  12. log.info("Password for account"+token.getPrincipal()+"was incorrect");
  13. }catch (LockedAccountException e) {
  14. // TODO: handle exception
  15. log.info("The account for username"+token.getPrincipal()+"is locked."+"Please contact your adminstrator to unlock it.");
  16. }
  17. }

比方说,

他们是是谁:

  1. log.info("User["+currentUser.getPrincipal()+"]"+"logged in successfully");

判断他们是否有特定的角色:

  1. if(currentUser.hasRole("schwartz")) {
  2. log.info("May the schwartz be with you!");
  3. }else {
  4. log.info("Hello,mere mortal");
  5. }

还可以判断他们是否有权限在一个确定类型的实体上进行操作:

  1. if(currentUser.isPermitted("winnebego:drive:eagle5")) {
  2. log.info("You are permitted to 'drive' the winnebago with license plate (id) 'eagle5' . " + "Here are the keys - have fun!");
  3. }else {
  4. log.info("Sorry,you aren't allowed to drive the 'eagle5' winnebago");
  5. }

最后,当用户完成了对应用程序的使用,他们可以注销:

  1. currentUser.logout();

以上代码完全版如下所示:

  1. import org.apache.log4j.Logger;
  2. import org.apache.shiro.SecurityUtils;
  3. import org.apache.shiro.authc.IncorrectCredentialsException;
  4. import org.apache.shiro.authc.LockedAccountException;
  5. import org.apache.shiro.authc.UnknownAccountException;
  6. import org.apache.shiro.authc.UsernamePasswordToken;
  7. import org.apache.shiro.config.IniSecurityManagerFactory;
  8. import org.apache.shiro.mgt.SecurityManager;
  9. import org.apache.shiro.session.Session;
  10. import org.apache.shiro.util.Factory;
  11.  
  12. public class Tutorial {
  13.  
  14. private static Logger log = Logger.getLogger(Tutorial.class);
  15.  
  16. public static void main(String[] args) {
  17.  
  18. log.info("My First Apache Shiro Application");
  19.  
  20. Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
  21.  
  22. SecurityManager securityManager = factory.getInstance();
  23.  
  24. SecurityUtils.setSecurityManager(securityManager);
  25.  
  26. org.apache.shiro.subject.Subject currentUser = SecurityUtils.getSubject();
  27.  
  28. Session session = currentUser.getSession();
  29.  
  30. session.setAttribute("someKey", "aValue");
  31.  
  32. String value = (String) session.getAttribute("someKey");
  33.  
  34. if(value.equals("aValue")) {
  35. log.info("Retrieved the correct value!["+value+"]");
  36. }
  37.  
  38. if(!currentUser.isAuthenticated()) {
  39. UsernamePasswordToken token = new UsernamePasswordToken("lonestarr","vespa");
  40. token.setRememberMe(true);
  41.  
  42. try {
  43. currentUser.login(token);
  44. } catch (UnknownAccountException e) {
  45. // TODO: handle exception
  46. log.info("there is no user with username of"+token.getPrincipal());
  47. }catch (IncorrectCredentialsException e) {
  48. // TODO: handle exception
  49. log.info("Password for account"+token.getPrincipal()+"was incorrect");
  50. }catch (LockedAccountException e) {
  51. // TODO: handle exception
  52. log.info("The account for username"+token.getPrincipal()+"is locked."+"Please contact your adminstrator to unlock it.");
  53. }
  54. }
  55.  
  56. log.info("User["+currentUser.getPrincipal()+"]"+"logged in successfully");
  57.  
  58. //test a role
  59.  
  60. if(currentUser.hasRole("schwartz")) {
  61. log.info("May the schwartz be with you!");
  62. }else {
  63. log.info("Hello,mere mortal");
  64. }
  65.  
  66. if(currentUser.isPermitted("winnebego:drive:eagle5")) {
  67. log.info("You are permitted to 'drive' the winnebago with license plate (id) 'eagle5' . " + "Here are the keys - have fun!");
  68. }else {
  69. log.info("Sorry,you aren't allowed to drive the 'eagle5' winnebago");
  70. }
  71.  
  72. currentUser.logout();
  73. System.exit(0);
  74.  
  75. }
  76. }

以上是完整的示例说明如下:

从创建工厂加载配置文件shiro.init到创建安全管理器,到获取当前用户,到用sesion保存用户实例。

再到获取用户实例及其获取用户角色及其相应权限

shiro实战系列(二)之入门实战续的更多相关文章

  1. shiro实战系列(一)之入门实战

    一.什么是shiro? Apache Shiro 是一个强大而灵活的开源安全框架,它干净利落地处理身份认证,授权,企业会话管理和加密.   Apache Shiro 的首要目标是易于使用和理解.安全有 ...

  2. WCF开发实战系列二:使用IIS发布WCF服务

    WCF开发实战系列二:使用IIS发布WCF服务 (原创:灰灰虫的家http://hi.baidu.com/grayworm) 上一篇中,我们创建了一个简单的WCF服务,在测试的时候,我们使用VS200 ...

  3. [CXF REST标准实战系列] 二、Spring4.0 整合 CXF3.0,实现测试接口(转)

    转自:[CXF REST标准实战系列] 二.Spring4.0 整合 CXF3.0,实现测试接口 文章Points: 1.介绍RESTful架构风格 2.Spring配置CXF 3.三层初设计,实现W ...

  4. SQL Server 性能优化实战系列(二)

    SQL Server datetime数据类型设计.优化误区 一.场景 在SQL Server 2005中,有一个表TestDatetime,其中Dates这个字段的数据类型是datetime,如果你 ...

  5. ElasticSearch实战系列二: ElasticSearch的DSL语句使用教程---图文详解

    前言 在上一篇中介绍了ElasticSearch集群和kinaba的安装教程,本篇文章就来讲解下 ElasticSearch的DSL语句使用. ElasticSearch DSL 介绍 Elastic ...

  6. MP实战系列(二)之集成swagger

    其实与spring+springmvc+mybatis集成swagger没什么区别,只是之前写的太不好了,所以这次决定详细写. 提到swagger不得不提rest,rest是一种架构风格,里面有对不同 ...

  7. Java秒杀系统实战系列~商品秒杀代码实战

    摘要: 本篇博文是“Java秒杀系统实战系列文章”的第六篇,本篇博文我们将进入整个秒杀系统核心功能模块的代码开发,即“商品秒杀”功能模块的代码实战. 内容: “商品秒杀”功能模块是建立在“商品详情”功 ...

  8. 关东升的iOS实战系列图书 《iOS实战:入门与提高卷(Swift版)》已经上市

             承蒙广大读者的厚爱我的 <iOS实战:入门与提高卷(Swift版)>京东上市了,欢迎广大读者提出宝贵意见.http://item.jd.com/11766718.html ...

  9. Flume系列二之案例实战

    Flume案例实战 写在前面 通过前面一篇文章http://blog.csdn.net/liuge36/article/details/78589505的介绍我们已经知道flume到底是什么?flum ...

随机推荐

  1. 彻底理解voliate

    1.voliate简介 在上一篇文章中我们深入理解了java关键字synchronized,我们知道在java中还有一大神器就是关键volatile,可以说是和synchronized各领风骚,其中奥 ...

  2. Java基础——6种常用类讲解

    本文主要介绍几种Java中常用类的应用. 一.System类 从API当中我们可以看出,public final class System exends Object.System类包含一些有用的字段 ...

  3. Codeforces343D(SummerTrainingDay06-F dfs序+线段树)

    D. Water Tree time limit per test:4 seconds memory limit per test:256 megabytes input:standard input ...

  4. Codeforces731C(SummerTrainingDay06-M 并查集)

    C. Socks time limit per test:2 seconds memory limit per test:256 megabytes input:standard input outp ...

  5. longing加载中实例

    利用图片播放 <div class="wrap" id="wrap" style="position: inherit; height: 604 ...

  6. 从零开始学习html(十)CSS格式化排版——上

    一.文字排版--字体 <!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type&qu ...

  7. js之面向对象

    本文的面向对象分为ES6和ES6之前的,重点学习ES6的===============================一.面向对象 1.什么是面向对象 a)什么是对象:万物都可以抽象成对象 时间对象 ...

  8. 使用ArcGIS Runtime 100 进行本地GIS数据处理的注意事项

    如下图所示,如果需要使用ArcGIS Runtime 100 进行本地GIS数据处理,则需要依赖Local Server通过发布GP服务实现. 一.ArcGIS Runtime所使用的GPK是有版本限 ...

  9. Linux下安装VSCode

    进行下载 64位的包:地址: https://code.visualstudio.com/docs/?dv=linux64&build=insiders 1.解压: tar -zxvf cod ...

  10. TensorFlow数据读取方式:Dataset API

    英文详细版参考:https://www.cnblogs.com/jins-note/p/10243716.html Dataset API是TensorFlow 1.3版本中引入的一个新的模块,主要服 ...