概念

  • 安全权限框架
  • 认证、授权、加密、会话管理、web集成、缓存

image.png

  • Authentication:身份认证 / 登录,验证用户是不是拥有相应的身份;
  • Authorization:授权,即权限验证,验证某个已认证的用户是否拥有某个权限;即判断用户是否能做事情,常见的如:验证某个用户是否拥有某个角色。或者细粒度的验证某个用户对某个资源是否具有某个权限;
  • Session Management:会话管理,即用户登录后就是一次会话,在没有退出之前,它的所有信息都在会话中;会话可以是普通 JavaSE 环境的,也可以是如 Web 环境的;
  • Cryptography:加密,保护数据的安全性,如密码加密存储到数据库,而不是明文存储;
  • Web Support:Web 支持,可以非常容易的集成到 Web 环境;
  • Caching:缓存,比如用户登录后,其用户信息、拥有的角色 / 权限不必每次去查,这样可以提高效率;
  • Concurrency:shiro 支持多线程应用的并发验证,即如在一个线程中开启另一个线程,能把权限自动传播过去;
  • Testing:提供测试支持;
  • Run As:允许一个用户假装为另一个用户(如果他们允许)的身份进行访问;
  • Remember Me:记住我,这个是非常常见的功能,即一次登录后,下次再来的话不用登录了。

