Get through the use of native Shiro in one article

Table of contents

Environmental preparation

add dependencies

INI file

 login authentication

Login Authentication Concept

Basic flow of login authentication

 Login authentication instance

Authentication process

role, authorization

authorization concept

Authorization method

Authorization process 

Authorized instance

Shiro encryption

Shiro custom login authentication 


Environmental preparation

Shiro does not depend on the container, just create a maven project directly

add dependencies

<dependencies>
    <dependency>
        <groupId>org.apache.shiro</groupId>
        <artifactId>shiro-core</artifactId>
        <version>1.9.0</version>
    </dependency>
    <dependency>
        <groupId>commons-logging</groupId>
        <artifactId>commons-logging</artifactId>
        <version>1.2</version>
    </dependency>
</dependencies>

INI file

Information related to Shiro's access permissions can be obtained through the database or through the ini configuration file

1. Create ini file

[users]
zhangsan=z3
lisi=14

 login authentication

Login Authentication Concept

  • (1) Identity verification: Generally, it is necessary to provide some identification information such as identity ID to indicate the identity of the login , such as providing email, user name/password to prove.
  • (2) In shiro, the user needs to provide principals (identity) and credentials (proof) to shiro, so that the application can verify the user's identity
  • (3) principals: identity, that is, the identification attribute of the subject, which can be any attribute, such as user name, email address, etc., as long as it is unique. A subject can have multiple principals, but only one Primary principals , usually username/email/mobile phone number.
  • (4) credentials: proof/credentials, that is, security values ​​that only the subject knows, such as passwords/digital certificates, etc.
  • (5) The most common combination of principals and credentials is username/password

Basic flow of login authentication

(1) Collect user identity/credentials, such as username/password
(2) Call Subject.login to log in. If it fails, it will get the corresponding AuthenticationException
, and prompt the user for error information according to the exception; otherwise, the login is successful
(3) Create a custom The Realm class inherits the org.apache.shiro.realm.AuthenticatingRealm class and
implements the doGetAuthenticationInfo() method

 Login authentication instance

public class ShiroRun {
    public static void main(String[] args) {
        //1.初始化获取securitymanager
        IniSecurityManagerFactory factory = new IniSecurityManagerFactory("classpath:shiro.ini");
        SecurityManager securityManager = factory.getInstance();
        SecurityUtils.setSecurityManager(securityManager);
        //2.获取subjecty对象
        Subject subject = SecurityUtils.getSubject();
        //3.创建tocken对象,web应用用户名从页面传入
        AuthenticationToken token = new UsernamePasswordToken("zhangsan", "z3");
        //完成登录
        try {
            subject.login(token);
            System.out.println("登录成功");
        } catch (UnknownAccountException e) {
            e.printStackTrace();
            System.out.println("用户不存在");

        } catch (IncorrectCredentialsException e) {
            e.printStackTrace();
            System.out.println("密码错误");
        } catch (AuthenticationException ae) {
            //unexpected condition? error?
        }


    }
}

Authentication process


(1) First call Subject.login(token) to log in, which will automatically delegate to SecurityManager
(2) SecurityManager is responsible for the real authentication logic; it will delegate to Authenticator for authentication;
(3) Authenticator is the real authentication Or, the core identity authentication entry point in the Shiro API, where you can customize and insert your own implementation; (
4) Authenticator may delegate to the corresponding AuthenticationStrategy for multi-Realm authentication. By default, ModularRealmAuthenticator will call AuthenticationStrategy for multi-Realm authentication;
(5) Authenticator will pass the corresponding token into Realm, and obtain authentication information from Realm. If no return/throws an exception, it means authentication failed. Multiple Realms can be configured here, and will be accessed according to the corresponding order and strategy. 

role, authorization

authorization concept

(1) Authorization, also called access control, is to control who accesses which resources in the application (such as accessing pages/editing data/page
operations, etc.). There are several key objects that need to be understood in authorization: Subject, Resource,
Permission , and Role.
(2) Subject (Subject): The user who accesses the application, and uses Subject in Shiro to represent the user. Users are only
allowed to access the corresponding resources after authorization.
(3) Resource (Resource): URLs that users can access in the application, such as accessing JSP pages, viewing/editing
some data, accessing a business method, printing text, etc. are all resources. Users can only access after authorization. (4) Permission (Permission): The atomic authorization unit in the security policy. Through the permission, we can indicate whether the user has the right to operate a certain resource
in the application .
That is, the permission indicates whether the user can access a certain resource in the application, such as: access
the user list page to view/add/modify/delete user data (that is, in many cases, it is CRUD (add query, modify and delete) type
permission ), etc. . Permissions represent whether a user has the right to operate a certain resource, that is, whether the operation on a certain resource is allowed or not
.
(5) Shiro supports coarse-grained permissions (such as all permissions of user modules) and fine-grained permissions (
permissions
, that is, instance level) (6) Role (Role): a collection of permissions, generally Give users roles instead of permissions , that is, users can
have a set of permissions, which is more convenient when granting permissions. Typical example: project manager, technical director, CTO, development engineer
Engineers are all roles, and different roles have a different set of permissions

