6, Spring Boot integrates Shiro

6.1. Integration ideas

6.2. Create spring boot project

Create a new webapp directory under main

6.3. Introducing shiro dependency

 <!--introduce Shiro rely on-->
        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-spring-boot-starter</artifactId>
            <version>1.5.3</version>
        </dependency>

6.4. Configure shiro environment

Create configuration class ShiroConfig

1. Configuration: shiroFilterFactoryBean
@Bean
public ShiroFilterFactoryBean getShiroFilterFactoryBean(DefaultWebSecurityManager defaultWebSecurityManager) {
    	//Create shiro's filter
    ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        //Set security manager for filter
    shiroFilterFactoryBean.setSecurityManager(defaultWebSecurityManager);
        return shiroFilterFactoryBean;
    }
2. Configure WebSecurityManager
@Bean
public DefaultWebSecurityManager getDefaultWebSecurityManager(Realm realm) {        DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();
        //Settings for Security Manager
        defaultWebSecurityManager.setRealm(realm);
        return defaultWebSecurityManager;
    }
3. Configure custom relay
@Bean
 public Realm getRealm() {
        CustomerRealm customerRealm = new CustomerRealm();
        return customerRealm;
    }
ShiroConfig
package com.hz52.springboot_jsp_shiro.config;


import com.hz52.springboot_jsp_shiro.shiro.realms.CustomerRealm;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * @Program: springboot_jsp_shiro
 * @Description: Used to integrate shiro related configuration classes
 * @Author: 52Hz
 * @CreationTime: 2021 Wednesday, October 20, 2009, 9:18
 **/

@Configuration
public class ShiroConfig {

    //1. shiroFilter / / intercepts all requests (dependency 2)
    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(DefaultWebSecurityManager defaultWebSecurityManager) {
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();

        //Set security manager for filter
        shiroFilterFactoryBean.setSecurityManager(defaultWebSecurityManager);


        //Configure system restricted resources
        Map<String, String> map = new HashMap<String, String>();
        map.put("/index.jsp", "authc");  //authc requires authentication and authorization to request this resource
        shiroFilterFactoryBean.setFilterChainDefinitionMap(map);


        //Default authentication interface path
        shiroFilterFactoryBean.setLoginUrl("/login.jsp");


        //Configure system public resources


        return shiroFilterFactoryBean;
    }


    //2. Create security manager (dependency 3)
    @Bean
    public DefaultWebSecurityManager getDefaultWebSecurityManager(Realm realm) {
        DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();

        //Settings for Security Manager
        defaultWebSecurityManager.setRealm(realm);


        return defaultWebSecurityManager;
    }


    //3. Create a custom realm (depending on the custom realm in Realms)
    @Bean
    public Realm getRealm() {
        CustomerRealm customerRealm = new CustomerRealm();
        return customerRealm;

    }


}

Configure custom Realm

CustomerRealm
package com.hz52.springboot_jsp_shiro.shiro.realms;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

/**
 * @Program: springboot_jsp_shiro
 * @Description: Custom realm
 * @Author: 52Hz
 * @CreationTime: 2021 Wednesday, October 20, 2009 9:40
 **/
public class CustomerRealm extends AuthorizingRealm {
    
    //Processing authorization
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    //Process authentication
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        return null;
    }
}

6.5 common filters

Shiro provides several default filters. We can use these filters to configure the permission to control the specified URL. Shiro's common filters are as follows:

Configuration abbreviationCorresponding filterfunction
Authentication related
anonAnonymousFilterSpecifies that the url can be accessed anonymously
authcFormAuthenticationFilterForm based interceptors; For example, "/ * * = authc", if there is no login, it will jump to the corresponding login page to log in; Main attributes: usernameParam: user name parameter name (username) submitted by the form; passwordParam: the name of the password parameter submitted by the form (password); rememberMeParam: password parameter name of form submission (rememberMe); loginUrl: login page address (/ login.jsp); successUrl: the default redirection address after successful login; failureKeyAttribute: error information store key after login failure (shiroLoginFailure)
authcBasicBasicHttpAuthenticationFilterBasic HTTP authentication interceptor, main attribute: applicationName: information displayed in the pop-up login box (application)
logoutauthc.LogoutFilterExit interceptor, main attribute: redirectUrl: the redirected address after successful exit (/)
userUserFilterUser interceptor, the user has been authenticated / remember that I can log in
Authorization related
rolesRolesAuthorizationFilterRole authorization interceptor to verify whether the user has all roles; Main attribute: loginUrl: login page address (/ login.jsp); unauthorizedUrl: the address redirected after unauthorized; Example "/ admin/**=roles[admin]"
permsPermissionsAuthorizationFilterAuthority authorization interceptor to verify whether the user has all permissions; Properties are the same as roles; Example "/ user/**=perms [" user:create "]"
portPortFilterPort interceptor, main attribute: port (80): the port that can pass through; For example "/ test= port[80]", if the user accesses the page is non-80, the request port will be automatically changed to 80 and redirected to the 80 port. Other paths / parameters are the same
restHttpMethodPermissionFilterThe rest style interceptor automatically constructs the permission string according to the request method (GET=read, POST=create,PUT=update,DELETE=delete,HEAD=read,TRACE=read,OPTIONS=read, MKCOL=create); For example, "/ users=rest[user]", the "user:read,user:create,user:update,user:delete" permission string will be automatically spelled out for permission matching (all must be matched, isPermittedAll)
sslSslFilterThe SSL interceptor can pass only if the request protocol is https; Otherwise, it will automatically jump to https port (443); The others are the same as port interceptors
noSessionCreationNoSessionCreationAuthorizationFilterYou need to specify permissions to access

6.6 certification and withdrawal

Modify UserController

package com.hz52.springboot_jsp_shiro.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * @Program: springboot_jsp_shiro
 * @Description:
 * @Author: 52Hz
 * @CreationTime: 2021 Wednesday, October 20, 2014, 14:13
 **/
@Controller
@RequestMapping("user")
public class UserController {


