Shiro security framework explanation and application

Table of contents

1. Permission management

1.1. What is permission management?

1.2. What is identity authentication?

1.3. What is authorization?

2. What is shiro?

2.1. Reasons for using shiro

3. Shiro’s core components

 3.1、Subject

3.2、SecurityManager

3.3. Authenticator (authenticator)

3.4. Authorizer

3.5. Realm (database reading + authentication function + authorization function implementation)

3.6、SessionManager

3.7、SessionDAO

3.8、CacheManager

3.9、Cryptography

4. Use shiro to complete authentication and authorization

4.1. Use shiro to complete authentication

4.1.1. Create a normal maven project

4.1.2. Create an ini file

4.1.3. Write test code

4.1.4. Certification process flow chart

 4.2. Use shiro to complete authorization

4.2.1. Modify ini file

4.2.2. Modify test code

4.2.3. Authorization process flow chart

1. Permission management

1.1. What is permission management?

Basically, systems involving user participation must carry out permission management. Permission management belongs to the category of system security. Permission management realizes the control of user access to the system. According to security rules or security policies, it is controlled that users can access and only access what they have been authorized to do. resource.

Permission management includes two parts: user identity authentication and authorization, referred to as authentication and authorization. For resources that require access control, users must first undergo identity authentication. After passing the authentication, the user can access the resource only after passing the authentication.

1.2. What is identity authentication?

Identity authentication is the process of determining whether a user is a legitimate user. The most commonly used simple identity authentication method is for the system to determine whether the user's identity is correct by checking the user name and password entered by the user to see if they are consistent with the user's user name and password stored in the system. For systems that use fingerprints and other systems, you need to show your fingerprint; for card swiping systems such as hardware keys, you need to swipe your card.

1.3. What is authorization?

Authorization, that is, access control, controls who can access which resources. After identity authentication, the subject needs to be assigned permissions to access system resources. Some resources cannot be accessed without permissions.

It is relatively troublesome to complete authentication and authorization by yourself. You can use a third-party framework to help you complete the binding of authentication and permissions.

Use more third-party frameworks--- shiro and springsecurity security framework. Shiro is relatively simple to use. And it can be used alone or integrated with the spring framework.

2. What is shiro?

Apache Shiro is a powerful and easy-to-use Java security framework that provides authentication, authorization, encryption, session management and other functions. For any application, Shiro can provide comprehensive security management services. And compared to other security frameworks, spring security, Shiro is much simpler.

2.1. Reasons for using shiro

Shiro makes it very easy to develop good enough applications, which can be used not only in the JavaSE environment, but also in the JavaEE environment. Shiro can help us complete: authentication, authorization, encryption, session management, integration with the Web, caching, etc.

3. Shiro’s core components

 3.1、Subject

Subject, external applications interact with the subject, and the subject uses the user as the subject of the current operation. This subject can be a user requesting through a browser, or it may be a running program. Subject is an interface in Shiro. The interface defines many methods related to authentication and authorization. External programs perform authentication and authorization through the subject, and the subject performs authentication and authorization through the SecurityManager security manager.

3.2、SecurityManager

SecurityManager permission manager, which is the core of Shiro, is responsible for the security management of all subjects. Subject authentication, authorization, etc. can be completed through SecurityManager . SecurityManager performs authentication through Authenticator, authorization through Authorizer , and session management through SessionManager. SecurityManager is an interface that inherits the three interfaces Authenticator, Authorizer, and SessionManager.

3.3. Authenticator (authenticator)

Authenticator is the authenticator, which authenticates the user's identity when logging in.

3.4. Authorizer

Authorizer, the user is authenticated through the authenticator. When accessing the function, the authorizer needs to be used to determine whether the user has the operation permission for this function.

3.5. Realm (database reading + authentication function + authorization function implementation)

Realm field is equivalent to datasource data source. SecurityManager needs to obtain user permission data through Realm for security authentication.
For example:
    If the user identity data is in the database, then realm needs to obtain the user identity information from the database.
Note:
    Do not understand realm as just fetching data from the data source. There is also code related to authentication and authorization verification in realm.

3.6、SessionManager

SessionManager session management, the shiro framework defines a set of session management, which does not rely on the session of the web container, so shiro can be used in non-web applications, and can also centrally manage the sessions of distributed applications. This feature can make it possible sign in.

