欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

SpringBoot整合Shiro思路(最新超詳細)

 更新時間:2022年03月03日 11:58:45   作者:Java追求者  
這篇文章主要介紹了SpringBoot整合Shiro思路(最新超詳細),本文內(nèi)容比較長,通過實例代碼給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下

1.SpringBoot整合Shiro思路

在這里插入圖片描述

2. 環(huán)境搭建

2.1 創(chuàng)建項目

在這里插入圖片描述

2.2 引入依賴

pom.xml

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

        <artifactId>spring-boot-devtools</artifactId>
        <scope>runtime</scope>
        <optional>true</optional>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    <!--引入Jsp依賴-->
        <groupId>org.apache.tomcat.embed</groupId>
        <artifactId>tomcat-embed-jasper</artifactId>
    <!--jstl-->
        <groupId>jstl</groupId>
        <artifactId>jstl</artifactId>
        <version>1.2</version>
</dependencies>
<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
            <configuration>
                <excludes>
                    <exclude>
                        <groupId>org.projectlombok</groupId>
                        <artifactId>lombok</artifactId>
                    </exclude>
                </excludes>
            </configuration>
        </plugin>
    </plugins>
</build>

2.3 創(chuàng)建前端頁面

在webapp文件夾中創(chuàng)建index.jsp和login.jsp
index.jsp

<%@page contentType="text/html;UTF-8" pageEncoding="UTF-8" isErrorPage="false" %>
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
<%--受限資源--%>
<h1>系統(tǒng)主頁</h1>
<ul>
    <li><a href="#" rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow" >用戶管理</a></li>
    <li><a href="#" rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow" >商品管理</a></li>
    <li><a href="#" rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow" >訂單管理</a></li>
    <li><a href="#" rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow" >物流管理</a></li>
</ul>
</body>
</html>

login.jsp

<%@page contentType="text/html;UTF-8" pageEncoding="UTF-8" isErrorPage="false" %>
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
<h1>登錄界面</h1>
<form action="${pageContext.request.contextPath}/user/login" method="post">
    用戶名:<input type="text" name="username" > <br/>
    密碼  : <input type="text" name="password"> <br>
    <input type="submit" value="登錄">
</form>
</html>

2.4 配置視圖信息

application.properties

server.port=8080
server.servlet.context-path=/shiro
spring.application.name=shiro

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

2.5 解決IDEA沖突問題

JSP 與IDEA 與SpringBoot存在一定的不兼容,修改此配置即可解決

在這里插入圖片描述

2.6 測試搭建的環(huán)境

在這里插入圖片描述

3. 整合Shiro

3.1 引入依賴

pom.xml

<!--引入shrio-->
<dependency>
    <groupId>org.apache.shiro</groupId>
    <artifactId>shiro-spring-boot-starter</artifactId>
    <version>1.5.3</version>
</dependency>

3.2 自定義Realm

在shiro文件夾下創(chuàng)建realm文件夾

package com.test.shiro.realm;

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;

/**
 * 自定義Realm
 */
public class CustomerRealm extends AuthorizingRealm {
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

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

3.3 Shiro配置

在config文件夾中創(chuàng)建ShiroConfig.java

@Configuration
public class ShiroConfig {
    //ShiroFilter過濾所有請求
    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(DefaultWebSecurityManager securityManager) {
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        //給ShiroFilter配置安全管理器
        shiroFilterFactoryBean.setSecurityManager(securityManager);
        //配置系統(tǒng)受限資源
        //配置系統(tǒng)公共資源
        Map<String, String> map = new HashMap<String, String>();
        map.put("/index.jsp","authc");//表示這個資源需要認證和授權(quán)
        // 設(shè)置認證界面路徑
        shiroFilterFactoryBean.setLoginUrl("/login.jsp");
        shiroFilterFactoryBean.setFilterChainDefinitionMap(map);

        return shiroFilterFactoryBean;
    }
    //創(chuàng)建安全管理器
    @Bean
    public DefaultWebSecurityManager getDefaultWebSecurityManager(Realm realm) {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setRealm(realm);
        return securityManager;
    }
    //創(chuàng)建自定義Realm
    @Bean
    public Realm getRealm() {
        CustomerRealm realm = new CustomerRealm();
        return realm;
    }
}

3.4 啟動測試

輸入http://localhost:8080/shiro/index.jsp,發(fā)現(xiàn)需要跳轉(zhuǎn)到login.jsp

在這里插入圖片描述

4. 常見過濾器

注意: shiro提供和多個默認的過濾器,我們可以用這些過濾器來配置控制指定url的權(quán)限:

5. 認證和退出

5.1 在index.jsp添加a標(biāo)簽

index.jsp

<a href="${pageContext.request.contextPath}/user/logout" rel="external nofollow"  rel="external nofollow" >退出登錄</a>

5.2 編寫controller

UserController.java

@Controller
@RequestMapping("/user")
public class UserController {
    @RequestMapping("logout")
    public String logout() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "redirect:/login.jsp";
    }
    @RequestMapping("/login")
    public String login(String username, String password) {
        //獲取主題對象
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(new UsernamePasswordToken(username,password));
            System.out.println("登錄成功?。?!");
            return "redirect:/index.jsp";
        } catch (UnknownAccountException e) {
            e.printStackTrace();
            System.out.println("用戶錯誤!?。?);
        } catch (IncorrectCredentialsException e) {
            System.out.println("密碼錯誤?。?!");
        }
        return "redirect:/login.jsp";
    }
}

5.3 修改自定義Realm

CustomerRealm.java

/**
 * 自定義Realm
 */
public class CustomerRealm extends AuthorizingRealm {
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String principal = (String) authenticationToken.getPrincipal();
        if ("zhangsan".equals(principal)) {
            return new SimpleAuthenticationInfo(principal,"123456",this.getName());
        }
        return null;
    }
}

5.4 修改ShiroConfig配置

ShiroConfig.java
公共資源一定是在受限資源上面,不然會造成死循環(huán)。