    @RequestMapping("login")
    public String login(String username, String password) {

        //Get principal object
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(new UsernamePasswordToken(username, password));
            return "redirect:/index.jsp";
        } catch (UnknownAccountException e) {
            e.printStackTrace();
            System.out.println("User name error");
        } catch (IncorrectCredentialsException e) {
            e.printStackTrace();
            System.out.println("Password error");
        }
        return "redirect:/login.jsp";
    }


    @RequestMapping("logout")
    public String logout(String username, String password) {

        //Get principal object
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "redirect:/login.jsp";
    }


}

Modify ShiroConfig

package com.hz52.springboot_jsp_shiro.config;


import com.hz52.springboot_jsp_shiro.shiro.realms.CustomerRealm;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * @Program: springboot_jsp_shiro
 * @Description: Used to integrate shiro related configuration classes
 * @Author: 52Hz
 * @CreationTime: 2021 Wednesday, October 20, 2009, 9:18
 **/

@Configuration
public class ShiroConfig {

    //1. shiroFilter / / intercepts all requests (dependency 2)
    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(DefaultWebSecurityManager defaultWebSecurityManager) {
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();

        //Set security manager for filter
        shiroFilterFactoryBean.setSecurityManager(defaultWebSecurityManager);


        //Configure system restricted resources
        Map<String, String> map = new HashMap<String, String>();
        map.put("/user/login","anon");   //Set anon as a public resource
        map.put("/**", "authc");  //authc requires authentication and authorization to request this resource
        shiroFilterFactoryBean.setFilterChainDefinitionMap(map);


        //Default authentication interface path
        shiroFilterFactoryBean.setLoginUrl("/login.jsp");


        //Configure system public resources


        return shiroFilterFactoryBean;
    }


    //2. Create security manager (dependency 3)
    @Bean
    public DefaultWebSecurityManager getDefaultWebSecurityManager(Realm realm) {
        DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();

        //Settings for Security Manager
        defaultWebSecurityManager.setRealm(realm);


        return defaultWebSecurityManager;
    }


    //3. Create a custom realm (depending on the custom realm in Realms)
    @Bean
    public Realm getRealm() {
        CustomerRealm customerRealm = new CustomerRealm();
        return customerRealm;

    }


}

Modify login.jsp

<%@page contentType="text/html; UTF-8%" pageEncoding="UTF-8" isELIgnored="false" %>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
<h1>User login</h1>

<form action="${pageContext.request.contextPath}/user/login" method="post">
    user name:<input type="text" name="username"><br/>
    password:<input type="text" name="password"><br/>
    <input type="submit" value="Sign in">
</form>

</body>
</html>

Modify index.jsp

<%@page contentType="text/html; UTF-8%" pageEncoding="UTF-8" isELIgnored="false" %>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
<h1>System home page V1.0</h1>
<a href="${pageContext.request.contextPath}/user/logout">Log out</a>
<ul>
    <li><a href="">user management </a></li>
    <li><a href="">Commodity management</a></li>
    <li><a href="">Order management</a></li>
    <li><a href="">physical distribution management</a></li>


</ul>
</body>
</html>

Modify CustomerRealm

package com.hz52.springboot_jsp_shiro.shiro.realms;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

/**
 * @Program: springboot_jsp_shiro
 * @Description: Custom realm
 * @Author: 52Hz
 * @CreationTime: 2021 Wednesday, October 20, 2009 9:40
 **/
public class CustomerRealm extends AuthorizingRealm {

    //Processing authorization
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    //Process authentication
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {


        System.out.println("===================");
        String principal = (String) token.getPrincipal();
          if ("xiaochen".equals(principal)) {
            return new SimpleAuthenticationInfo(principal,"123",this.getName());
        }
        return null;
    }
}

6.7 database registration and certification

register

new table

Add dependent pom
		<!--mybatis Related components-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.2</version>
        </dependency>

        <!--mysql assembly-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.38</version>
        </dependency>


        <!--druid rely on-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.19</version>
        </dependency>
Configure application.properties
server.port=8080
server.servlet.context-path=/shiro
spring.application.name=shiro


spring.mvc.view.prefix=/
spring.mvc.view.suffix=.jsp





######Druid Monitoring configuration######
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.url=jdbc:mysql://localhost:3306/shiro?characterEncoding=utf8&useUnicode=true&useSSL=false&serverTimezone=GMT%2B8
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driverClassName=com.mysql.cj.jdbc.Driver
#dataSource Pool configuration
spring.datasource.initialSize=5
spring.datasource.minIdle=5
spring.datasource.maxActive=20
spring.datasource.maxWait=60000
spring.datasource.timeBetweenEvictionRunsMillis=60000   
spring.datasource.minEvictableIdleTimeMillis=300000
spring.datasource.validationQuery=SELECT 1 FROM DUAL
spring.datasource.testWhileIdle=true
spring.datasource.testOnBorrow=false
spring.datasource.exceptionSorter=true
spring.datasource.testOnReturn=false
spring.datasource.poolPreparedStatements=true
spring.datasource.filters=stat,wall,log4j
spring.datasource.maxPoolPreparedStatementPerConnectionSize=20
spring.datasource.connectionProperties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
spring.datasource.useGlobalDataSourceStat=true


mybatis.type-aliases-package=com.hz52.springboot_jsp_shiro.entity
mybatis.mapper-locations=classpath:com/hz52/mapper/*.xml





New SaltUtils

package com.hz52.Utils;

import java.util.Random;

/**
 * @Program: springboot_jsp_shiro
 * @Description: Static method for generating salt: how many bits are passed in and how many bits are returned
 * @Author: 52Hz
 * @CreationTime: 2021 Friday, October 22, 2010, 10:19
 **/
public class SaltUtils {

    public static String getSalt(int n) {
        char[] chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()".toCharArray();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < n; i++) {
            char aChar = chars[new Random().nextInt(chars.length)];
            sb.append(aChar);
        }
        return sb.toString();
    }

    public static void main(String[] args) {
        System.out.println(getSalt(32));
    }


}

New UserController
package com.hz52.springboot_jsp_shiro.controller;

import com.hz52.springboot_jsp_shiro.entity.User;
import com.hz52.springboot_jsp_shiro.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * @Program: springboot_jsp_shiro
 * @Description:
 * @Author: 52Hz
 * @CreationTime: 2021 Wednesday, October 20, 2014, 14:13
 **/
@Controller
@RequestMapping("user")
public class UserController {

    @Autowired
    private UserService userService;