image.png
Subject:主体,代表了当前 “用户”,这个用户不一定是一个具体的人,与当前应用交互的任何东西都是 Subject,如网络爬虫,机器人等;即一个抽象概念;所有 Subject 都绑定到 SecurityManager,与 Subject 的所有交互都会委托给 SecurityManager;可以把 Subject 认为是一个门面;SecurityManager 才是实际的执行者;
SecurityManager:安全管理器;即所有与安全有关的操作都会与 SecurityManager 交互;且它管理着所有 Subject;可以看出它是 Shiro 的核心,它负责与后边介绍的其他组件进行交互,如果学习过 SpringMVC,你可以把它看成 DispatcherServlet 前端控制器;
Realm:域,Shiro 从 Realm 获取安全数据(如用户、角色、权限),就是说 SecurityManager 要验证用户身份,那么它需要从 Realm 获取相应的用户进行比较以确定用户身份是否合法;也需要从 Realm 得到用户相应的角色 / 权限进行验证用户是否能进行操作;可以把 Realm 看成 DataSource,即安全数据源。
image.png

  • Subject:主体,可以看到主体可以是任何可以与应用交互的 “用户”;
  • SecurityManager:相当于 SpringMVC 中的 DispatcherServlet 或者 Struts2 中的 FilterDispatcher;是 Shiro 的心脏;所有具体的交互都通过 SecurityManager 进行控制;它管理着所有 Subject、且负责进行认证和授权、及会话、缓存的管理。
  • Authenticator:认证器,负责主体认证的,这是一个扩展点,如果用户觉得 Shiro 默认的不好,可以自定义实现;其需要认证策略(Authentication Strategy),即什么情况下算用户认证通过了;
  • Authorizer:授权器,或者访问控制器,用来决定主体是否有权限进行相应的操作;即控制着用户能访问应用中的哪些功能;
  • Realm:可以有 1 个或多个 Realm,可以认为是安全实体数据源,即用于获取安全实体的;可以是 JDBC 实现,也可以是 LDAP 实现,或者内存实现等等;由用户提供;注意:Shiro 不知道你的用户 / 权限存储在哪及以何种格式存储;所以我们一般在应用中都需要实现自己的 Realm;
  • SessionManager:如果写过 Servlet 就应该知道 Session 的概念,Session 呢需要有人去管理它的生命周期,这个组件就是 SessionManager;而 Shiro 并不仅仅可以用在 Web 环境,也可以用在如普通的 JavaSE 环境、EJB 等环境;所以呢,Shiro 就抽象了一个自己的 Session 来管理主体与应用之间交互的数据;这样的话,比如我们在 Web 环境用,刚开始是一台 Web 服务器;接着又上了台 EJB 服务器;这时想把两台服务器的会话数据放到一个地方,这个时候就可以实现自己的分布式会话(如把数据放到 Memcached 服务器);
  • SessionDAO:DAO 大家都用过,数据访问对象,用于会话的 CRUD,比如我们想把 Session 保存到数据库,那么可以实现自己的 SessionDAO,通过如 JDBC 写到数据库;比如想把 Session 放到 Memcached 中,可以实现自己的 Memcached SessionDAO;另外 SessionDAO 中可以使用 Cache 进行缓存,以提高性能;
  • CacheManager:缓存控制器,来管理如用户、角色、权限等的缓存的;因为这些数据基本上很少去改变,放到缓存中后可以提高访问的性能
  • Cryptography:密码模块,Shiro 提供了一些常见的加密组件用于如密码加密 / 解密的。

    quick start

  1. 导入依赖 ```xml

    1. <!-- https://mvnrepository.com/artifact/org.apache.shiro/shiro-core -->
    2. <dependency>
    3. <groupId>org.apache.shiro</groupId>
    4. <artifactId>shiro-core</artifactId>
    5. <version>1.8.0</version>
    6. </dependency>
    7. <dependency>
    8. <groupId>org.slf4j</groupId>
    9. <artifactId>jcl-over-slf4j</artifactId>
    10. <version>1.7.21</version>
    11. </dependency>
  1. <!-- https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-slf4j-impl -->
  2. <dependency>
  3. <groupId>org.apache.logging.log4j</groupId>
  4. <artifactId>log4j-slf4j-impl</artifactId>
  5. <version>2.17.1</version>
  6. </dependency>
  7. <!-- https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-core -->
  8. <dependency>
  9. <groupId>org.apache.logging.log4j</groupId>
  10. <artifactId>log4j-core</artifactId>
  11. <version>2.17.1</version>
  12. </dependency>
  13. <dependency>
  14. <groupId>log4j</groupId>
  15. <artifactId>log4j</artifactId>
  16. <version>1.2.17</version>
  17. </dependency>
  18. </dependencies>
  1. 2. 配置文件
  2. ```properties
  3. [users]
  4. # user 'root' with password 'secret' and the 'admin' role
  5. root = secret, admin
  6. # user 'guest' with the password 'guest' and the 'guest' role
  7. guest = guest, guest
  8. # user 'presidentskroob' with password '12345' ("That's the same combination on
  9. # my luggage!!!" ;)), and role 'president'
  10. presidentskroob = 12345, president
  11. # user 'darkhelmet' with password 'ludicrousspeed' and roles 'darklord' and 'schwartz'
  12. darkhelmet = ludicrousspeed, darklord, schwartz
  13. # user 'lonestarr' with password 'vespa' and roles 'goodguy' and 'schwartz'
  14. lonestarr = vespa, goodguy, schwartz
  15. # -----------------------------------------------------------------------------
  16. # Roles with assigned permissions
  17. #
  18. # Each line conforms to the format defined in the
  19. # org.apache.shiro.realm.text.TextConfigurationRealm#setRoleDefinitions JavaDoc
  20. # -----------------------------------------------------------------------------
  21. [roles]
  22. # 'admin' role has all permissions, indicated by the wildcard '*'
  23. admin = *
  24. # The 'schwartz' role can do anything (*) with any lightsaber:
  25. schwartz = lightsaber:*
  26. # The 'goodguy' role is allowed to 'drive' (action) the winnebago (type) with
  27. # license plate 'eagle5' (instance specific id)
  28. goodguy = winnebago:drive:eagle5
  1. quickstart ```java import org.apache.shiro.SecurityUtils; import org.apache.shiro.authc.*; import org.apache.shiro.ini.IniSecurityManagerFactory; import org.apache.shiro.mgt.SecurityManager; import org.apache.shiro.session.Session; import org.apache.shiro.subject.Subject; import org.apache.shiro.lang.util.Factory; import org.slf4j.Logger; import org.slf4j.LoggerFactory;

/**

  • Simple Quickstart application showing how to use Shiro’s API. *
  • @since 0.9 RC2 */ public class Quickstart {

    private static final transient Logger log = LoggerFactory.getLogger(Quickstart.class);

  1. public static void main(String[] args) {
  2. // The easiest way to create a Shiro SecurityManager with configured
  3. // realms, users, roles and permissions is to use the simple INI config.
  4. // We'll do that by using a factory that can ingest a .ini file and
  5. // return a SecurityManager instance:
  6. // Use the shiro.ini file at the root of the classpath
  7. // (file: and url: prefixes load from files and urls respectively):
  8. Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
  9. SecurityManager securityManager = factory.getInstance();
  10. // for this simple example quickstart, make the SecurityManager
  11. // accessible as a JVM singleton. Most applications wouldn't do this
  12. // and instead rely on their container configuration or web.xml for
  13. // webapps. That is outside the scope of this simple quickstart, so
  14. // we'll just do the bare minimum so you can continue to get a feel
  15. // for things.
  16. SecurityUtils.setSecurityManager(securityManager);
  17. // Now that a simple Shiro environment is set up, let's see what you can do:
  18. // get the currently executing user:
  19. Subject currentUser = SecurityUtils.getSubject();
  20. // Do some stuff with a Session (no need for a web or EJB container!!!)
  21. Session session = currentUser.getSession();
  22. session.setAttribute("someKey", "aValue");
  23. String value = (String) session.getAttribute("someKey");
  24. if (value.equals("aValue")) {
  25. log.info("Retrieved the correct value! [" + value + "]");
  26. }
  27. // let's login the current user so we can check against roles and permissions:
  28. if (!currentUser.isAuthenticated()) {
  29. UsernamePasswordToken token = new UsernamePasswordToken("lonestarr", "vespa");
  30. token.setRememberMe(true);
  31. try {
  32. currentUser.login(token);
  33. } catch (UnknownAccountException uae) {
  34. log.info("There is no user with username of " + token.getPrincipal());
  35. } catch (IncorrectCredentialsException ice) {
  36. log.info("Password for account " + token.getPrincipal() + " was incorrect!");
  37. } catch (LockedAccountException lae) {
  38. log.info("The account for username " + token.getPrincipal() + " is locked. " +
  39. "Please contact your administrator to unlock it.");
  40. }
  41. // ... catch more exceptions here (maybe custom ones specific to your application?
  42. catch (AuthenticationException ae) {
  43. //unexpected condition? error?
  44. }
  45. }
  46. //say who they are:
  47. //print their identifying principal (in this case, a username):
  48. log.info("User [" + currentUser.getPrincipal() + "] logged in successfully.");
  49. //test a role:
  50. if (currentUser.hasRole("schwartz")) {
  51. log.info("May the Schwartz be with you!");
  52. } else {
  53. log.info("Hello, mere mortal.");
  54. }
  55. //test a typed permission (not instance-level)
  56. if (currentUser.isPermitted("lightsaber:wield")) {
  57. log.info("You may use a lightsaber ring. Use it wisely.");
  58. } else {
  59. log.info("Sorry, lightsaber rings are for schwartz masters only.");
  60. }
  61. //a (very powerful) Instance Level permission:
  62. if (currentUser.isPermitted("winnebago:drive:eagle5")) {
  63. log.info("You are permitted to 'drive' the winnebago with license plate (id) 'eagle5'. " +
  64. "Here are the keys - have fun!");
  65. } else {
  66. log.info("Sorry, you aren't allowed to drive the 'eagle5' winnebago!");
  67. }
  68. //all done - log out!
  69. currentUser.logout();
  70. System.exit(0);
  71. }

} ```