@Configuration
public class ShiroConfig {
    //ShiroFilter過濾所有請求
    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(DefaultWebSecurityManager securityManager) {
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        //給ShiroFilter配置安全管理器
        shiroFilterFactoryBean.setSecurityManager(securityManager);
        //配置系統(tǒng)受限資源
        //配置系統(tǒng)公共資源
        Map<String, String> map = new HashMap<String, String>();
        map.put("/user/login","anon");//表示這個為公共資源 一定是在受限資源上面
        map.put("/**","authc");//表示這個受限資源需要認證和授權(quán)
        // 設(shè)置認證界面路徑
        shiroFilterFactoryBean.setLoginUrl("/login.jsp");
        shiroFilterFactoryBean.setFilterChainDefinitionMap(map);

        return shiroFilterFactoryBean;
    }
    //創(chuàng)建安全管理器
    @Bean
    public DefaultWebSecurityManager getDefaultWebSecurityManager(Realm realm) {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setRealm(realm);
        return securityManager;
    }
    //創(chuàng)建自定義Realm
    @Bean
    public Realm getRealm() {
        CustomerRealm realm = new CustomerRealm();
        return realm;
    }
}

5.5 測試

登錄正常,登出正常,未登錄和登出后不能訪問index.jsp

在這里插入圖片描述

在這里插入圖片描述

6. MDSalt的認證實現(xiàn)

6.1 創(chuàng)建數(shù)據(jù)庫

SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for t_user
-- ----------------------------
DROP TABLE IF EXISTS `t_user`;
CREATE TABLE `t_user` (
  `id` INT(6) NOT NULL AUTO_INCREMENT,
  `username` VARCHAR(40) DEFAULT NULL,
  `password` VARCHAR(40) DEFAULT NULL,
  `salt` VARCHAR(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=INNODB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;

SET FOREIGN_KEY_CHECKS = 1;

6.2 引入依賴

<!--引入mybatis-->
<dependency>
    <groupId>tk.mybatis</groupId>
    <artifactId>mapper-spring-boot-starter</artifactId>
    <version>2.1.5</version>
</dependency>
<!--mysql-->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>
<!--druid-->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.2.6</version>
</dependency>

6.3 配置數(shù)據(jù)源和整合mybatis

application.properties

#配置數(shù)據(jù)源
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/springboot_shrio?characterEncoding=UTF-8
spring.datasource.username=root
spring.datasource.password=123456

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

6.4 創(chuàng)建實體類entity

User.java

@Data
@Accessors(chain = true)
@NoArgsConstructor
@AllArgsConstructor
public class User {
    private String  id;
    private String username;
    private String password;
    private String salt;
}

6.5 創(chuàng)建DAO接口

UserDao.java

@Mapper
@Repository
public interface UserDao {
    void save(User user);

    User findByUsername(String username);
}

6.6 編寫Mapper配置文件

UserDao.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.test.dao.UserDao">

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

6.7 創(chuàng)建Service接口

UserService.java

public interface UserService {
    //注冊用戶方法
    void register(User user);
    //根據(jù)用戶名查找用戶
    User findByUsername(String username);
}

6.8 編寫生成隨機鹽工具類

SaltUtil.java

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

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

6.9 編寫Service實現(xiàn)類

UserServiceImpl.java

@Service("userService")
@Transactional
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDao userDao;

    @Override
    public void register(User user) {
        //1.獲取隨機鹽
        String salt = SaltUtil.getSalt(8);
        //2.將隨機鹽保存到數(shù)據(jù)
        user.setSalt(salt);
        //3.明文密碼進行md5 + salt + hash散列
       Md5Hash MD5 = new Md5Hash(user.getPassword(),salt,1024);
       user.setPassword(MD5.toHex());
       userDao.save(user);
    }

    @Override
    public User findByUsername(String username) {
        return userDao.findByUsername(username);
    }
}

6.10 編寫Controller

UserController.java

@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping("/register")
    public String register(User user) {
        try {
            userService.register(user);
            return "redirect:/login.jsp";
        } catch (Exception e) {
            e.printStackTrace();
            return "redirect:/register.jsp";
        }
    }
    @RequestMapping("logout")
    public String logout() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "redirect:/login.jsp";
    }
    @RequestMapping("/login")
    public String login(String username, String password) {
        //獲取主題對象
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(new UsernamePasswordToken(username,password));
            System.out.println("登錄成功?。?!");
            return "redirect:/index.jsp";
        } catch (UnknownAccountException e) {
            e.printStackTrace();
            System.out.println("用戶錯誤?。?!");
        } catch (IncorrectCredentialsException e) {
            System.out.println("密碼錯誤!??!");
        }
        return "redirect:/login.jsp";
    }
}

6.11 修改自定義Realm

CustomerRealm.java

/**
 * 自定義Realm
 */
public class CustomerRealm extends AuthorizingRealm {
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String principal = (String) authenticationToken.getPrincipal();
        //獲取UserService對象
        UserService userService = (UserService) ApplicationContextUtil.getBean("userService");
        //System.out.println(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;
    }
}

6.12 編寫獲取對象工具類

ApplicationContextUtil.java

@Component
public class ApplicationContextUtil implements ApplicationContextAware {

    private static ApplicationContext context;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.context = applicationContext;
    }
    //根據(jù)bean名字獲取工廠中指定bean 對象
    public static Object getBean(String beanName) {
        return context.getBean(beanName);
    }
}

6.13 修改Config

ShiroConfig.java