    @RequestMapping("login")
    public String login(String username, String password) {

        //Get principal object
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(new UsernamePasswordToken(username, password));
            return "redirect:/index.jsp";
        } catch (UnknownAccountException e) {
            e.printStackTrace();
            System.out.println("User name error");
        } catch (IncorrectCredentialsException e) {
            e.printStackTrace();
            System.out.println("Password error");
        }
        return "redirect:/login.jsp";
    }


    @RequestMapping("logout")
    public String logout(String username, String password) {

        //Get principal object
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "redirect:/login.jsp";
    }


    /**
     * @Description: User registration
     * @Author: 52Hz
     * @Date: 2021/10/22
     * @Time: 15:29
     */
    @RequestMapping("register")
    public String register(User user) {
        try {
            userService.register(user);
            return "redirect:/login.jsp";
        } catch (Exception e) {
            e.printStackTrace();
            return "redirect:/register.jsp";
        }

    }

}

New UserServiceImpl
package com.hz52.springboot_jsp_shiro.service.impl;

import com.hz52.Utils.SaltUtils;
import com.hz52.springboot_jsp_shiro.dao.UserDAO;
import com.hz52.springboot_jsp_shiro.entity.User;
import com.hz52.springboot_jsp_shiro.service.UserService;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @Program: springboot_jsp_shiro
 * @Description:
 * @Author: 52Hz
 * @CreationTime: 2021 Friday, October 22, 2010, 10:14
 **/
@Service
@Transactional
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDAO userDAO;

    @Override
    public void register(User user) {
        
        //Handle business call DAO

        //MD5+Salt+Hash with plaintext password
        //1. Generate random salt
        String salt = SaltUtils.getSalt(8);
        //2. Save random salt to database
        user.setSalt(salt);
        //3. md5+salt+hash for plaintext password
        Md5Hash md5Hash = new Md5Hash(user.getPassword(), salt, 1024);
        user.setPassword(md5Hash.toHex());

        //Save object
        userDAO.save(user);

    }
}

New register.jsp
<%@page contentType="text/html; UTF-8%" pageEncoding="UTF-8" isELIgnored="false" %>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
<h1>User registration</h1>

<form action="${pageContext.request.contextPath}/user/register" method="post">
    user name:<input type="text" name="username"><br/>
    password:<input type="text" name="password"><br/>
    <input type="submit" value="Register now">
</form>

</body>
</html>
New UserDAOMapper.xml

<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.hz52.springboot_jsp_shiro.dao.UserDAO">


    <insert id="save" parameterType="User" useGeneratedKeys="true" keyProperty="id">
        insert into t_user
        values (#{id}, #{username}, #{password}, #{salt})
    </insert>

</mapper>

authentication

Modify UserDAO
package com.hz52.springboot_jsp_shiro.dao;

import com.hz52.springboot_jsp_shiro.entity.User;
import org.apache.ibatis.annotations.Mapper;

/**
 * @Program: springboot_jsp_shiro
 * @Description:
 * @Author: 52Hz
 * @CreationTime: 2021 Wednesday, October 20, 2007, 17:27
 **/
@Mapper
public interface UserDAO {
    void save(User user);

    User findByUserName(String username);
}

Modify UserService
package com.hz52.springboot_jsp_shiro.service;

import com.hz52.springboot_jsp_shiro.entity.User;

/**
 * @Program: springboot_jsp_shiro
 * @Description:
 * @Author: 52Hz
 * @CreationTime: 2021 Friday, October 22, 2010, 10:13
 **/
public interface UserService {

    //On behalf of registered users
    void register(User user);

    User findByUserName(String username);


}

Modify UserServiceImpl
package com.hz52.springboot_jsp_shiro.service.impl;

import com.hz52.Utils.SaltUtils;
import com.hz52.springboot_jsp_shiro.dao.UserDAO;
import com.hz52.springboot_jsp_shiro.entity.User;
import com.hz52.springboot_jsp_shiro.service.UserService;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @Program: springboot_jsp_shiro
 * @Description:
 * @Author: 52Hz
 * @CreationTime: 2021 Friday, October 22, 2010, 10:14
 **/
@Service
@Transactional
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDAO userDAO;

    @Override
    public void register(User user) {

        //Handle business call DAO

        //MD5+Salt+Hash with plaintext password
        //1. Generate random salt
        String salt = SaltUtils.getSalt(8);
        //2. Save random salt to database
        user.setSalt(salt);
        //3. md5+salt+hash for plaintext password
        Md5Hash md5Hash = new Md5Hash(user.getPassword(), salt, 1024);
        user.setPassword(md5Hash.toHex());

        //Save object
        userDAO.save(user);

    }

    @Override
    public User findByUserName(String username) {
        return userDAO.findByUserName(username);
    }
}

Modify CustomerRealm
package com.hz52.springboot_jsp_shiro.shiro.realms;

import com.hz52.springboot_jsp_shiro.Utils.ApplicationContextUtils;
import com.hz52.springboot_jsp_shiro.entity.User;
import com.hz52.springboot_jsp_shiro.service.UserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.context.ApplicationContext;
import org.springframework.util.ObjectUtils;

/**
 * @Program: springboot_jsp_shiro
 * @Description: Custom realm
 * @Author: 52Hz
 * @CreationTime: 2021 Wednesday, October 20, 2009 9:40
 **/
public class CustomerRealm extends AuthorizingRealm {

    //Processing authorization
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    //Process authentication
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {


        String principal = (String) token.getPrincipal();


        //Get the service object in the factory
        UserService userService = (UserService) ApplicationContextUtils.getBean("userService");
        User user = userService.findByUserName(principal);
        if (!ObjectUtils.isEmpty(user)) {
            return new SimpleAuthenticationInfo(user.getUsername(), user.getPassword(), ByteSource.Util.bytes(user.getSalt()), this.getName());
        }


        return null;
    }
}

