Apache Shiro Authority Framework Theory Introduction

Source: Internet
Author: User

Apache Shiro Rights Management Framework Introduction

Apache Shiro's website address is as follows:

http://shiro.apache.org/

Apache Shiro is an easy-to-use, powerful and flexible open source Java Security Framework, hereinafter referred to as Shiro. It cleanly handles identity authentication, authorization, and enterprise session management and encryption. Shiro has an easy-to-understand API that you can use quickly and easily to protect any application-from the smallest mobile app to the largest Web and enterprise application.

Shiro Permissions Basic Concepts:

    • Security entities: Objects that are protected by the rights system, such as payroll data.
    • Permissions: Is the behavior that needs to be verified, such as viewing, modifying, and so on.
    • Assign permissions: Assign certain permissions to certain security entities to some people. is the process of adding data to or maintaining data in a database
    • Permission validation (permission matching): Determines whether a person or program has some or some permissions on a security entity. The process of getting the corresponding data from the database for matching.
    • Inheritance of permissions: If more than one security entity has a containment relationship and a security entity does not have permission restrictions, it inherits the appropriate permissions for the security entity that contains it.
    • The closest matching principle for permissions: If multiple security entities have a containment relationship and a security entity does not have permission restrictions, it will look up and match the appropriate permission limit until it finds a security entity that has the appropriate permission limit closest to the security entity. If the entire hierarchy is looked for and there is no match to the appropriate permission limits, it means that everyone has this corresponding permission limit for this security entity.

What Shiro can do:

    • Authentication: Verifying the identity of a user
    • Authorization: To perform access control on a user: To determine whether a user is allowed to do something
    • Management: Use the Session API in any environment, even without a Web or EJB container.
    • Encryption: Use encryption to protect or hide data in a more concise and easy-to-access way to prevent prying
    • Realms: A data source that aggregates one or more user-safe data
    • Single Sign-On (SSO) feature: Enable the Remember Me service for users who are not associated to a login
Shiro's main functional architecture diagram:

You can see the four core parts of Shiro:

    • Authentication (authentication): simply "sign in", which proves who the user is.
    • Authorization: The process of access control, which is to decide whether you have permission to access protected resources.
    • Session Management: Manages user-specific sessions, even in non-WEB or EJB applications.
    • Cryptography (Encryption): Keeping data secure by using cryptographic algorithms

Shiro also provides the following extensions:

    • Web support: Provides some common features for Web applications.
    • Caching: Caching can make an application run more efficiently.
    • Concurrency: Multithreading-related features.
    • Testing: Help us with testing-related functions
    • "Run as": A feature that allows a user to assume that another user's identity (if allowed) is sometimes useful in managing scripts.
    • "Remember Me": Remember the user identity, provide similar shopping cart function.
Shiro 3 Core component diagrams for the conceptual layer architecture:

    • Subject: A person who is interacting with the system, or a third-party service. All Subject instances are bound to (and this is required) on a securitymanager.
    • The heart of the Securitymanager:shiro architecture is used to coordinate internal security components, manage internal component instances, and through it to provide various services for security management. When Shiro interacts with a Subject, it is essentially the behind-the-scenes securitymanager that handles all the heavy Subject security operations and can compare their concepts to the front-end controllers in Springmvc.
    • Realms: Essentially a security-specific DAO. When configuring Shiro, you must specify at least one Realm to be used for authentication or authorization. Shiro provides a variety of available Realms to obtain security-related data. such as relational databases (JDBC), INI, and properties files. You can define your own Realm implementation to represent your custom data source.
Shiro Frame Composition:

    • Authenticator: The component that performs the authentication (logon) of the user. Authenticator obtains data from one or more realms to verify the identity of the user. If there is more than one realm, then the interface authenticationstrategy will determine what kind of authentication is successful (for example, if one realm succeeds and the others fail, the login succeeds).
    • Authorizer: The rights manager, which is used primarily for user access control, to verify that users can access protected resources in the app.
    • Sessionmanager:session Manager to consistently use the Session API at any application or architecture level
    • Sessiondao:sessionmanager performs a Session persistence (CRUD) operation.
    • CacheManager: Provides caching support for Shiro components.
    • Cryptography:shiro's API drastically simplifies password encryption in Java APIs
    • Realms:shiro through Realms to obtain the appropriate security data
Shiro Configuration Basics

Shiro is designed to work in any environment, from simple command-line applications to enterprise cluster applications. Due to the diversity of the environment, Shiro can use a variety of configuration mechanisms.

Users

    • INI configuration: INI is actually a text configuration that contains key/value pairs that are organized by uniquely named items.
    • The [Users] section allows you to define a static set of user accounts
    • Format of each line:username = password, roleName1, roleName2, …