@Configuration
public class ShiroConfig {
    //ShiroFilter過濾所有請求
    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(DefaultWebSecurityManager securityManager) {
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        //給ShiroFilter配置安全管理器
        shiroFilterFactoryBean.setSecurityManager(securityManager);
        //配置系統(tǒng)受限資源
        //配置系統(tǒng)公共資源
        Map<String, String> map = new HashMap<String, String>();
        map.put("/user/login","anon");//表示這個為公共資源 一定是在受限資源上面
        map.put("/user/register","anon");//表示這個為公共資源 一定是在受限資源上面
        map.put("/register.jsp","anon");//表示這個為公共資源 一定是在受限資源上面
        map.put("/**","authc");//表示這個受限資源需要認證和授權(quán)
        // 設(shè)置認證界面路徑
        shiroFilterFactoryBean.setLoginUrl("/login.jsp");
        shiroFilterFactoryBean.setFilterChainDefinitionMap(map);

        return shiroFilterFactoryBean;
    }
    //創(chuàng)建安全管理器
    @Bean
    public DefaultWebSecurityManager getDefaultWebSecurityManager(Realm realm) {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setRealm(realm);
        return securityManager;
    }
    //創(chuàng)建自定義Realm
    @Bean
    public Realm getRealm() {
        CustomerRealm realm = new CustomerRealm();
        HashedCredentialsMatcher credentialsMatcher = new HashedCredentialsMatcher();
        //設(shè)置使用MD5加密算法
        credentialsMatcher.setHashAlgorithmName("md5");
        //散列次數(shù)
        credentialsMatcher.setHashIterations(1024);
        realm.setCredentialsMatcher(credentialsMatcher);
        return realm;
    }

6.14 添加注冊頁面

register.jsp

<%@page contentType="text/html;UTF-8" pageEncoding="UTF-8" isErrorPage="false" %>
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
<h1>注冊界面</h1>
<form action="${pageContext.request.contextPath}/user/register" method="post">
    用戶名:<input type="text" name="username" > <br/>
    密碼  : <input type="text" name="password"> <br>
    <input type="submit" value="立即注冊">
</form>
</html>

6.15 測試

添加成功

在這里插入圖片描述


認證

在這里插入圖片描述

優(yōu)化版推薦閱讀(SpringBoot + Shiro + Jwt 實現(xiàn)登錄認證,代碼分析):https://blog.csdn.net/qq_43290318/article/details/108225519

7. 授權(quán)實現(xiàn)

7.1 模擬數(shù)據(jù)實現(xiàn)授權(quán)

7.1.1 模擬數(shù)據(jù)

CustomerRealm.java

@Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        String principal = (String) principalCollection.getPrimaryPrincipal();
        if ("zhangsan".equals(principal)) {
            SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
            info.addRole("admin");
            info.addRole("user");
            info.addStringPermission("user:find:*");
            info.addStringPermission("admin:*");
            return info;
        }
        return null;
    }

7.1.2 頁面資源授權(quán)

index.jsp

<%@page contentType="text/html;UTF-8" pageEncoding="UTF-8" isErrorPage="false" %>
<%@taglib prefix="shiro" uri="http://shiro.apache.org/tags" %>
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
<%--受限資源--%>
<h1>系統(tǒng)主頁</h1>
<a href="${pageContext.request.contextPath}/user/logout" rel="external nofollow"  rel="external nofollow" >退出登錄</a>
<ul>
    <shiro:hasRole name="user">
        <li><a href="#" rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow" >用戶管理</a></li>
        <ul>
            <shiro:hasPermission name="user:save:*">
                <li><a href="#" rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow" >增加</a></li>
            </shiro:hasPermission>
            <shiro:hasPermission name="user:delete:*">
            <li><a href="#" rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow" >刪除</a></li>
            </shiro:hasPermission>
            <shiro:hasPermission name="user:update:*">
            <li><a href="#" rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow" >修改</a></li>
            </shiro:hasPermission>
            <shiro:hasPermission name="user:find:*">
            <li><a href="#" rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow" >查詢</a></li>
            </shiro:hasPermission>
        </ul>
    </shiro:hasRole>
    <shiro:hasRole name="admin">
        <li><a href="#" rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow" >商品管理</a></li>
        <li><a href="#" rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow" >訂單管理</a></li>
        <li><a href="#" rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow"  rel="external nofollow" >物流管理</a></li>
    </shiro:hasRole>

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

7.1.3 代碼方式授權(quán)

OrderController.java

@Controller
@RequestMapping("order")
public class OrderController {
    @RequestMapping("save")
    public String save() {
        //基于角色
        //獲取主體對象
        Subject subject = SecurityUtils.getSubject();
        //代碼方式
        if (subject.hasRole("admin")) {
            System.out.println("保存訂單!");
        }else{
            System.out.println("無權(quán)訪問!");
        }
        System.out.println("進入save方法============");
        return "redircet:/index.jsp";
    }
}

7.1.4 方法調(diào)用授權(quán)

OrderController.java

@Controller
@RequestMapping("order")
public class OrderController {

    @RequiresRoles(value={"admin","user"})//用來判斷角色  同時具有 admin user
    @RequiresPermissions("user:update:01") //用來判斷權(quán)限字符串
    @RequestMapping("save")
    public String save(){
        System.out.println("進入方法");
        return "redirect:/index.jsp";
    }

}

7.2 數(shù)據(jù)庫實現(xiàn)角色授權(quán)

7.2.1 授權(quán)數(shù)據(jù)持久化

在這里插入圖片描述

7.2.2 創(chuàng)建數(shù)據(jù)庫表

SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

-- ----------------------------
-- Table structure for t_perms
-- ----------------------------
DROP TABLE IF EXISTS `t_perms`;
CREATE TABLE `t_pers` (
  `id` int(6) NOT NULL AUTO_INCREMENT,
  `name` varchar(80) DEFAULT NULL,
  `url` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

-- ----------------------------
-- 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) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