Modify UserDAOMapper.xml
<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.hz52.springboot_jsp_shiro.dao.UserDAO">


    <insert id="save" parameterType="User" useGeneratedKeys="true" keyProperty="id">
        insert into t_user
        values (#{id}, #{username}, #{password}, #{salt})
    </insert>
    <select id="findByUserName" resultType="User" parameterType="String">
        select id, username,password, salt
        from t_user
        where username = #{username}
    </select>

</mapper>

Modify ShiroConfig
package com.hz52.springboot_jsp_shiro.config;


import com.hz52.springboot_jsp_shiro.shiro.realms.CustomerRealm;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * @Program: springboot_jsp_shiro
 * @Description: Used to integrate shiro related configuration classes
 * @Author: 52Hz
 * @CreationTime: 2021 Wednesday, October 20, 2009, 9:18
 **/

@Configuration
public class ShiroConfig {

    //1. shiroFilter / / intercepts all requests (dependency 2)
    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(DefaultWebSecurityManager defaultWebSecurityManager) {
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();

        //Set security manager for filter
        shiroFilterFactoryBean.setSecurityManager(defaultWebSecurityManager);


        //Configure system restricted resources
        Map<String, String> map = new HashMap<String, String>();
        map.put("/user/login", "anon");   //Set anon as a public resource
        map.put("/user/register", "anon");   //Set anon as a public resource
        map.put("/register.jsp", "anon");   //Set anon as a public resource


        map.put("/**", "authc");  //authc requires authentication and authorization to request this resource
        shiroFilterFactoryBean.setFilterChainDefinitionMap(map);


        //Default authentication interface path
        shiroFilterFactoryBean.setLoginUrl("/login.jsp");


        //Configure system public resources


        return shiroFilterFactoryBean;
    }


    //2. Create security manager (dependency 3)
    @Bean
    public DefaultWebSecurityManager getDefaultWebSecurityManager(Realm realm) {
        DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();

        //Settings for Security Manager
        defaultWebSecurityManager.setRealm(realm);


        return defaultWebSecurityManager;
    }


    //3. Create a custom realm (depending on the custom realm in Realms)
    @Bean
    public Realm getRealm() {
        CustomerRealm customerRealm = new CustomerRealm();

        //Modify password matcher: the default is the simplest
        HashedCredentialsMatcher credentialsMatcher = new HashedCredentialsMatcher();
        //Set the encryption algorithm to md5
        credentialsMatcher.setHashAlgorithmName("md5");
        //Sets the number of hashes
        credentialsMatcher.setHashIterations(1024);

        customerRealm.setCredentialsMatcher(
                credentialsMatcher);


        return customerRealm;

    }


}

6.8 authorization

Basic use

Modify index.jsp

Add label

<%@taglib prefix="shiro" uri="http://shiro.apache.org/tags" %>

Single role label
 <shiro:hasRole name="admin">
        <li><a href="">Commodity management</a></li>
        <li><a href="">Order management</a></li>
        <li><a href="">physical distribution management</a></li>
    </shiro:hasRole>

Multi role label
  <shiro:hasAnyRoles name="user,admin">
        <li><a href="">user management </a></li>
    </shiro:hasAnyRoles>

<%@page contentType="text/html; UTF-8%" pageEncoding="UTF-8" isELIgnored="false" %>
<%@taglib prefix="shiro" uri="http://shiro.apache.org/tags" %>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
<h1>System home page V1.0</h1>
<a href="${pageContext.request.contextPath}/user/logout">Log out</a>


<ul>
    <li><a href="">user management </a></li>
    <shiro:hasRole name="admin">
        <li><a href="">Commodity management</a></li>
        <li><a href="">Order management</a></li>
        <li><a href="">physical distribution management</a></li>
    </shiro:hasRole>


</ul>


</body>
</html>
Modify CustomerRealm
package com.hz52.springboot_jsp_shiro.shiro.realms;

import com.hz52.springboot_jsp_shiro.Utils.ApplicationContextUtils;
import com.hz52.springboot_jsp_shiro.entity.User;
import com.hz52.springboot_jsp_shiro.service.UserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.context.ApplicationContext;
import org.springframework.util.ObjectUtils;

/**
 * @Program: springboot_jsp_shiro
 * @Description: Custom realm
 * @Author: 52Hz
 * @CreationTime: 2021 Wednesday, October 20, 2009 9:40
 **/
public class CustomerRealm extends AuthorizingRealm {

    //Processing authorization
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {

        //Get identity information
        String primaryPrincipal = (String) principals.getPrimaryPrincipal();

        //Obtain role information and permission information according to the master identity information
        if ("xiaochen".equals(primaryPrincipal)) {
            SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
            simpleAuthorizationInfo.addRole("user");
            return simpleAuthorizationInfo;
        }


        return null;
    }

    //Process authentication
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String principal = (String) token.getPrincipal();
        //Get the service object in the factory
        UserService userService = (UserService) ApplicationContextUtils.getBean("userService");
        User user = userService.findByUserName(principal);
        if (!ObjectUtils.isEmpty(user)) {
            return new SimpleAuthenticationInfo(user.getUsername(), user.getPassword(), ByteSource.Util.bytes(user.getSalt()), this.getName());
        }
        return null;
    }
}

test

Modify CustomerRealm
package com.hz52.springboot_jsp_shiro.shiro.realms;

import com.hz52.springboot_jsp_shiro.Utils.ApplicationContextUtils;
import com.hz52.springboot_jsp_shiro.entity.User;
import com.hz52.springboot_jsp_shiro.service.UserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.context.ApplicationContext;
import org.springframework.util.ObjectUtils;

/**
 * @Program: springboot_jsp_shiro
 * @Description: Custom realm
 * @Author: 52Hz
 * @CreationTime: 2021 Wednesday, October 20, 2009 9:40
 **/
public class CustomerRealm extends AuthorizingRealm {

    //Processing authorization
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {

        //Get identity information
        String primaryPrincipal = (String) principals.getPrimaryPrincipal();

        //Obtain role information and permission information according to the master identity information
        if ("xiaochen".equals(primaryPrincipal)) {
            SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
            simpleAuthorizationInfo.addRole("admin");
            return simpleAuthorizationInfo;
        }


        return null;
    }

    //Process authentication
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String principal = (String) token.getPrincipal();
        //Get the service object in the factory
        UserService userService = (UserService) ApplicationContextUtils.getBean("userService");
        User user = userService.findByUserName(principal);
        if (!ObjectUtils.isEmpty(user)) {
            return new SimpleAuthenticationInfo(user.getUsername(), user.getPassword(), ByteSource.Util.bytes(user.getSalt()), this.getName());
        }
        return null;
    }
}

