Shiro 核心概念

关于 Shiro,需要理解三个核心概念:Subject、SecurityManager 和 Realms。

Vue + Spring Boot 项目实战(十三):使用 Shiro 实现用户信息加密与登录认证

这里我特意去查了官方文档,因为感觉市面上很多解读不太靠谱。所谓戏说不是胡说,改编不是乱编,一千个读者心中只能有一个 Shiro,那就是我讲的 Shiro。

The word Subject is a security term that basically means “the currently executing user”. It’s just not called a ‘User’ because the word ‘User’ is usually associated with a human being. In the security world, the term ‘Subject’ can mean a human being, but also a 3rd party process, daemon account, or anything similar. It simply means ‘the thing that is currently interacting with the software’. For most intents and purposes though, you can think of this as Shiro’s ‘User’ concept.

Subject: “现在在与软件交互的东西”,这个东西可能是你是我,可能是第三方进程。说白了就是穿了马甲的用户类,负责存储与修改当前用户的信息和状态。

之后你会看到,使用 Shiro 实现我们所设计的各种功能,实际上就是在调用 Subject 的 API。


The Subject’s ‘behind the scenes’ counterpart is the SecurityManager. While the Subject represents security operations for the current user, the SecurityManager manages security operations for all users. It is the heart of Shiro’s architecture and acts as a sort of ‘umbrella’ object that references many internally nested security components that form an object graph. However, once the SecurityManager and its internal object graph is configured, it is usually left alone and application developers spend almost all of their time with the Subject API.

SecurityManager: Subject 背后的女人,安全相关的操作实际上是由她管理的。只用在项目中配置一次,就可以忘掉她了。


A Realm acts as the ‘bridge’ or ‘connector’ between Shiro and your application’s security data. That is, when it comes time to actually interact with security-related data like user accounts to perform authentication (login) and authorization (access control), Shiro looks up many of these things from one or more Realms configured for an application.

Realm: 是 Shiro 和安全相关数据(比如用户信息)的桥梁,也就是说,Realm 负责从数据源中获取数据并加工后传给 SecurityManager。

我们可以通过配置使用特定的 Realm 替代 DAO,和 JPA 类似,Realm 获取数据的方法被封装了起来,但是数据库中的表名、字段等需要与源码预定义的查询保持一致,所以在我们的项目中获取数据的功能仍旧可以交给 JPA 完成,Realm 只负责加工并传递这些数据。


除了上述三种概念,还有四大功能——Authentication(认证)、Authorization(授权)、Session Management(会话管理)、Cryptography(加密),各种安全框架解决的都是这几类问题,看名字就大概知道是什么意思了。