3.7、SessionDAO

SessionDAO is a session dao, which is a set of interfaces for session operations
. For example,
    the session can be stored in the database through jdbc.
    The session can also be stored in the cache server redis.

3.8、CacheManager

CacheManager cache management stores user permission data in the cache, which can improve performance.

3.9、Cryptography

Cryptography password management, shiro provides a set of encryption/decryption components to facilitate development. For example, it provides commonly used hashing, md5 and other functions.

4. Use shiro to complete authentication and authorization

4.1. Use shiro to complete authentication

The user information used here exists in the --ini file [actual development storage database].

4.1.1. Create a normal maven project

Introduce shiro dependencies:

    <dependencies>
        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-core</artifactId>
            <version>1.7.0</version>
        </dependency>
    </dependencies>

4.1.2. Create an ini file

# [users] Define user information--when the table name is users
[users]
# =The left side indicates the user name =The right side indicates the password
zhangsan=123456
lisi=123456

4.1.3. Write test code

package demo01;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.realm.text.IniRealm;
import org.apache.shiro.subject.Subject;

/**
 * @program:shiro-framework
 * @description:
 * @author: 
 * @create: 2023-07-05 11:03
 **/
public class Test {
    public static void main(String[] args) {
        //创建一个SecurityManager对象
        DefaultSecurityManager securityManager=new DefaultSecurityManager();
        //设置securityManager使用的realm
        IniRealm realm=new IniRealm("classpath:shiro.ini");
        securityManager.setRealm(realm);
        //把SecurityManager放入上下文中。使其有效
        SecurityUtils.setSecurityManager(securityManager);
        //获取Subject对象
        Subject subject = SecurityUtils.getSubject();
        //shiro把用户输入的账号和密码封装到UsernamePasswordToken类中。
        UsernamePasswordToken token=new UsernamePasswordToken("zhangsan","1234567");
        try {
            //调用subject中的认证方法。
            subject.login(token);
            System.out.println("登录成功");
        }catch (Exception e){
            e.printStackTrace();
            System.out.println("登录失败");
        }

    }
}

4.1.4. Certification process flow chart

 4.2. Use shiro to complete authorization

Note: Permissions can only be judged after authentication.

4.2.1. Modify ini file

# [users]定义用户的信息--当对于表名叫users
[users]
# =左边表示用户名  =右边表示密码和对应的角色
zhangsan=123456,admin
lisi=123456,role1,role2
#[roles]定义角色信息以及该角色具有的权限信息。
[roles]
#=左边:角色名  右边: 该角色具有的权限
admin=user:query,user:insert,user:delete,user:update
role1=user:query,user:export
role2=user:delete,user:update

4.2.2. Modify test code

package demo01;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.realm.text.IniRealm;
import org.apache.shiro.subject.Subject;

import java.util.Arrays;

/**
 * @program:shiro-framework
 * @description:
 * @author:
 * @create: 2023-07-05 11:03
 **/
public class Test02 {
    public static void main(String[] args) {
        //1.获取SecurityManager对象
        DefaultSecurityManager securityManager=new DefaultSecurityManager();
        //2.为SecurityManager指定操作数据源的对象realm
        IniRealm realm=new IniRealm("classpath:shiro.ini");
        securityManager.setRealm(realm);

        //3.把securityManager放入上下文 使其生效
        SecurityUtils.setSecurityManager(securityManager);



        //4.获取Subject
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token=new UsernamePasswordToken("lisi","123456");
        try {
            subject.login(token);
        }catch (Exception e){
            e.printStackTrace();
            System.out.println("登录失败");
        }
        //subject.logout();//退出

        System.out.println("==============================权限校验=======================================");
        boolean permitted = subject.isPermitted("user:query");
        System.out.println("判断当前用户是否具有user:query的权限:"+permitted);
        boolean[] permitted1 = subject.isPermitted("user:query", "user:delete", "user:export");
        System.out.println("判断当前用户具有的权限:"+ Arrays.toString(permitted1));
        boolean permittedAll = subject.isPermittedAll("user:query", "user:update", "user:insert");
        System.out.println("是否同时具有上面的权限:"+permittedAll);

    }
}

4.2.3. Authorization process flow chart

Guess you like

Origin blog.csdn.net/weixin_54065960/article/details/131609651