-- ----------------------------
-- Table structure for t_role_perms
-- ----------------------------
DROP TABLE IF EXISTS `t_role_perms`;
CREATE TABLE `t_role_perms` (
  `id` int(6) NOT NULL,
  `roleid` int(6) DEFAULT NULL,
  `permsid` int(6) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

-- ----------------------------
-- Table structure for t_user
-- ----------------------------
DROP TABLE IF EXISTS `t_user`;
CREATE TABLE `t_user` (
  `id` int(6) NOT NULL AUTO_INCREMENT,
  `username` varchar(40) DEFAULT NULL,
  `password` varchar(40) DEFAULT NULL,
  `salt` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Table structure for t_user_role
-- ----------------------------
DROP TABLE IF EXISTS `t_user_role`;
CREATE TABLE `t_user_role` (
  `id` int(6) NOT NULL,
  `userid` int(6) DEFAULT NULL,
  `roleid` int(6) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

SET FOREIGN_KEY_CHECKS = 1;

7.2.3 創(chuàng)建實體類

User

@Data
@Accessors(chain = true)
@AllArgsConstructor
@NoArgsConstructor
public class User implements Serializable {
    private String id;
    private String username;
    private String password;
    private String salt;

    //定義角色集合
    private List<Role> roles;

}

Role

@Data
@Accessors(chain = true)
@AllArgsConstructor
@NoArgsConstructor
public class Role implements Serializable {
    private String id;
    private String name;

    //定義權(quán)限的集合
    private List<Perms> perms;

}

Perms

@Data
@Accessors(chain = true)
@AllArgsConstructor
@NoArgsConstructor
public class Perms implements Serializable {
    private String id;
    private String name;
    private String url;
}

7.2.4 創(chuàng)建Dao接口

UserDao.java

//根據(jù)用戶名查詢所有角色
User findRolesByUserName(String username);

7.2.5 編寫Mapper實現(xiàn)

UserDao.xml

<resultMap id="userMap" type="User">
  <id column="uid" property="id"/>
  <result column="username" property="username"/>
  <!--角色信息-->
  <collection property="roles" javaType="list" ofType="Role">
    <id column="id" property="id"/>
    <result column="rname" property="name"/>
  </collection>
</resultMap>

<select id="findRolesByUserName" parameterType="String" resultMap="userMap">
  SELECT u.id uid,u.username,r.id,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>

7.2.6 編寫Service接口

UserService.java

public interface UserService {
    User findRoleByUsername(String username);
}

7.2.7 編寫Service實現(xiàn)方法

UserServiceImpl.java

@Service("userService")
@Transactional
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDao userDao;
    
    @Override
    public User findRoleByUsername(String username) {
        return userDao.findRoleByUsername(username);
    }
}

7.2.8 修改自定義Realm

CustomerRealm.java

/**
 * 自定義Realm
 */
public class CustomerRealm extends AuthorizingRealm {
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        String principal = (String) principalCollection.getPrimaryPrincipal();
        //獲取UserService對象
        UserService userService = (UserService) ApplicationContextUtil.getBean("userService");
        //System.out.println(userService);
        //基于角色授權(quán)
        User user = userService.findRoleByUsername(principal);
        if (!CollectionUtils.isEmpty(user.getRoles())) {
            SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
            user.getRoles().forEach(role -> info.addRole(role.getName()));
            return info;
        }
        return null;
    }
    ......
}

7.3 數(shù)據(jù)庫實現(xiàn)權(quán)限授權(quán)

7.3.1 創(chuàng)建Dao接口

UserDao.java

	@Mapper
@Repository
public interface UserDao {
    //根據(jù)角色id查詢權(quán)限集合
    Role findPermByRoleId(String id);
    //根據(jù)角色id查詢權(quán)限集合
    List<Perms> findPermsByRoleId2(String id);
}

7.3.2 編寫Mapper實現(xiàn)

UserDao.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.test.dao.UserDao">
    <resultMap id="roleMap" type="Role">
        <result column="name" property="name"/>
        <collection property="perms" javaType="list" ofType="Perms">
            <id column="id" property="id"/>
            <result column="name" property="name"/>
            <result column="url" property="url"/>
        </collection>
    </resultMap>
    <select id="findPermByRoleId" parameterType="String" resultType="Role" resultMap="roleMap">
        SELECT r.`name`,p.`id`,p.`name`,p.`url`
        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>

    <select id="findPermsByRoleId2" 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>

7.3.3 編寫Service接口

UserService.java

public interface UserService {
     //根據(jù)角色id查詢權(quán)限集合
    Role findPermByRoleId(String id);
    //根據(jù)角色id查詢權(quán)限集合
    List<Perms> findPermsByRoleId2(String id);
}

7.3.4 編寫Service實現(xiàn)方法

UserServiceImpl.java

@Service("userService")
@Transactional
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDao userDao;
    
  @Override
    public Role findPermByRoleId(String id) {
        return userDao.findPermByRoleId(id);
    }

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

7.3.5 修改自定義Realm

CustomerRealm.java

/**
 * 自定義Realm
 */
public class CustomerRealm extends AuthorizingRealm {
   @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        String principal = (String) principalCollection.getPrimaryPrincipal();
        //獲取UserService對象
        UserService userService = (UserService) ApplicationContextUtil.getBean("userService");
        //System.out.println(userService);
        //基于角色授權(quán)
        User user = userService.findRoleByUsername(principal);
        System.out.println("user======="+user);
        if (!CollectionUtils.isEmpty(user.getRoles())) {
            SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
            user.getRoles().forEach(role ->{
                    info.addRole(role.getName());
                /*Role role2 = userService.findPermByRoleId(role.getId());
                System.out.println("role2======"+role2);
                if (!CollectionUtils.isEmpty(role2.getPerms())) {
                    role2.getPerms().forEach(perm -> info.addStringPermission(perm.getName()));
                }*/

                //權(quán)限信息
                List<Perms> perms = userService.findPermsByRoleId2(role.getId());
                System.out.println("perms========"+perms);
                if(!CollectionUtils.isEmpty(perms) && perms.get(0)!=null ){
                    perms.forEach(perm->{
                        info.addStringPermission(perm.getName());
                    });
                }
            });
            return info;
        }
        return null;
    }
    ......
}

7.3.6 數(shù)據(jù)庫表數(shù)據(jù)設(shè)置

在這里插入圖片描述

7.3.7 測試

在這里插入圖片描述

在這里插入圖片描述

8. shiro使用緩存

8.1 Cache

8.1.1 Cache 作用

Cache 緩存: 計算機內(nèi)存中一段數(shù)據(jù)

作用: 用來減輕DB的訪問壓力,從而提高系統(tǒng)的查詢效率

流程:

在這里插入圖片描述

8.1.2 使用shiro中默認EhCache實現(xiàn)緩存

1.引入依賴

<!--引入shiro和ehcache-->
<dependency>
  <groupId>org.apache.shiro</groupId>
  <artifactId>shiro-ehcache</artifactId>
  <version>1.5.3</version>
</dependency>

2.開啟緩存

//3.創(chuàng)建自定義realm
@Bean
public Realm getRealm() {
    CustomerRealm realm = new CustomerRealm();
    HashedCredentialsMatcher credentialsMatcher = new HashedCredentialsMatcher();
    //設(shè)置使用MD5加密算法
    credentialsMatcher.setHashAlgorithmName("md5");
    //散列次數(shù)
    credentialsMatcher.setHashIterations(1024);
    realm.setCredentialsMatcher(credentialsMatcher);

    //開啟緩存管理器
    realm.setCacheManager(new EhCacheManager());
    realm.setCachingEnabled(true);//開啟緩存
    realm.setAuthenticationCachingEnabled(true);//開啟認證緩存
    realm.setAuthenticationCacheName("authentication");
    realm.setAuthorizationCachingEnabled(true);//開啟授權(quán)緩存
    realm.setAuthorizationCacheName("authorization");

    return realm;
}