Roles

    • [Roles] section allows you to associate roles and permissions defined in the [Users] section
    • Format of each line:rolename = permissionDefinition1, permissionDefinition2, …
      • Permissiondefinition is an arbitrary string, but most people will use a string that conforms to the org.apache.shiro.authz.permission.WildcardPermission format.

Attention:

    • If a separate permissiondefinition needs to be separated by an internal comma (for example, Printer:5thfloor:print,info), the user is required to surround the definition with double quotes to avoid error parsing.
    • If the role does not want to associate permissions, you do not need to list them in the [Roles] section. Defining a role name in the [user] section is sufficient to create a role that does not yet exist.
    • Defining only non-empty [users] or [roles] parts will automatically trigger the creation of Org.apache.shiro.realm.text.IniRealm instances
Shiro Identity Authentication: Authentication

Authentication: Authentication--By submitting the user's identity and credentials to Shiro to determine if they match the application's expectations.

Basic concepts:

    • Principals (Identity): Subject identifying attributes (Identity attribute). For example, we login to submit the user name.
    • Credentials (voucher): Used as a supporting evidence, this evidence contains xxx Ming. For example, we login to provide the password

Basic Steps for Certification:

    • Collection of principals (identity) and credentials (vouchers) submitted by subjects;
    • Submit Principals (identity) and credentials (credentials) for authentication;
    • If the commit succeeds, access is allowed, or re-authenticated or blocked.
    • The Authenticationtoken:shiro represents the most basic interface of the authentication system for submitted principals (identity) and Credentials (credentials).
    • Usernamepasswordtoken:authenticationtoken implementation class for the interface that supports the most common user name/password Authentication

Submit user name/password for authentication:

Subject currentUser = SecurityUtils.getSubject();currentUser.login(token);

Handling authentication successes and failures

    • Authentication succeeded: No return, no exception, passed.
    • Authentication failed, thrown out of the exception, can be captured and processed in the program

Authentication order:

Certification process:

Step 1: application code calls the Subject.login method to pass the created Authenticationtoken instance that contains the end user's principals (identity) and Credentials (credentials)

Step 2: Subject instances, typically delegatingsubject (or subclasses), delegate the application's SecurityManager to begin real validation by calling Securitymanager.login (token).

Step 3: Subjectmanager receives token, calling the internal Authenticator instance to call Authenticator.authenticate (token). Authenticator is typically a modularrealmauthenticator instance that supports reconciling one or more realm instances in authentication.

Step 4: If more than one Realm,modularrealmauthenticator instance is configured in the application, the configured authenticationstrategy will be used to initiate the Multi-realm authentication attempt. Before realms was authenticated, during and after the call, Authenticationstrategy was called to enable it to react to the results of each realm.

Step 5: each configured Realm is used to help see if it supports the submission of Authenticationtoken. If supported, then the Getauthenticationinfo method that supports Realm will be invoked with the token being submitted. The Getauthenticationinfo method effectively represents a single authentication attempt for a particular Realm.

Shiro Authorization

Authorization: also known as access control-controls who has permission to do what in the application. In authorization, there are several key objects that need to be understood: Subject principals, Resource resources, Permissions permissions, role roles:

    • Subject Principal: The user who accesses the app, uses Subject in Shiro to represent the user, and the user needs authorization to access the appropriate resource
    • Resource Resources: Anything that the user accesses in the app, such as: JSP, interface, picture, etc., are resources
    • Permissions permissions: The core element of the Shiro security mechanism. It explicitly declares the allowed behavior in the application. A well-formed permission declaration can clearly express the user's permissions on the resource. The description of permissions is accomplished primarily through wildcard expressions in Shiro
    • Role roles: A named entity that typically represents a set of behaviors or responsibilities. These behaviors evolve into things that can or cannot be done in an application. Roles are typically assigned to user accounts. A role has a collection of permissions. When authorizing authentication, you need to determine whether the current role has the specified permissions. This role permission can have a detailed permission description for the role. Shiro the official recommendation to use this method

Examples of authorization checks: whether users can access a webpage, edit data, or use this printer

three elements of authorization: permissions, Roles, and users.

You need to associate users and permissions in your application: It is common practice to assign permissions to roles and then assign roles to one or more users.

Shiro three ways to authorize:

    • Write code: Perform authorization checks in Java code with structures like if and else blocks.
    • JDK Annotations: You can add authorization annotations to Java methods
    • JSP Tag Library: You can control the JSP page output based on roles and permissions.

Shiro Authorization sequence Diagram:

Timing Diagram:

    • Step 1: the application or framework code calls any Subject,, hasRole* checkRole* isPermitted* , or checkPermission* variant of the method, passing any required permissions
    • Step 2: An instance of Subject-usually a delegatingsubject (or subclass) that calls the corresponding method of SecurityManager.
    • Step 3: SecurityManager org.apache.shiro.authz.Authorizer The corresponding method of the calling interface. By default, the Authorizer instance is an Modularrealmauthorizer instance that supports reconciling one or more realm instances during any authorization operation.
    • Step 4: Each configured Realm is checked for the implementation of the same Authorizer interface. If it is, Realm's individual,, hasRole* checkRole* isPermitted* , or checkPermission* method will be called.
Shiro Basic Syntax: How permissions is declared

Simple string of basic syntax:

    • That is, a simple string to represent a permission, such as: user (equivalent to: user:* )

Multi-level management of the underlying syntax:

    • For example: user:query、user:edit
    • Multiple values: Each part can protect multiple values. Therefore, in addition to granting users user:query and user:edit permissions, you can simply grant them one:user:query, edit
    • You can also use a * number instead of all values, such as: user:* , or write: *:query , a user has query permissions in all fields

Instance-level access control for the underlying syntax:

    • This typically uses three parts: a domain, an operation, and an instance that is implemented. Such as:user:edit:manager
    • You can also use wildcard characters to define, such as:user:edit:*、user:*:*、user:*:manager
    • Partially omitted wildcard: The missing part means that the user can access all matching values, such as: user:edit equivalent user:edit :* , user equivalent touser:*:*

Note: wildcards can only omit parts from the end of a string, meaning that User:edit is not equivalent to User:*:edit

Shiro logoff

Logout (Logout):currentUser.logout();

    • When the logout () method is called, the existing Session is invalidated and the identity is lost (in the Web application, the RememberMe cookie is deleted).
    • After Subject logoff, the instance of the Subject is again considered anonymous.

Note: WEB applications Remember that identities are often dependent on cookies, but cookies are only deleted after Response is returned, so it is recommended that you redirect a new view or page to the terminal immediately after calling Subject.logout (). This ensures that security-related cookies can be deleted as expected.

Realm
    • Realm: A component that accesses application security data, such as users, roles, and permissions.
    • Realm is usually a one-to-many correspondence with data sources, such as relational databases, file systems, or other similar resources. Realm is essentially a DAO that accesses security data.
    • Data sources typically store authentication data (such as credentials for passwords) and authorization data, such as roles or permissions, so each realm can perform authentication and authorization operations.
Realms Certification Implementation

The Shiro authentication process is performed by Realm, and org.apache.shiro.realm.Realm the getAuthenticationInfo(AuthenticationToken token) method that SecurityManager calls

The implementation class that is typically provided in the actual development, org.apache.shiro.realm.AuthenticatingRealm and provides a concrete implementation of the method in the implementation class doGetAuthenticationInfo(AuthenticationToken token)

    1. Check submitted for certification of XXX information
    2. Obtain user information from a data source (typically a database) based on the XXX information
    3. The user information is matched to verify.
    4. Validation will return a AuthenticationInfo instance that encapsulates the user information.
    5. Validation failure throws authenticationexception exception information.
Shiro permission interception

Shiro and spring security, are based on filters to achieve permission interception. Default filter in Shiro:

Filter Chain:

Filter class Diagram:

Shiro Session Management

Shiro provides complete enterprise-level session management capabilities, independent of underlying containers (such as Tomcat) that can be used in either J2SE or the Java EE Environment, providing session management, session event snooping, session storage/persistence, container-independent clustering, expiration/expiration support, transparent support for the web, SSO support features such as single sign-on.

It is recommended that in development, the controller layer uses the native HttpSession object to use the session object provided by Shiro in the service layer. If you use the HttpSession object in the service layer, it is intrusive and is not recommended. The session provided by Shiro is a good solution to this problem.

Session Management related classes diagram:

Shiro Permissions Cache

The cache is XXX can the important means, the same batch of data for multiple queries, the first query to go to the database, query data, save the data in memory, the second time after the query can be directly from memory to obtain data, so do not need to interact with the database. This reduces the number of times the system queries the database and improves performance.

Caching is appropriate for data that is not constantly changing, such as the information and permissions of users in the system do not change frequently, especially for caching for next use. Where our permissions information is not how to change, the permission information cache can improve the performance of our system. However, Shiro does not implement the cache itself, but instead provides a cache interface for other third-party implementations that support Ehcache and MapCache caches by default.

Shiro Cache-related class diagrams:

Apache Shiro Authority Framework Theory Introduction

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.