编程知识 cdmana.com

Quick start to Shiro security framework

Catalog

1、 About Shiro

website

Shiro characteristic

Shiro Basic function point

Shiro framework

2、 Quick start

2.1、Shiro Authentication


1、 About Shiro

website

Apache Shiro is a powerful and easy-to-use Java security framework that performs authentication, authorization, cryptography, and session management. With Shiro’s easy-to-understand API, you can quickly and easily secure any application – from the smallest mobile applications to the largest web and enterprise applications.
Apache Shiro Is a powerful and easy to use Java Security framework , Can be used for authentication 、 to grant authorization 、 Encryption and session management .Shiro It's easy to understand API, You can quickly 、 Easy access to any application —— From the smallest mobile applications to the largest network and enterprise applications .

In short ,Apache Shiro Is a powerful and flexible open source security framework , Authentication can be fully handled 、 to grant authorization 、 Encryption and session management .

Shiro characteristic

  • Easy to use —— Ease of use is the ultimate goal of the project . Application security is very confusing and frustrating , Is considered to be “ The inevitable ”. If you make it so simple that a novice can use it , It will no longer be a pain .
  • comprehensive —— No other security framework has the same width range Apache Shiro equally , It can be yours “ "One-stop" work style ” Provide security for your security needs .
  • flexible ——Apache Shiro It can work in any application environment . Although working in the network 、EJB and IoC It may not be needed in the environment . but Shiro There is no specification for authorization , There aren't even many dependencies .
  • Web Support ——Apache Shiro Have exciting web Application support , Allows you to be application-based url Create flexible security policies and network protocols ( for example REST), There is also a set JSP The library controls the page output .
  • Low coupling ——Shiro clean API And design patterns make it easy to integrate with many other frameworks and applications . You'll see Shiro Seamlessly integrate Spring Such a framework , as well as Grails, Wicket, Tapestry, Mule, Apache Camel, Vaadin... etc. .
  • Be widely supported ——Apache Shiro yes Apache Part of the software foundation . Project development and user groups have friendly netizens willing to help . Such commercial companies if needed Katasoft It also provides professional support and services .

Shiro Basic function point

  • Authentication: Identity Authentication / Sign in , Verify that the user has an identity ;
  • Authorization: to grant authorization , That is, permission verification , Verify that an authenticated user has certain privileges ; That is to determine whether the user can do something , The common ones are : Verify that a user has a role . Or fine-grained verification of whether a user has a right to a resource ;
  • Session Management: session management , That is, once the user logs in, it is a session , Before I quit , All of its information is in the conversation ; Conversations can be normal JavaSE Environmental , It could also be like Web Environmental ;
  • Cryptography: encryption , Protect data security , Such as password encryption stored in the database , Instead of plaintext storage ;
  • Web Support:Web Support , Can be easily integrated into Web Environmental Science ;
  • Caching: cache , Like when the user logs in , Its user information 、 Owned role / Permissions don't have to be checked every time , This can improve efficiency ;
  • Concurrency:shiro Support concurrent validation for multi-threaded applications , That is, start another thread in one thread , Can automatically propagate permissions to ;
  • Testing: Provide test support ;
  • Run As: Allows one user to pretend to be another ( If they allow it ) The identity of the access ;
  • Remember Me: Remember me , This is a very common feature , After one login , You don't have to log in the next time you come .

    Remember a little ,Shiro They don't maintain users 、 Maintenance access ; We need to design them ourselves / Provide ; It is then injected through the corresponding interface Shiro that will do .

Shiro framework

In the concept ,Shiro Architecture consists of three main ideas :Subject,SecurityManager and Realm. The following diagram shows how these components interact , We will describe them in turn below .

  • Subject: The current user ,Subject It could be a person , But it can also be a third-party service 、 Daemon account 、 Clock guard tasks and so on – Any event currently interacting with the software .
  • SecurityManager: Manage all Subject,SecurityManager yes Shiro The heart of the architecture , Cooperate with internal safety components to form a safety umbrella .
  • Realms: Used for authentication of permission information , We do it ourselves .Realm It's essentially a specific security DAO: It encapsulates the details of connecting to the data source , obtain Shiro Relevant data required . In the configuration Shiro When , You must specify at least one Realm To implement authentication (authentication) and / Or authorized (authorization).

We need to achieve Realms Of Authentication and Authorization. among Authentication Is used to authenticate the user ,Authorization Authorization access control , Used to authorize actions performed by a user , Proves whether the user is allowed to perform the current operation , Such as accessing a link , A resource file, etc .

2、 Quick start

2.1、Shiro Authentication

                    shiro Certification flow chart

Sample code :

1、 establish maven engineering , Introduce dependency

<dependency>
   <groupId>org.apache.shiro</groupId>
   <artifactId>shiro-core</artifactId>
   <version>1.4.0</version>
</dependency>
<dependency>
   <groupId>junit</groupId>
   <artifactId>junit</artifactId>
   <version>4.12</version>
</dependency>

2、 Create test class

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.realm.SimpleAccountRealm;
import org.apache.shiro.subject.Subject;
import org.junit.Before;
import org.junit.Test;

public class AuthenticationTest {

    SimpleAccountRealm simpleAccountRealm = new SimpleAccountRealm();

    //  Add a user before the method starts 
    @Before
    public void addUser() {
        simpleAccountRealm.addAccount("admin", "111111");
    }

    @Test
    public void testAuthentication() {
        // 1. structure SecurityManager Environmental Science 
        DefaultSecurityManager defaultSecurityManager = new DefaultSecurityManager();
        defaultSecurityManager.setRealm(simpleAccountRealm);

        // 2. Subject submits authentication request 
        SecurityUtils.setSecurityManager(defaultSecurityManager); //  Set up SecurityManager Environmental Science 
        Subject subject = SecurityUtils.getSubject(); //  Get the current body 

        UsernamePasswordToken token = new UsernamePasswordToken("admin", "111111");
        subject.login(token); //  Sign in 

        // subject.isAuthenticated() Method returns a boolean value , To determine whether the user has successfully authenticated 
        System.out.println("isAuthenticated:" + subject.isAuthenticated()); //  Output true

        subject.logout(); //  Log out 

        System.out.println("isAuthenticated:" + subject.isAuthenticated()); //  Output false
    }
}

3、 Run and view the results

      After running, you can see isAuthenticated Print first true, Indicates that the authentication is successful ; The second print is false, Because the user has logged out , Authentication failed .

The specific authentication process :

The process is as follows :

  1. First call  Subject.login(token)  Log in , It will automatically delegate to  Security Manager, Must pass before calling  SecurityUtils.setSecurityManager()  Set up ;
  2. SecurityManager  Responsible for the real authentication logic ; It's going to delegate to  Authenticator  Authentication ;
  3. Authenticator  Is the real authenticator ,Shiro API  In the core of the identity authentication entry point , Here you can customize to insert your own implementation ;
  4. Authenticator  You might delegate to the corresponding  AuthenticationStrategy  Do more  Realm  Authentication , Default  ModularRealmAuthenticator  Would call  AuthenticationStrategy  Do more  Realm  Authentication ;
  5. Authenticator  I'm going to put the corresponding  token  Pass in  Realm, from  Realm  Gets the authentication information , If there is no return / Throwing an exception indicates that the authentication failed . More than one can be configured here  Realm, Access will be conducted in the appropriate order and policy .

版权声明
本文为[osc_ d7or6cwg]所创,转载请带上原文链接,感谢
https://cdmana.com/2020/12/20201224104413012b.html

Scroll to Top