8.1.3 測試

注意:如果控制臺沒有任何sql展示說明緩存已經(jīng)開啟

8.2 Redis

8.2.1 shiro中使用Redis作為緩存實現(xiàn)

1.引入redis依賴

<!--redis整合springboot-->
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

2.配置redis連接

spring.redis.port=6379
spring.redis.host=localhost
spring.redis.database=0

3.啟動redis服務(wù)

在這里插入圖片描述

4. 開發(fā)RedisCacheManager

自定義shiro緩存管理器
RedisCacheManager.java

import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheException;
import org.apache.shiro.cache.CacheManager;

//自定義shiro緩存管理器
public class RedisCacheManager implements CacheManager {
    //參數(shù)1:認證或者是授權(quán)緩存的統(tǒng)一名稱
    @Override
    public <K, V> Cache<K, V> getCache(String cacheName) throws CacheException {
        System.out.println(cacheName);
        return new RedisCache<K,V>(cacheName);
    }
}

5.開RedisCache實現(xiàn)

//自定義redis緩存的實現(xiàn)
public class RedisCache<k,v> implements Cache<k,v> {

    private String cacheName;

    public RedisCache() {
    }

    public RedisCache(String cacheName) {
        this.cacheName = cacheName;
    }

    @Override
    public v get(k k) throws CacheException {
        return (v) getRedisTemplate().opsForHash().get(this.cacheName, k.toString());
    }

    @Override
    public v put(k k, v v) throws CacheException {
        System.out.println("put key: "+k);
        System.out.println("put value:"+v);
        getRedisTemplate().opsForHash().put(this.cacheName,k.toString(), v);
        return null;
    }

    @Override
    public v remove(k k) throws CacheException {
        System.out.println("=============remove=============");
        return (v) getRedisTemplate().opsForHash().delete(this.cacheName,k.toString());
    }

    @Override
    public void clear() throws CacheException {
        System.out.println("=============clear==============");
        getRedisTemplate().delete(this.cacheName);
    }

    @Override
    public int size() {
        return getRedisTemplate().opsForHash().size(this.cacheName).intValue();
    }

    @Override
    public Set<k> keys() {
        return getRedisTemplate().opsForHash().keys(this.cacheName);
    }

    @Override
    public Collection<v> values() {
        return getRedisTemplate().opsForHash().values(this.cacheName);
    }

    private RedisTemplate getRedisTemplate(){
        RedisTemplate redisTemplate = (RedisTemplate) ApplicationContextUtil.getBean("redisTemplate");
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        return redisTemplate;
    }
}

6. 啟動項目測試發(fā)現(xiàn)報錯 錯誤解釋: 由于shiro中提供的simpleByteSource實現(xiàn)沒有實現(xiàn)序列化,所有在認證時出現(xiàn)錯誤信息

在這里插入圖片描述

解決方案如下:
實現(xiàn) 實體類 序列化
自定義salt實現(xiàn) 實現(xiàn)序列化接口

import org.apache.shiro.codec.Base64;
import org.apache.shiro.codec.CodecSupport;
import org.apache.shiro.codec.Hex;
import org.apache.shiro.util.ByteSource;

