Shiro framework detailed tagline

Shiro framework detailed tagline

I have used the shiro permission control framework in my work. I have always stayed in the aspect of use before. I don t have too much knowledge in this area. Now I have time to study the use of this Shiro permission framework. .

What is Shiro?

Apache Shiro is a powerful and flexible open source security framework that cleanly handles identity authentication, authorization, enterprise session management and encryption.

The primary goal of Apache Shiro is to be easy to use and understand. Security is sometimes very complicated and even painful, but it is not necessary.

The framework should cover up as much complexity as possible and expose a clean and intuitive API to simplify the efforts of developers to make their applications safe.

Because many people prefer to use Spring Security and Shiro provided by Spring for comparison, we also compare this content.

Apache Shiro is a security framework for Java.

At present, more and more people use Apache Shiro, because it is quite simple. Compared with Spring Security, it may not be as powerful as Spring Security, but it may not need such complicated things in actual work, so use small and simple Shiro is enough.

Therefore, many times in our work, we directly use Shiro for security control.

After we have finished the introduction, what is the use of Shiro? 1. Authenticate users to verify their identity 2. Perform access control on users

For example, we can use it to determine whether a user is assigned a security role. Then determine what authority this person can handle in the project. This means that if there are two people, one is the administrator, he has the function of adding, deleting, modifying, and checking, and the other user is only checking again, without adding The function of deletion and modification can be controlled by Shiro to achieve this effect.

We can take a look at Shiro on the Apache official website and what features it contains.

Let's take a look at what each module represents?

Authentication: Authentication, sometimes abbreviated as "login", is the act of proving that the user is who they say they are.

Authorization: The process of authorization and access control, that is, the absolute "who" accesses "what". Authorization is used to answer security questions, such as "whether the user is allowed to edit the account", "whether the user is allowed to view this page", and "whether the user Can access" to this button? "These are all decisions that determine the user's right to access, so they all represent authorization checks.

Cryptography: Cryptography is the practice of protecting information from bad access by hiding it or turning it into meaningless, so that no one else can read it. Shiro focuses on two core elements of cryptography: passwords that use public or private keys to encrypt data, and hashes that irreversibly encrypt data such as passwords (also known as message digests).

The main goal of Shiro Cryptography is to take a traditionally very complex field and make it easy for others to implement while providing strong cryptographic functions.

Session Management: Session session. A session is a data bucket that your users carry for a period of time when using your application. Traditionally, sessions are dedicated to Web or EJB environments. no longer! Shiro supports sessions in any application environment. In addition, Shiro also provides many other powerful features to help you manage your sessions.

Web Support: Shiro's web-supported API can easily help protect web applications. It is mainly used for a good support for Web programs.

Caching: Caching, he is the first-tier citizen in Apache Shiro to ensure fast and efficient security operations.

Concurrency: Shiro uses its concurrency features to support multi-threaded applications.

Testing: Testing support exists to help you write unit tests and integration tests, and to ensure that yours is as safe as expected.

"Run As": In fact, this is a function that allows a user to assume the identity of another user, which is sometimes effective when managing scripts.

Remember Me: Remember the user's identity in the session, so they only need to log in when mandatory.

Shiro core

Shiro actually has three core components, Subject, SecurityManager and Realms.

Subject: Subject is essentially a specific security "view" of the currently executing user. In view of the fact that the term "User" usually means a person, and a Subject can be a person, but it can also represent a third-party service, daemon account, cron job, or any other similar things-basically it is currently working with software Anything that interacts.

All Subject instances are bound to (and this is required) a SecurityManager. When you interact with a Subject, those interactions translate into interactions with the specific subject interacting with the SecurityManager. We can think of Subject as a facade, and SecurityManager is the real executor.

SecurityManager: Security manager, which means that all security-related operations will interact with the SecurityManager, and it manages the Subject. It is actually the core of Shiro and the heart of the Shiro architecture. And as a kind of "protective umbrella" object to coordinate the internal security components to form an object graph.

Realms: Realm, Shiro obtains security data (such as users, roles, permissions) from Realm, that is, if SecurityManager wants to verify user identity, then it needs to obtain corresponding users from Realm to compare to determine whether the user identity is legal; it also needs to get from Realm Get the user's corresponding role/permission to verify whether the user can perform the operation; Realm can be regarded as a DataSource, that is, a secure data source.

When configuring Shiro, you must specify at least one Realm for authentication and/or authorization. SecurityManager may configure multiple Realms, but at least one is required.

We can see shiro's control of permissions through a simple login.