Modify index.jsp
<%@page contentType="text/html; UTF-8%" pageEncoding="UTF-8" isELIgnored="false" %>
<%@taglib prefix="shiro" uri="http://shiro.apache.org/tags" %>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
<h1>System home page V1.0</h1>
<a href="${pageContext.request.contextPath}/user/logout">Log out</a>


<ul>

    <shiro:hasAnyRoles name="user,admin">
        <li><a href="">user management </a></li>
    </shiro:hasAnyRoles>





    <shiro:hasRole name="admin">
        <li><a href="">Commodity management</a></li>
        <li><a href="">Order management</a></li>
        <li><a href="">physical distribution management</a></li>
    </shiro:hasRole>


</ul>


</body>
</html>
test

Test 2

Test 3

Modify index.jsp
<%@page contentType="text/html; UTF-8%" pageEncoding="UTF-8" isELIgnored="false" %>
<%@taglib prefix="shiro" uri="http://shiro.apache.org/tags" %>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
<h1>System home page V1.0</h1>
<a href="${pageContext.request.contextPath}/user/logout">Log out</a>


<ul>

    <shiro:hasAnyRoles name="user,admin">
        <li><a href="">user management </a></li>
        <ul>

            <shiro:hasPermission name="user:add:*">
                <li><a href="">add to</a></li>
            </shiro:hasPermission>

            <shiro:hasPermission name="user:delete:*">
                <li><a href="">delete</a></li>
            </shiro:hasPermission>

            <shiro:hasPermission name="user:update:*">
                <li><a href="">modify</a></li>
            </shiro:hasPermission>

            <shiro:hasPermission name="user:find:*">
                <li><a href="">query</a></li>
            </shiro:hasPermission>


        </ul>


    </shiro:hasAnyRoles>


    <shiro:hasRole name="admin">
        <li><a href="">Commodity management</a></li>
        <li><a href="">Order management</a></li>
        <li><a href="">physical distribution management</a></li>
    </shiro:hasRole>


</ul>


</body>
</html>
Modify CustomerRealm
package com.hz52.springboot_jsp_shiro.shiro.realms;

import com.hz52.springboot_jsp_shiro.Utils.ApplicationContextUtils;
import com.hz52.springboot_jsp_shiro.entity.User;
import com.hz52.springboot_jsp_shiro.service.UserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.context.ApplicationContext;
import org.springframework.util.ObjectUtils;

/**
 * @Program: springboot_jsp_shiro
 * @Description: Custom realm
 * @Author: 52Hz
 * @CreationTime: 2021 Wednesday, October 20, 2009 9:40
 **/
public class CustomerRealm extends AuthorizingRealm {

    //Processing authorization
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {

        //Get identity information
        String primaryPrincipal = (String) principals.getPrimaryPrincipal();

        //Obtain role information and permission information according to the master identity information
        if ("xiaochen".equals(primaryPrincipal)) {
            SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();

            //Add role
            simpleAuthorizationInfo.addRole("user");

            //Add role string
            simpleAuthorizationInfo.addStringPermission("user:*:*");


            return simpleAuthorizationInfo;
        }


        return null;
    }

    //Process authentication
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String principal = (String) token.getPrincipal();
        //Get the service object in the factory
        UserService userService = (UserService) ApplicationContextUtils.getBean("userService");
        User user = userService.findByUserName(principal);
        if (!ObjectUtils.isEmpty(user)) {
            return new SimpleAuthenticationInfo(user.getUsername(), user.getPassword(), ByteSource.Util.bytes(user.getSalt()), this.getName());
        }
        return null;
    }
}

Demo order addition verification

Role verification

Add orderController

package com.hz52.springboot_jsp_shiro.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * @Program: springboot_jsp_shiro
 * @Description:
 * @Author: 52Hz
 * @CreationTime: 2021 Saturday, October 23, 2009 9:47
 **/
@Controller
@RequestMapping("order")
public class orderController {



    //Method 3: Annotation
    @RequiresRoles(value = {"admin","user"})    //Used to judge the role
    @RequestMapping("save")
    public String save() {

        System.out.println("Entry method");
        
        //Get principal object
        Subject subject = SecurityUtils.getSubject();


        //Mode 1: code mode
        if (subject.hasRole("admin")) {
            System.out.println("Save order");
        } else {
            System.out.println("No access");
        }

        //Method 2: Based on permission string


        return "redirect:/index.jsp";
    }


}

Permission string
Modify CustomerRealm

package com.hz52.springboot_jsp_shiro.shiro.realms;

import com.hz52.springboot_jsp_shiro.Utils.ApplicationContextUtils;
import com.hz52.springboot_jsp_shiro.entity.User;
import com.hz52.springboot_jsp_shiro.service.UserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.context.ApplicationContext;
import org.springframework.util.ObjectUtils;

/**
 * @Program: springboot_jsp_shiro
 * @Description: Custom realm
 * @Author: 52Hz
 * @CreationTime: 2021 Wednesday, October 20, 2009 9:40
 **/
public class CustomerRealm extends AuthorizingRealm {

    //Processing authorization
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {

        //Get identity information
        String primaryPrincipal = (String) principals.getPrimaryPrincipal();

        //Obtain role information and permission information according to the master identity information
        if ("xiaochen".equals(primaryPrincipal)) {
            SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();

            //Add role
            simpleAuthorizationInfo.addRole("admin");
            simpleAuthorizationInfo.addRole("user");

            //Add role string
           // simpleAuthorizationInfo.addStringPermission("user:*:*");

            simpleAuthorizationInfo.addStringPermission("user:add:*");
            simpleAuthorizationInfo.addStringPermission("user:update:01");


            return simpleAuthorizationInfo;
        }


        return null;
    }

    //Process authentication
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String principal = (String) token.getPrincipal();
        //Get the service object in the factory
        UserService userService = (UserService) ApplicationContextUtils.getBean("userService");
        User user = userService.findByUserName(principal);
        if (!ObjectUtils.isEmpty(user)) {
            return new SimpleAuthenticationInfo(user.getUsername(), user.getPassword(), ByteSource.Util.bytes(user.getSalt()), this.getName());
        }
        return null;
    }
}