Authorization method

1) Programmatic: complete by writing if/else authorization code block

(2) Annotation type: It is completed by placing corresponding annotations on the executed Java method, and corresponding exceptions will be thrown without permission

(3) JSP/GSP tags: completed through the corresponding tags on the JSP/GSP page

Authorization process 

(1) First call the Subject.isPermitted*/hasRole* interface, which will delegate to the SecurityManager, and
the SecurityManager will then delegate to the Authorizer;
(2) The Authorizer is the real authorizer. If you call isPermitted("user:view"), It will first
convert the string into the corresponding Permission instance through the PermissionResolver;
(3) Before authorization, it will call the corresponding Realm to obtain the corresponding role/permission of the Subject to match the incoming
role/permission;
(4) The Authorizer will judge whether the role/permission of the Realm matches the incoming one. If there are multiple Realms, it will be entrusted
to the ModularRealmAuthorizer for cyclic judgment. If it matches, such as isPermitted*/hasRole*, it will return
true, otherwise it will return false to indicate that the authorization failed

Authorized instance

(1) Get role information

1. Add role configuration to shiro.ini

[users]
zhangsan=z3,role1,role2
lisi=l4

2. Add code to the example, communicate with hasRole() to determine whether the user has a specified role

 (2) Judging authority information

1. Add permission configuration to shiro.ini

[roles]
role1=user:insert,user:select

 2. Add code to the example to determine whether the user has specified permissions

Shiro encryption

In actual system development, some sensitive information needs to be encrypted, such as user passwords. Shiro embeds many commonly used encryption algorithms, such as MD5 encryption. Shiro makes it easy to use message encryption.

public class ShiroMD5 {
    public static void main(String[] args) {
        //密码明文
        String password = "z3";
        //使用 md5加密
        Md5Hash md5Hash = new Md5Hash(password);
        System.out.println("md5 加密:"+md5Hash.toHex());
        //带盐的 md5 加密,盐就是在密码明文后拼接新字符串,然后再进行加密
        Md5Hash md5Hash2 = new Md5Hash(password,"salt");
        System.out.println("md5 带盐加密:"+md5Hash2.toHex());
         //为了保证安全,避免被破解还可以多次迭代加密,保证数据安全
        Md5Hash md5Hash3 = new Md5Hash(password,"salt",3);
        System.out.println("md5 带盐三次加密:"+md5Hash3.toHex());
        //使用父类实现加密
        SimpleHash simpleHash = new SimpleHash("MD5",password,"salt",3);
        System.out.println("父类带盐三次加密:"+simpleHash.toHex());
    }
}

Shiro custom login authentication 

Shiro's default login authentication is without encryption. If you want to implement encrypted authentication, you need to customize login authentication and customize Realm.

public class MyRealm extends AuthenticatingRealm {
    //自定义的登录认证方法,Shiro 的 login 方法底层会调用该类的认证方法完成登录认证 
    //需要配置自定义的 realm 生效,在 ini 文件中配置,或 Springboot 中配置 
    //该方法只是获取进行对比的信息,认证逻辑还是按照 Shiro 的底层认证逻辑完成认证 
    protected AuthenticationInfo doGetAuthenticationInfo(
            AuthenticationToken authenticationToken) throws

            AuthenticationException {
        //1 获取身份信息 
        String principal = authenticationToken.getPrincipal().toString();
        //2 获取凭证信息 
        String password = new String((char[])
                authenticationToken.getCredentials());
        System.out.println("认证用户信息:"+principal+"---"+password);
        //3 获取数据库中存储的用户信息 
        if(principal.equals("zhangsan")){
            //3.1 数据库存储的加盐迭代 3 次密码 
            String pwdInfo = "7174f64b13022acd3c56e2781e098a5f";
            //3.2 创建封装了校验逻辑的对象,将要比较的数据给该对象 
            AuthenticationInfo info = new SimpleAuthenticationInfo(
                    authenticationToken.getPrincipal(),
                    pwdInfo,
                    ByteSource.Util.bytes("salt"),
                    authenticationToken.getPrincipal().toString());
            return info;
        }
        return null;
    }
} 

Add configuration information in shiro.ini

[main]
md5CredentialsMatcher=org.apache.shiro.authc.cre
dential.Md5CredentialsMatcher
md5CredentialsMatcher.hashIterations=3
myrealm=com.atguigu.shirotest.MyRealm
myrealm.credentialsMatcher=$md5CredentialsMatcher
securityManager.realms=$myrealm
[users]
zhangsan=7174f64b13022acd3c56e2781e098a5f,role1,
role2
lisi=l4
[roles]
role1=user:insert,user:select

Guess you like

Origin blog.csdn.net/m0_62436868/article/details/130546864