import java.io.File;
import java.io.InputStream;
import java.io.Serializable;
import java.util.Arrays;
//自定義salt實現(xiàn) 實現(xiàn)序列化接口
public class MyByteSource implements ByteSource, Serializable {
    private  byte[] bytes;
    private String cachedHex;
    private String cachedBase64;
    public MyByteSource(byte[] bytes) {
        this.bytes = bytes;
    }
    public MyByteSource(char[] chars) {
        this.bytes = CodecSupport.toBytes(chars);
    public MyByteSource(String string) {
        this.bytes = CodecSupport.toBytes(string);
    public MyByteSource(ByteSource source) {
        this.bytes = source.getBytes();
    public MyByteSource(File file) {
        this.bytes = (new MyByteSource.BytesHelper()).getBytes(file);
    public MyByteSource(InputStream stream) {
        this.bytes = (new MyByteSource.BytesHelper()).getBytes(stream);
    public static boolean isCompatible(Object o) {
        return o instanceof byte[] || o instanceof char[] || o instanceof String || o instanceof ByteSource || o instanceof File || o instanceof InputStream;
    public byte[] getBytes() {
        return this.bytes;
    public boolean isEmpty() {
        return this.bytes == null || this.bytes.length == 0;
    public String toHex() {
        if (this.cachedHex == null) {
            this.cachedHex = Hex.encodeToString(this.getBytes());
        }
        return this.cachedHex;
    public String toBase64() {
        if (this.cachedBase64 == null) {
            this.cachedBase64 = Base64.encodeToString(this.getBytes());
        return this.cachedBase64;
    public String toString() {
        return this.toBase64();
    public int hashCode() {
        return this.bytes != null && this.bytes.length != 0 ? Arrays.hashCode(this.bytes) : 0;
    public boolean equals(Object o) {
        if (o == this) {
            return true;
        } else if (o instanceof ByteSource) {
            ByteSource bs = (ByteSource)o;
            return Arrays.equals(this.getBytes(), bs.getBytes());
        } else {
            return false;
    private static final class BytesHelper extends CodecSupport {
        private BytesHelper() {
        public byte[] getBytes(File file) {
            return this.toBytes(file);
        public byte[] getBytes(InputStream stream) {
            return this.toBytes(stream);
}

修改自定義realm中使用的salt

@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
    String principal = (String) authenticationToken.getPrincipal();
    //獲取UserService對象
    UserService userService = (UserService) ApplicationContextUtil.getBean("userService");
    //System.out.println(userService);
    User user = userService.findByUsername(principal);
    if (!ObjectUtils.isEmpty(user)) {
        return new SimpleAuthenticationInfo(user.getUsername(), user.getPassword(), new MyByteSource(user.getSalt()), this.getName());
    }
    return null;
}

8. 測試

在這里插入圖片描述

9. shrio實現(xiàn)驗證功能

9.1 驗證碼工具類

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.Random;

/**
 *@創(chuàng)建人  cx
 *@創(chuàng)建時間  2018/11/27 17:36
 *@描述   驗證碼生成
 */
public class VerifyCodeUtils{

    //使用到Algerian字體,系統(tǒng)里沒有的話需要安裝字體,字體只顯示大寫,去掉了1,0,i,o幾個容易混淆的字符
    public static final String VERIFY_CODES = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ";
    private static Random random = new Random();


    /**
     * 使用系統(tǒng)默認字符源生成驗證碼
     * @param verifySize    驗證碼長度
     * @return
     */
    public static String generateVerifyCode(int verifySize){
        return generateVerifyCode(verifySize, VERIFY_CODES);
    }
    /**
     * 使用指定源生成驗證碼
     * @param verifySize    驗證碼長度
     * @param sources   驗證碼字符源
     * @return
     */
    public static String generateVerifyCode(int verifySize, String sources){
        if(sources == null || sources.length() == 0){
            sources = VERIFY_CODES;
        }
        int codesLen = sources.length();
        Random rand = new Random(System.currentTimeMillis());
        StringBuilder verifyCode = new StringBuilder(verifySize);
        for(int i = 0; i < verifySize; i++){
            verifyCode.append(sources.charAt(rand.nextInt(codesLen-1)));
        }
        return verifyCode.toString();
    }

    /**
     * 生成隨機驗證碼文件,并返回驗證碼值
     * @param w
     * @param h
     * @param outputFile
     * @param verifySize
     * @return
     * @throws IOException
     */
    public static String outputVerifyImage(int w, int h, File outputFile, int verifySize) throws IOException{
        String verifyCode = generateVerifyCode(verifySize);
        outputImage(w, h, outputFile, verifyCode);
        return verifyCode;
    }

    /**
     * 輸出隨機驗證碼圖片流,并返回驗證碼值
     * @param w
     * @param h
     * @param os
     * @param verifySize
     * @return
     * @throws IOException
     */
    public static String outputVerifyImage(int w, int h, OutputStream os, int verifySize) throws IOException{
        String verifyCode = generateVerifyCode(verifySize);
        outputImage(w, h, os, verifyCode);
        return verifyCode;
    }

    /**
     * 生成指定驗證碼圖像文件
     * @param w
     * @param h
     * @param outputFile
     * @param code
     * @throws IOException
     */
    public static void outputImage(int w, int h, File outputFile, String code) throws IOException{
        if(outputFile == null){
            return;
        }
        File dir = outputFile.getParentFile();
        if(!dir.exists()){
            dir.mkdirs();
        }
        try{
            outputFile.createNewFile();
            FileOutputStream fos = new FileOutputStream(outputFile);
            outputImage(w, h, fos, code);
            fos.close();
        } catch(IOException e){
            throw e;
        }
    }

    /**
     * 輸出指定驗證碼圖片流
     * @param w
     * @param h
     * @param os
     * @param code
     * @throws IOException
     */
    public static void outputImage(int w, int h, OutputStream os, String code) throws IOException{
        int verifySize = code.length();
        BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
        Random rand = new Random();
        Graphics2D g2 = image.createGraphics();
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
        Color[] colors = new Color[5];
        Color[] colorSpaces = new Color[] { Color.WHITE, Color.CYAN,
                Color.GRAY, Color.LIGHT_GRAY, Color.MAGENTA, Color.ORANGE,
                Color.PINK, Color.YELLOW };
        float[] fractions = new float[colors.length];
        for(int i = 0; i < colors.length; i++){
            colors[i] = colorSpaces[rand.nextInt(colorSpaces.length)];
            fractions[i] = rand.nextFloat();
        }
        Arrays.sort(fractions);

        g2.setColor(Color.GRAY);// 設(shè)置邊框色
        g2.fillRect(0, 0, w, h);

        Color c = getRandColor(200, 250);
        g2.setColor(c);// 設(shè)置背景色
        g2.fillRect(0, 2, w, h-4);

        //繪制干擾線
        Random random = new Random();
        g2.setColor(getRandColor(160, 200));// 設(shè)置線條的顏色
        for (int i = 0; i < 20; i++) {
            int x = random.nextInt(w - 1);
            int y = random.nextInt(h - 1);
            int xl = random.nextInt(6) + 1;
            int yl = random.nextInt(12) + 1;
            g2.drawLine(x, y, x + xl + 40, y + yl + 20);
        }

        // 添加噪點
        float yawpRate = 0.05f;// 噪聲率
        int area = (int) (yawpRate * w * h);
        for (int i = 0; i < area; i++) {
            int x = random.nextInt(w);
            int y = random.nextInt(h);
            int rgb = getRandomIntColor();
            image.setRGB(x, y, rgb);
        }

        shear(g2, w, h, c);// 使圖片扭曲

        g2.setColor(getRandColor(100, 160));
        int fontSize = h-4;
        Font font = new Font("Algerian", Font.ITALIC, fontSize);
        g2.setFont(font);
        char[] chars = code.toCharArray();
        for(int i = 0; i < verifySize; i++){
            AffineTransform affine = new AffineTransform();
            affine.setToRotation(Math.PI / 4 * rand.nextDouble() * (rand.nextBoolean() ? 1 : -1), (w / verifySize) * i + fontSize/2, h/2);
            g2.setTransform(affine);
            g2.drawChars(chars, i, 1, ((w-10) / verifySize) * i + 5, h/2 + fontSize/2 - 10);
        }

        g2.dispose();
        ImageIO.write(image, "jpg", os);
    }

    private static Color getRandColor(int fc, int bc) {
        if (fc > 255)
            fc = 255;
        if (bc > 255)
            bc = 255;
        int r = fc + random.nextInt(bc - fc);
        int g = fc + random.nextInt(bc - fc);
        int b = fc + random.nextInt(bc - fc);
        return new Color(r, g, b);
    }

    private static int getRandomIntColor() {
        int[] rgb = getRandomRgb();
        int color = 0;
        for (int c : rgb) {
            color = color << 8;
            color = color | c;
        }
        return color;
    }

    private static int[] getRandomRgb() {
        int[] rgb = new int[3];
        for (int i = 0; i < 3; i++) {
            rgb[i] = random.nextInt(255);
        }
        return rgb;
    }

    private static void shear(Graphics g, int w1, int h1, Color color) {
        shearX(g, w1, h1, color);
        shearY(g, w1, h1, color);
    }

    private static void shearX(Graphics g, int w1, int h1, Color color) {

        int period = random.nextInt(2);

        boolean borderGap = true;
        int frames = 1;
        int phase = random.nextInt(2);

        for (int i = 0; i < h1; i++) {
            double d = (double) (period >> 1)
                    * Math.sin((double) i / (double) period
                    + (6.2831853071795862D * (double) phase)
                    / (double) frames);
            g.copyArea(0, i, w1, 1, (int) d, 0);
            if (borderGap) {
                g.setColor(color);
                g.drawLine((int) d, i, 0, i);
                g.drawLine((int) d + w1, i, w1, i);
            }
        }

    }

    private static void shearY(Graphics g, int w1, int h1, Color color) {

        int period = random.nextInt(40) + 10; // 50;

        boolean borderGap = true;
        int frames = 20;
        int phase = 7;
        for (int i = 0; i < w1; i++) {
            double d = (double) (period >> 1)
                    * Math.sin((double) i / (double) period
                    + (6.2831853071795862D * (double) phase)
                    / (double) frames);
            g.copyArea(i, 0, 1, h1, 0, (int) d);
            if (borderGap) {
                g.setColor(color);
                g.drawLine(i, (int) d, i, 0);
                g.drawLine(i, (int) d + h1, i, h1);
            }

        }

    }
    public static void main(String[] args) throws IOException {
        //獲取驗證碼
        String s = generateVerifyCode(4);
        //將驗證碼放入圖片中
        outputImage(260,60,new File("/Users/chenyannan/Desktop/安工資料/aa.jpg"),s);
        System.out.println(s);
    }
}

9.2 開發(fā)頁面加入驗證碼

<form action="${pageContext.request.contextPath}/user/login" method="post">
    用戶名:<input type="text" name="username"> 

    密碼 : <input type="text" name="password"> 

    請輸入驗證碼: <input type="text" name="code"><img src="${pageContext.request.contextPath}/user/getImage" alt="">

    <input type="submit" value="登錄">
</form>

9.3 開發(fā)控制器

@RequestMapping("getImage")
public void getImage(HttpSession session, HttpServletResponse response) throws IOException {
  //生成驗證碼
  String code = VerifyCodeUtils.generateVerifyCode(4);
  //驗證碼放入session
  session.setAttribute("code",code);
  //驗證碼存入圖片
  ServletOutputStream os = response.getOutputStream();
  response.setContentType("image/png");
  VerifyCodeUtils.outputImage(220,60,os,code);
}

9.4 放行驗證碼

ShiroConfig.java

map.put("/user/getImage","anon");//驗證碼

9.5 修改認證流程

@RequestMapping("login")
public String login(String username, String password,String code,HttpSession session) {
    //比較驗證碼
    String codes = (String) session.getAttribute("code");
    try {
        if (codes.equalsIgnoreCase(code)){
            //獲取主體對象
            Subject subject = SecurityUtils.getSubject();
                subject.login(new UsernamePasswordToken(username, password));
                return "redirect:/index.jsp";
        }else{
            throw new RuntimeException("驗證碼錯誤!");
        }
    } catch (UnknownAccountException e) {
        e.printStackTrace();
        System.out.println("用戶名錯誤!");
    } catch (IncorrectCredentialsException e) {
        e.printStackTrace();
        System.out.println("密碼錯誤!");
    }catch (Exception e){
        e.printStackTrace();
        System.out.println(e.getMessage());
    }
    return "redirect:/login.jsp";
}

9.6 啟動測試

在這里插入圖片描述

10. shiro標(biāo)簽在jsp使用

需要在jsp頁面中引入標(biāo)簽
<%@ taglib uri="http://shiro.apache.org/tags" prefix="shiro" %>
標(biāo)簽:
<shiro:authenticated> 登錄之后
<shiro:notAuthenticated> 不在登錄狀態(tài)時
<shiro:guest> 用戶在沒有RememberMe時
<shiro:user> 用戶在RememberMe時
<shiro:hasAnyRoles name="abc,123" > 在有abc或者123角色時
<shiro:hasRole name="abc"> 擁有角色abc
<shiro:lacksRole name="abc"> 沒有角色abc
<shiro:hasPermission name="abc"> 擁有權(quán)限資源abc <shiro:lacksPermission name="abc"> 沒有abc權(quán)限資源
<shiro:principal> 顯示用戶身份名稱
<shiro:principal property="username"/> 顯示用戶身份中的屬性值

11. Shiro整合springboot之thymeleaf權(quán)限控制

11.1 引入依賴

<dependency>
    <groupId>com.github.theborakompanioni</groupId>
    <artifactId>thymeleaf-extras-shiro</artifactId>
    <version>2.0.0</version>
</dependency>

11.2 頁面中引入命名空間

<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"
      xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">

11.3 常見權(quán)限控制標(biāo)簽使用

<!-- 驗證當(dāng)前用戶是否為“訪客”,即未認證(包含未記?。┑挠脩簟?-->
<p shiro:guest="">Please <a href="login.html" rel="external nofollow"  rel="external nofollow"  rel="external nofollow" >login</a></p>

<!-- 認證通過或已記住的用戶。 -->
<p shiro:user="">
    Welcome back John! Not John? Click <a href="login.html" rel="external nofollow"  rel="external nofollow"  rel="external nofollow" >here</a> to login.
</p>
<!-- 已認證通過的用戶。不包含已記住的用戶,這是與user標(biāo)簽的區(qū)別所在。 -->
<p shiro:authenticated="">
    Hello, <span shiro:principal=""></span>, how are you today?
<a shiro:authenticated="" href="updateAccount.html" rel="external nofollow" >Update your contact information</a>
<!-- 輸出當(dāng)前用戶信息,通常為登錄帳號信息。 -->
<p>Hello, <shiro:principal/>, how are you today?</p>
<!-- 未認證通過用戶,與authenticated標(biāo)簽相對應(yīng)。與guest標(biāo)簽的區(qū)別是,該標(biāo)簽包含已記住用戶。 -->
<p shiro:notAuthenticated="">
    Please <a href="login.html" rel="external nofollow"  rel="external nofollow"  rel="external nofollow" >login</a> in order to update your credit card information.
<!-- 驗證當(dāng)前用戶是否屬于該角色。 -->
<a shiro:hasRole="admin" href="admin.html" rel="external nofollow" >Administer the system</a><!-- 擁有該角色 -->
<!-- 與hasRole標(biāo)簽邏輯相反,當(dāng)用戶不屬于該角色時驗證通過。 -->
<p shiro:lacksRole="developer"><!-- 沒有該角色 -->
    Sorry, you are not allowed to developer the system.
<!-- 驗證當(dāng)前用戶是否屬于以下所有角色。 -->
<p shiro:hasAllRoles="developer, 2"><!-- 角色與判斷 -->
    You are a developer and a admin.
<!-- 驗證當(dāng)前用戶是否屬于以下任意一個角色。  -->
<p shiro:hasAnyRoles="admin, vip, developer,1"><!-- 角色或判斷 -->
    You are a admin, vip, or developer.
<!--驗證當(dāng)前用戶是否擁有指定權(quán)限。  -->
<a shiro:hasPermission="userInfo:add" href="createUser.html" rel="external nofollow"  rel="external nofollow" >添加用戶</a><!-- 擁有權(quán)限 -->
<!-- 與hasPermission標(biāo)簽邏輯相反,當(dāng)前用戶沒有制定權(quán)限時,驗證通過。 -->
<p shiro:lacksPermission="userInfo:del"><!-- 沒有權(quán)限 -->
    Sorry, you are not allowed to delete user accounts.
<!-- 驗證當(dāng)前用戶是否擁有以下所有角色。 -->
<p shiro:hasAllPermissions="userInfo:view, userInfo:add"><!-- 權(quán)限與判斷 -->
    You can see or add users.
<!-- 驗證當(dāng)前用戶是否擁有以下任意一個權(quán)限。  -->
<p shiro:hasAnyPermissions="userInfo:view, userInfo:del"><!-- 權(quán)限或判斷 -->
    You can see or delete users.
<a shiro:hasPermission="pp" href="createUser.html" rel="external nofollow"  rel="external nofollow" >Create a new User</a>

11.4 加入shiro的方言配置

頁面標(biāo)簽不起作用一定要記住加入方言處理

@Bean(name = "shiroDialect")
public ShiroDialect shiroDialect(){
  return new ShiroDialect();
}

內(nèi)容參考:
B站編程不良人:https://www.bilibili.com/video/BV1uz4y197Zm 
僅用于學(xué)習(xí)!

到此這篇關(guān)于SpringBoot整合Shiro思路(最新超詳細)的文章就介紹到這了,更多相關(guān)SpringBoot整合Shiro內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • 解決 java: 程序包com.baomidou.mybatisplus.annotation不存在

    解決 java: 程序包com.baomidou.mybatisplus.annotation不存在

    在使用Java編寫程序時,經(jīng)常會遇到各種編譯錯誤或運行時異常,本文主要介紹了解決java:程序包com.baomidou.mybatisplus.annotation不存在,具有一定的參考價值,感興趣的可以了解一下
    2024-03-03
  • Java輸出打印工具類封裝的實例

    Java輸出打印工具類封裝的實例

    下面小編就為大家?guī)硪黄狫ava輸出打印工具類封裝的實例。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2017-10-10
  • Java實現(xiàn)短信驗證碼和國際短信群發(fā)功能的示例

    Java實現(xiàn)短信驗證碼和國際短信群發(fā)功能的示例

    本篇文章主要介紹了Java實現(xiàn)短信驗證碼和國際短信群發(fā)功能的示例,具有一定的參考價值,感興趣的小伙伴們可以參考一下。
    2017-02-02
  • Java中indexOf()方法詳解及其日常使用舉例

    Java中indexOf()方法詳解及其日常使用舉例

    這篇文章主要給大家介紹了關(guān)于Java中indexOf()方法詳解及其日常使用舉例的相關(guān)資料,indexOf()方法是JavaScript字符串的內(nèi)置方法之一,它用于查找給定子字符串在原始字符串中第一次出現(xiàn)的位置,需要的朋友可以參考下
    2023-12-12
  • Spring?Boot用戶注冊驗證的實現(xiàn)全過程記錄

    Spring?Boot用戶注冊驗證的實現(xiàn)全過程記錄

    最近在設(shè)計自己的博客系統(tǒng),涉及到用戶注冊與登錄驗證,所以下面這篇文章主要給大家介紹了關(guān)于Spring?Boot用戶注冊驗證的實現(xiàn)全過程,文中通過實例代碼介紹的非常詳細,需要的朋友可以參考下
    2022-01-01
  • 基于spring中的aop簡單實例講解

    基于spring中的aop簡單實例講解

    下面小編就為大家?guī)硪黄趕pring中的aop簡單實例講解。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2017-07-07
  • Java最簡潔數(shù)據(jù)結(jié)構(gòu)之冒泡排序快速理解

    Java最簡潔數(shù)據(jù)結(jié)構(gòu)之冒泡排序快速理解

    冒泡排序是編程中數(shù)據(jù)結(jié)構(gòu)繞不過的一個基礎(chǔ)點,有關(guān)于冒泡排序的文章也有很多,但可能會比較繚亂未能理解,本章將一子u為簡潔明了的例圖帶你通關(guān)冒泡排序
    2021-11-11
  • 使用JavaMail發(fā)送郵件保證成功的方法

    使用JavaMail發(fā)送郵件保證成功的方法

    JavaMail是利用現(xiàn)有的郵件賬戶發(fā)送郵件的工具,使用過JavaMail的api發(fā)送郵件的人可能會有這樣一個疑惑:我如何知道我調(diào)用該api發(fā)送的郵件是否成功呢?那么通過下面這篇文章大家一起來看看使用JavaMail保證郵件發(fā)送成功的方法,有需要的朋友們可以參考借鑒。
    2016-11-11
  • Java調(diào)用SQL腳本執(zhí)行常用的方法示例

    Java調(diào)用SQL腳本執(zhí)行常用的方法示例

    這篇文章主要給大家介紹了關(guān)于Java調(diào)用SQL腳本執(zhí)行常用的方法的相關(guān)資料,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧。
    2018-04-04
  • Java String index out of range:100錯誤解決方案詳解

    Java String index out of range:100錯誤解決方案詳解

    這篇文章主要介紹了Java String index out of range:100錯誤解決方案詳解,本篇文章通過簡要的案例,講解了該項技術(shù)的了解與使用,以下就是詳細內(nèi)容,需要的朋友可以參考下
    2021-08-08

最新評論