Modify orderController

package com.hz52.springboot_jsp_shiro.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * @Program: springboot_jsp_shiro
 * @Description:
 * @Author: 52Hz
 * @CreationTime: 2021 Saturday, October 23, 2009 9:47
 **/
@Controller
@RequestMapping("order")
public class orderController {



    //Method 3: Annotation
    //@RequiresRoles("admin") / / used to judge roles (single)
    //@RequiresRoles(value = {"admin","user"}) / / used to judge that the role representation has

    @RequiresPermissions("user:update:01")      //Permission string

    @RequestMapping("save")
    public String save() {

        System.out.println("Entry method");
        
        //Get principal object
        Subject subject = SecurityUtils.getSubject();


        //Mode 1: code mode
        if (subject.hasRole("admin")) {
            System.out.println("Save order");
        } else {
            System.out.println("No access");
        }

        //Method 2: Based on permission string


        return "redirect:/index.jsp";
    }


}

Role information database acquisition

shiro database
/*
 Navicat Premium Data Transfer

 Source Server         : MySQL
 Source Server Type    : MySQL
 Source Server Version : 80013
 Source Host           : localhost:3306
 Source Schema         : shiro

 Target Server Type    : MySQL
 Target Server Version : 80013
 File Encoding         : 65001

 Date: 23/10/2021 10:53:50
*/

SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