Let's understand it through diagrams, and then write a simple code

The above picture is the design of shiro role permissions,

And then we can look at its specific login diagram

Let me explain this picture.

1. The login operation carries the user name and password to the subject, and the subject calls its own login method to pass the user name and password to the authority manager. The authority manager passes the username and password to the realm authentication method written by the developer, and the realm sends it to the database according to the username To find out if the user exists, and if so, store the authentication information in the session

 /* *  1  *  2  *  3 |  */SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, user.getPassword(), this.getClass().getName());  

2. The authority manager will automatically determine whether the passed password is consistent with the correct password

3. Access to 3 types of resources (pages). The filter looks for the authority manager to determine whether the user has xxx authority. The authority manager takes out the authentication information object from the session and returns it to realm. Realm judges what authority the user has and encapsulates the authorization information Return to the authority manager, and the authority manager will return the result of the judgment to the filter

4. Access to 3 types of resources (addition of xxx requires access to service) (for filters belongs to 2 types of resources), when the method is executed, the pre-notification will be reached (the annotation @RequiresPermissions("courier:list") is added to the esrvice method ), the permission notification looks for the permission manager to judge whether the user has xxx permission, the permission manager takes out the authentication information object from the session and returns it to realm, and realm judges what permission the user has, encapsulates it in the authorization information and returns it to the permission manager. The permission manager returns the result of the judgment to the permission notification

In fact, in simple terms/userAction_login ---------->The request first arrives at the permission filter shiroFilter, first determine the type of resource

Login belongs to a type of resource and is directly released to ------>userActon (the subject object is called in userAction (the entry is an operation entry object, which has a login method, a logout method, and access to the current object method) Login method subject.login method (carrying username and password)

> The subject object calls the login method of the securityManager. The permission manager cannot determine that the user and password are correct.

>ream authentication|authorizer (written by the developer to determine whether the user name exists and what permissions it has) >After processing, the authentication information object is returned to the securityManager () If there is no problem with the authentication information, permission management The device will store the authentication information in the session (prove that the authentication has been logged in)

You can customize a Realm;

 @Service("MyRealm")public class MyRealm extends AuthorizingRealm{//Realm     @Autowired    private UserDao ud;     @Autowired    private RoleService rs;     @Autowired    private PermissionService ps;     @Override   //    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {        User user = (User) principals.getPrimaryPrincipal();        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();        List<Role> roles = rs.findByUser(user);        if(roles != null && roles.size() > 0){            for (Role role : roles) {                info.addRole(role.getKeyword());            }        }        List<Permission> permissions = ps.findByUser(user);        if(permissions != null && permissions.size() > 0) {            for (Permission permission : permissions) {                info.addStringPermission(permission.getKeyword());            }        }        return info;    }     @Override   //    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken t) throws AuthenticationException {        UsernamePasswordToken token = (UsernamePasswordToken) t;        String username = token.getUsername();        User user = ud.findByUsername(username);        if(user != null){           /*             *  1              *  2              *  3 |              */           SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, user.getPassword(), this.getClass().getName());           //ActionContext.getContext().getSession().put("loginUser", user);            return info;        } else {            return null;        }     } }  

After logging in, access page resources (page resources belong to three types of resources and require permissions),

shiroFilter (which resources have been configured as one type and which resources are three types)

>Access the authority manager, find the authority manager to determine whether there is xxx authority (the authority manager itself cannot make a judgment), and the authority manager takes out the authentication information saved in the session when logging in before

Give it to >realm judgment (the authentication method in realm is called when logging in), realm queries the database to obtain permissions, and returns the permission information to >Permission Manager

The authority manager judges whether it has the xxx authority according to the authorization information of realm, and then notifies the result to > authority manager. If the authority manager ShiraFilter does not have the authority, it will jump to the response page.

This is actually a simple shiro framework design. It may be a little flawed in my personal design. It's just a test, and everyone can experience it by yourself.


Shiro is a very full-featured framework, and it is easy to use. Summarize the three core contents:


Shiro is powerful, simple and flexible. The projects under Apache are more reliable, and are not tied to any framework or container, and can run independently

So, do you understand this permission control framework? Let's exchange ideas if we have ideas.

The Java Geek Technology Official Account was established by a group of technical people who love Java development, focusing on sharing original, high-quality Java articles. If you think our article is not bad, please help to appreciate, watch, forward and support, and encourage us to share better articles.

Pay attention to the official account, you can reply "Nuggets" in the background of the official account to obtain the author's Java knowledge system/interview must-see materials.