-- ----------------------------
-- Table structure for t_pers
-- ----------------------------
DROP TABLE IF EXISTS `t_pers`;
CREATE TABLE `t_pers`  (
  `id` int(6) NOT NULL AUTO_INCREMENT,
  `name` varchar(60) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `url` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;

-- ----------------------------
-- Records of t_pers
-- ----------------------------

-- ----------------------------
-- Table structure for t_role
-- ----------------------------
DROP TABLE IF EXISTS `t_role`;
CREATE TABLE `t_role`  (
  `id` int(6) NOT NULL AUTO_INCREMENT,
  `name` varchar(60) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;

-- ----------------------------
-- Records of t_role
-- ----------------------------

-- ----------------------------
-- Table structure for t_role_perms
-- ----------------------------
DROP TABLE IF EXISTS `t_role_perms`;
CREATE TABLE `t_role_perms`  (
  `id` int(6) NOT NULL AUTO_INCREMENT,
  `roleid` int(6) NULL DEFAULT NULL,
  `permsid` int(6) NULL DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;

-- ----------------------------
-- Records of t_role_perms
-- ----------------------------

-- ----------------------------
-- Table structure for t_user
-- ----------------------------
DROP TABLE IF EXISTS `t_user`;
CREATE TABLE `t_user`  (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(40) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `password` varchar(40) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `salt` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;

-- ----------------------------
-- Records of t_user
-- ----------------------------
INSERT INTO `t_user` VALUES (1, '13185020807', '90d43ef551bf0d455024b24f1f5760a1', '90^MZwku');
INSERT INTO `t_user` VALUES (2, 'xiaochen', 'aed28391070e3c36918f2d4d08f38089', '!Tr5*JpZ');

-- ----------------------------
-- Table structure for t_user_roles
-- ----------------------------
DROP TABLE IF EXISTS `t_user_roles`;
CREATE TABLE `t_user_roles`  (
  `id` int(6) NOT NULL AUTO_INCREMENT,
  `userid` int(6) NULL DEFAULT NULL,
  `roleid` int(6) NULL DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;

-- ----------------------------
-- Records of t_user_roles
-- ----------------------------

SET FOREIGN_KEY_CHECKS = 1;

new table

t_role

t_pers

t_role_perms

t_user_role

New Role
package com.hz52.springboot_jsp_shiro.entity;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;

/**
 * @Program: springboot_jsp_shiro
 * @Description:
 * @Author: 52Hz
 * @CreationTime: 2021 Saturday, October 23, 2011, 11:10
 **/
@Data
@Accessors(chain = true)
@AllArgsConstructor
@NoArgsConstructor
public class Role {
    private String id;
    private String name;

}

New Perms
package com.hz52.springboot_jsp_shiro.entity;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;

/**
 * @Program: springboot_jsp_shiro
 * @Description:
 * @Author: 52Hz
 * @CreationTime: 2021 Saturday, October 23, 2011, 11:10
 **/
@Data
@Accessors(chain = true)
@AllArgsConstructor
@NoArgsConstructor
public class Perms {
    private String id;
    private String name;
    private String url;

}

Modify User
package com.hz52.springboot_jsp_shiro.entity;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;

import java.util.List;

/**
 * @Program: springboot_jsp_shiro
 * @Description:
 * @Author: 52Hz
 * @CreationTime: 2021 Wednesday, October 20, 2007, 17:20
 **/
@Data
@Accessors(chain = true)
@AllArgsConstructor
@NoArgsConstructor
public class User {
    private String id;
    private String username;
    private String password;
    private String salt;


    /**
     * @Description: Define character collection
     * @Author: 52Hz
     * @Date: 2021/10/23
     * @Time: 11:14
     */
    private List<Role> roles;


}

Modify UserDAO
package com.hz52.springboot_jsp_shiro.dao;

import com.hz52.springboot_jsp_shiro.entity.Role;
import com.hz52.springboot_jsp_shiro.entity.User;
import org.apache.ibatis.annotations.Mapper;

import java.util.List;

/**
 * @Program: springboot_jsp_shiro
 * @Description:
 * @Author: 52Hz
 * @CreationTime: 2021 Wednesday, October 20, 2007, 17:27
 **/
@Mapper
public interface UserDAO {
    void save(User user);

    User findByUserName(String username);


    //Query all roles by user
    User findRolesByUserName(String username);


}

Modify UserDAOMapper.xml

<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.hz52.springboot_jsp_shiro.dao.UserDAO">


    <insert id="save" parameterType="User" useGeneratedKeys="true" keyProperty="id">
        insert into t_user
        values (#{id}, #{username}, #{password}, #{salt})
    </insert>
    <select id="findByUserName" resultType="User" parameterType="String">
        select id, username, password, salt
        from t_user
        where username = #{username}
    </select>

    <resultMap id="userMap" type="User">
        <id column="uid" property="id"/>
        <result column="uname" property="username"/>

        <!--Role information-->
        <collection property="roles" javaType="list" ofType="Role">
            <id column="rid" property="id"/>
            <result column="rname" property="name"/>
        </collection>


    </resultMap>

    <select id="findRolesByUserName" parameterType="String" resultMap="userMap">
        SELECT u.id       uid,
               u.username uname,
               r.id       rid,
               r.NAME     rname
        FROM t_user u
                 LEFT JOIN t_user_role ur ON u.id = ur.userid
                 LEFT JOIN t_role r ON ur.roleid = r.id
        WHERE u.username = #{username}
    </select>

</mapper>

Test SQL

Modify UserService
package com.hz52.springboot_jsp_shiro.service;

import com.hz52.springboot_jsp_shiro.entity.Role;
import com.hz52.springboot_jsp_shiro.entity.User;

import java.util.List;

/**
 * @Program: springboot_jsp_shiro
 * @Description:
 * @Author: 52Hz
 * @CreationTime: 2021 Friday, October 22, 2010, 10:13
 **/
public interface UserService {

    //On behalf of registered users
    void register(User user);

    User findByUserName(String username);

    User findRolesByUserName(String username);

}

Modify UserServiceImpl
package com.hz52.springboot_jsp_shiro.service.impl;

import com.hz52.springboot_jsp_shiro.Utils.SaltUtils;
import com.hz52.springboot_jsp_shiro.dao.UserDAO;
import com.hz52.springboot_jsp_shiro.entity.Role;
import com.hz52.springboot_jsp_shiro.entity.User;
import com.hz52.springboot_jsp_shiro.service.UserService;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @Program: springboot_jsp_shiro
 * @Description:
 * @Author: 52Hz
 * @CreationTime: 2021 Friday, October 22, 2010, 10:14
 **/
@Service("userService")
@Transactional
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDAO userDAO;


    @Override
    public void register(User user) {

        //Handle business call DAO

        //MD5+Salt+Hash with plaintext password
        //1. Generate random salt
        String salt = SaltUtils.getSalt(8);
        //2. Save random salt to database
        user.setSalt(salt);
        //3. md5+salt+hash for plaintext password
        Md5Hash md5Hash = new Md5Hash(user.getPassword(), salt, 1024);
        user.setPassword(md5Hash.toHex());

        //Save object
        userDAO.save(user);

    }

    @Override
    public User findByUserName(String username) {
        return userDAO.findByUserName(username);
    }

    @Override
    public User findRolesByUserName(String username) {


        return userDAO.findRolesByUserName(username);
    }
}

Modify CustomerRealm
package com.hz52.springboot_jsp_shiro.shiro.realms;

import com.hz52.springboot_jsp_shiro.Utils.ApplicationContextUtils;
import com.hz52.springboot_jsp_shiro.entity.Role;
import com.hz52.springboot_jsp_shiro.entity.User;
import com.hz52.springboot_jsp_shiro.service.UserService;
import org.apache.commons.collections.ListUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.apache.shiro.util.CollectionUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.util.ObjectUtils;

import java.util.List;

/**
 * @Program: springboot_jsp_shiro
 * @Description: Custom realm
 * @Author: 52Hz
 * @CreationTime: 2021 Wednesday, October 20, 2009 9:40
 **/
public class CustomerRealm extends AuthorizingRealm {

    //Processing authorization
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {

        //Get identity information
        String primaryPrincipal = (String) principals.getPrimaryPrincipal();
        System.out.println("Invoke authorization authentication:" + primaryPrincipal);

        //Obtain role information and permission information according to the master identity information
        UserService userService = (UserService) ApplicationContextUtils.getBean("userService");
        User user = userService.findRolesByUserName(primaryPrincipal);

        //Authorization role information
        if (!CollectionUtils.isEmpty(user.getRoles())) {
            SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
            user.getRoles().forEach(role -> {
                simpleAuthorizationInfo.addRole(role.getName());
            });
            return simpleAuthorizationInfo;
        }


        return null;
    }

    //Process authentication
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String principal = (String) token.getPrincipal();
        //Get the service object in the factory
        UserService userService = (UserService) ApplicationContextUtils.getBean("userService");
        User user = userService.findByUserName(principal);
        if (!ObjectUtils.isEmpty(user)) {
            return new SimpleAuthenticationInfo(user.getUsername(), user.getPassword(), ByteSource.Util.bytes(user.getSalt()), this.getName());
        }
        return null;
    }
}

test

Permission information database acquisition

Modify Role
package com.hz52.springboot_jsp_shiro.entity;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;

import java.util.List;

/**
 * @Program: springboot_jsp_shiro
 * @Description:
 * @Author: 52Hz
 * @CreationTime: 2021 Saturday, October 23, 2011, 11:10
 **/
@Data
@Accessors(chain = true)
@AllArgsConstructor
@NoArgsConstructor
public class Role {
    private String id;
    private String name;

    /**
    *@Description: Define permission set
    *@Author: 52Hz
    *@Date: 2021/10/23
    *@Time: 13:43
    */
    private List<Perms> perms;

}

Modify t_pers

Modify t_role_perms

Modify UserService
package com.hz52.springboot_jsp_shiro.service;

import com.hz52.springboot_jsp_shiro.entity.Perms;
import com.hz52.springboot_jsp_shiro.entity.Role;
import com.hz52.springboot_jsp_shiro.entity.User;

import java.util.List;

/**
 * @Program: springboot_jsp_shiro
 * @Description:
 * @Author: 52Hz
 * @CreationTime: 2021 Friday, October 22, 2010, 10:13
 **/
public interface UserService {

    //On behalf of registered users
    void register(User user);

    User findByUserName(String username);

    User findRolesByUserName(String username);

    //Query permission collection according to role id
    List<Perms> findPermsByRid(String id);

}

Modify UserServiceImpl
package com.hz52.springboot_jsp_shiro.service.impl;

import com.hz52.springboot_jsp_shiro.Utils.SaltUtils;
import com.hz52.springboot_jsp_shiro.dao.UserDAO;
import com.hz52.springboot_jsp_shiro.entity.Perms;
import com.hz52.springboot_jsp_shiro.entity.Role;
import com.hz52.springboot_jsp_shiro.entity.User;
import com.hz52.springboot_jsp_shiro.service.UserService;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @Program: springboot_jsp_shiro
 * @Description:
 * @Author: 52Hz
 * @CreationTime: 2021 Friday, October 22, 2010, 10:14
 **/
@Service("userService")
@Transactional
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDAO userDAO;


    @Override
    public void register(User user) {

        //Handle business call DAO

        //MD5+Salt+Hash with plaintext password
        //1. Generate random salt
        String salt = SaltUtils.getSalt(8);
        //2. Save random salt to database
        user.setSalt(salt);
        //3. md5+salt+hash for plaintext password
        Md5Hash md5Hash = new Md5Hash(user.getPassword(), salt, 1024);
        user.setPassword(md5Hash.toHex());

        //Save object
        userDAO.save(user);

    }

    @Override
    public User findByUserName(String username) {
        return userDAO.findByUserName(username);
    }

    @Override
    public User findRolesByUserName(String username) {


        return userDAO.findRolesByUserName(username);
    }


    @Override
    public List<Perms> findPermsByRid(String id) {
        return userDAO.findPermsByRid(id);
    }



}

Modify CustomerRealm
package com.hz52.springboot_jsp_shiro.shiro.realms;

import com.hz52.springboot_jsp_shiro.Utils.ApplicationContextUtils;
import com.hz52.springboot_jsp_shiro.entity.Perms;
import com.hz52.springboot_jsp_shiro.entity.Role;
import com.hz52.springboot_jsp_shiro.entity.User;
import com.hz52.springboot_jsp_shiro.service.UserService;
import org.apache.commons.collections.ListUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.apache.shiro.util.CollectionUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.util.ObjectUtils;

import java.util.List;

/**
 * @Program: springboot_jsp_shiro
 * @Description: Custom realm
 * @Author: 52Hz
 * @CreationTime: 2021 Wednesday, October 20, 2009 9:40
 **/
public class CustomerRealm extends AuthorizingRealm {

    //Processing authorization
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {

        //Get identity information
        String primaryPrincipal = (String) principals.getPrimaryPrincipal();
        System.out.println("Invoke authorization authentication:" + primaryPrincipal);

        //Obtain role information and permission information according to the master identity information
        UserService userService = (UserService) ApplicationContextUtils.getBean("userService");
        User user = userService.findRolesByUserName(primaryPrincipal);

        //Authorization role information
        if (!CollectionUtils.isEmpty(user.getRoles())) {
            SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
            user.getRoles().forEach(role -> {

                //Role information
                simpleAuthorizationInfo.addRole(role.getName());

                //permissions information
                List<Perms> perms = userService.findPermsByRid(role.getId());
                if (!CollectionUtils.isEmpty(perms)) {
                    perms.forEach(perm -> {
                        simpleAuthorizationInfo.addStringPermission(perm.getName());
                    });
                }

            });
            return simpleAuthorizationInfo;
        }


        return null;
    }

    //Process authentication
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String principal = (String) token.getPrincipal();
        //Get the service object in the factory
        UserService userService = (UserService) ApplicationContextUtils.getBean("userService");
        User user = userService.findByUserName(principal);
        if (!ObjectUtils.isEmpty(user)) {
            return new SimpleAuthenticationInfo(user.getUsername(), user.getPassword(), ByteSource.Util.bytes(user.getSalt()), this.getName());
        }
        return null;
    }
}

Modify UserDAOMapper.xml

<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.hz52.springboot_jsp_shiro.dao.UserDAO">


    <insert id="save" parameterType="User" useGeneratedKeys="true" keyProperty="id">
        insert into t_user
        values (#{id}, #{username}, #{password}, #{salt})
    </insert>
    <select id="findByUserName" resultType="User" parameterType="String">
        select id, username, password, salt
        from t_user
        where username = #{username}
    </select>

    <resultMap id="userMap" type="User">
        <id column="uid" property="id"/>
        <result column="uname" property="username"/>

        <!--Role information-->
        <collection property="roles" javaType="list" ofType="Role">
            <id column="rid" property="id"/>
            <result column="rname" property="name"/>
        </collection>
    </resultMap>
    <select id="findRolesByUserName" parameterType="String" resultMap="userMap">
        SELECT u.id       uid,
               u.username uname,
               r.id       rid,
               r.NAME     rname
        FROM t_user u
                 LEFT JOIN t_user_role ur ON u.id = ur.userid
                 LEFT JOIN t_role r ON ur.roleid = r.id
        WHERE u.username = #{username}
    </select>


    <select id="findPermsByRid" parameterType="String" resultType="Perms">
        SELECT p.id,
               p.NAME,
               p.url,
               r.NAME
        FROM t_role r
                 LEFT JOIN t_role_perms rp ON r.id = rp.roleid
                 LEFT JOIN t_pers p ON rp.permsid = p.id
        WHERE r.id = #{id}
    </select>

</mapper>

Modify index.jsp
<%@page contentType="text/html; UTF-8%" pageEncoding="UTF-8" isELIgnored="false" %>
<%@taglib prefix="shiro" uri="http://shiro.apache.org/tags" %>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
<h1>System home page V1.0</h1>
<a href="${pageContext.request.contextPath}/user/logout">Log out</a>


<ul>

    <shiro:hasAnyRoles name="user,admin">
        <li><a href="">user management </a></li>
        <ul>

            <shiro:hasPermission name="user:add:*">
                <li><a href="">add to</a></li>
            </shiro:hasPermission>

            <shiro:hasPermission name="user:delete:*">
                <li><a href="">delete</a></li>
            </shiro:hasPermission>

            <shiro:hasPermission name="user:update:*">
                <li><a href="">modify</a></li>
            </shiro:hasPermission>

            <shiro:hasPermission name="order:find:*">
                <li><a href="">query</a></li>
            </shiro:hasPermission>


        </ul>


    </shiro:hasAnyRoles>


    <shiro:hasRole name="admin">
        <li><a href="">Commodity management</a></li>
        <li><a href="">Order management</a></li>
        <li><a href="">physical distribution management</a></li>
    </shiro:hasRole>


</ul>


</body>
</html>
test
xiaochen

zhangsan

Keywords: Java Shiro Spring Boot Back-end

Added by adamjblakey on Sat, 06 Nov 2021 22:38:00 +0200