首页 > 其他分享 >【WEEK14】 【DAY2】Shiro Part 7【English Version】

【WEEK14】 【DAY2】Shiro Part 7【English Version】

时间:2024-05-30 14:57:52浏览次数:15  
标签:Version 15.8 boot DAY2 Part user spring org shiro

2024.5.28 Tuesday
Continuation from previous 【WEEK14】 【DAY1】Shiro Part 6【English Version】

Contents

15.8. Integrate Shiro with Thymeleaf

15.8.1. Modify pom.xml to Add Dependencies

15.8.1.1. Importing the shiro-thymeleaf Integration Package

Official Website: Maven Repository: com.github.theborakompanioni » thymeleaf-extras-shiro (mvnrepository.com)
Insertion of Dependency

<!-- https://mvnrepository.com/artifact/com.github.theborakompanioni/thymeleaf-extras-shiro -->
<dependency>
    <groupId>com.github.theborakompanioni</groupId>
    <artifactId>thymeleaf-extras-shiro</artifactId>
    <version>2.0.0</version>
</dependency>

15.8.1.2. Current Complete pom.xml File

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.7.13</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>shiro-springboot</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>shiro-springboot</name>
    <description>shiro-springboot</description>
    <properties>
        <java.version>8</java.version>
    </properties>
    <dependencies>
        <!--
        Subject 用户
        SecurityManager 管理所有用户
        Realm   连接数据
        -->
        <!--shiro_thymeleaf Integration-->
        <!-- https://mvnrepository.com/artifact/com.github.theborakompanioni/thymeleaf-extras-shiro -->
        <dependency>
            <groupId>com.github.theborakompanioni</groupId>
            <artifactId>thymeleaf-extras-shiro</artifactId>
            <version>2.0.0</version>
        </dependency>

        <!--mysql-->
        <dependency>
            <groupId>com.mysql</groupId>
            <artifactId>mysql-connector-j</artifactId>
        </dependency>
        <!--log4j-->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
        <!--druid-->
        <!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.21</version>
        </dependency>
        <!--mybatis-->
        <!-- https://mvnrepository.com/artifact/org.mybatis.spring.boot/mybatis-spring-boot-starter -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.2.2</version>
        </dependency>
        <!--lombok-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.16.20</version>
        </dependency>

        <!--shiro Integration with Spring packages-->
        <!-- https://mvnrepository.com/artifact/org.apache.shiro/shiro-spring -->
        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-spring</artifactId>
            <version>1.4.1</version>
        </dependency>

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

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

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

15.8.2. Modify ShiroConfig.java

package com.P40.config;

import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;

@Configuration
public class ShiroConfig {
    //ShiroFilterFactoryBean
    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("securityManager") DefaultWebSecurityManager defaultWebSecurityManager){
        ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
        //What to configure: click to see the source code of ShiroFilterFactoryBean
        //Set security manager
        bean.setSecurityManager(defaultWebSecurityManager);

        //Add Shiro's built-in filters
        /*
        anon: Accessible without authentication
        authc: Requires authentication to access
        user: Must have 'remember me' feature enabled
        perms: Must have permission for a specific resource to access
        role: Must have permission for a specific role
         */
        //Login interception
        Map<String,String> filterMap = new LinkedHashMap<>();

        //Authorization. Normally, it should redirect to an unauthorized page, but at this point, due to only adding the following verifications, it directly jumps to the 401 page.
        filterMap.put("/user/add","perms[user:add]");
        filterMap.put("/user/update","perms[user:update]");

//        filterMap.put("/user/add","authc");
//        filterMap.put("/user/update","authc");
        //After modifying the access permissions of the add and update pages only here, restart the project, and clicking add or update will be intercepted, displaying a 404 error, hoping to redirect to the login page
        filterMap.put("/user/*","authc");   //Wildcards can also be used here (instead of /user/add and /user/update from the above two lines)
        bean.setFilterChainDefinitionMap(filterMap);

        //Redirect to login page if not authenticated
        bean.setLoginUrl("/toLogin");   //Set the login request

        //Unauthorized page
        bean.setUnauthorizedUrl("/noauth");

        return bean;
    }

    //DefaultWebSecurityManager
    @Bean(name = "securityManager") //Alias this class to facilitate calls by ShiroFilterFactoryBean
    public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm){    //Get UserRealm, but it seems that annotations are not needed here, it can be called directly
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        //The default class name of DefaultWebSecurityManager is defaultWebSecurityManager, just changed to securityManager here

        //Associate UserRealm
        securityManager.setRealm(userRealm);
        return securityManager;
    }

    //Create realm object, need to customize the class
    @Bean
    public UserRealm userRealm(){
        return new UserRealm();
    }

    //Creation order is reversed (from real->DefaultWebSecurityManager->ShiroFilterFactoryBean)

    //Integrate ShiroDialect (dialect): Used to integrate Shiro and Thymeleaf
    @Bean
    public ShiroDialect getShiroDialect(){
        return new ShiroDialect();
    }
}

15.8.3. Modify index.html

<!DOCTYPE html>
<html lang="en" xmlns:shiro="http://www.thymeleaf.org/thymeleaf-extras-shiro">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>Homepage</h1>

<!--Display "Login" entry only when not logged in-->
<div shiro:notAuthenticated>
    <a th:href="@{/toLogin}">Login</a>
</div>

<p th:text="${msg}"></p>
<hr>    <!--Create a horizontal line in the HTML page-->

<!--Display the functionality entry on the page only when the user has corresponding permissions in the database-->
<div shiro:hasPermission="user:add">
    <a th:href="@{/user/add}">add</a>
</div>
<div shiro:hasPermission="user:update">
    <a th:href="@{/user/update}">update</a>
</div>
<!--a tag defines a hyperlink, used to link from one page to another-->

<!--Display "Sign out" entry only when logged in-->
<hr>
<div shiro:Authenticated>
    <a class="nav-link" th:href="@{/logout}" onclick="alert('Logged out')">Sign out</a><!--Make sure not to misspell href as herf-->
</div>

</body>
</html>

15.8.4. Open all permissions for the root user (just for experimentation)

Insert Image Description Here

15.8.5. Modify MyController.java

Only the logout method is modified.

//Logout
@RequestMapping("/logout")
public String logout(){
    Subject currentUser = SecurityUtils.getSubject();
    currentUser.logout();
    return "/index";    //Modified to: Redirect to the homepage after logout
}

15.8.6. Restart

15.8.6.1. When no user is logged in

Insert Image Description Here

15.8.6.2. Click on Login

Only display the functionalities that the logged-in user has permission to access on the homepage
Insert Image Description Here
Insert Image Description Here
Insert Image Description Here
Insert Image Description Here

15.8.6.3. Click on Sign out

Changed to return to the main page (directly redirected to the login page when requesting authorization)
Insert Image Description Here
Insert Image Description Here

标签:Version,15.8,boot,DAY2,Part,user,spring,org,shiro
From: https://blog.csdn.net/2401_83329143/article/details/139250430

相关文章

  • Particles.js:为Web项目增添动态粒子效果
    Particles.js:为Web项目增添动态粒子效果示例介绍Particles.js是一个轻量级的JavaScript库,用于在Web页面上创建和管理动态粒子效果。它允许开发者通过简单的配置文件实现复杂的动画效果,为网页增添视觉吸引力。粒子可以是点、线、图像等,能够根据用户交互进行动态变化,Particles.......
  • 59天【代码随想录算法训练营34期】第十章 单调栈part02( ● 503.下一个更大元素II ●
    503.下一个更大元素IIclassSolution:defnextGreaterElements(self,nums:List[int])->List[int]:dp=[-1]*len(nums)stack=[]foriinrange(len(nums)*2):while(len(stack)!=0andnums[i%len(nums)]>nums[stack[-1......
  • [CEOI2010 day2] pin
    [CEOI2010day2]pin题目信息题目链接LuoguP6521题目描述给定\(n\)个长度为\(4\)的字符串,你需要找出有多少对字符串满足恰好\(D\)个对应位置的字符不同。输入格式输入第一行两个整数\(n,D\)。接下来的\(n\)行,每行一个长度为\(4\)的字符串。输出格式输出一行......
  • 【Java】 如何解决Java中的UnsupportedClassVersionError错误
    >>【痕迹】QQ+微信朋友圈和聊天记录分析工具>>(1)纯Python语言实现,使用Flask后端,本地分析,不上传个人数据。>>(2)内含QQ、微信聊天记录保存到本地的方法,真正实现自己数据自己管理。>>(3)数据可视化分析QQ、微信聊天记录,提取某一天的聊天记录与大模型对话。>>**下载......
  • 代码随想录算法训练Day20|LeetCode654-最大二叉树、LeetCode617-合并二叉树、LeetCode
    最大二叉树题目描述力扣654-最大二叉树给定一个不重复的整数数组nums。最大二叉树可以用下面的算法从nums递归地构建:创建一个根节点,其值为nums中的最大值。递归地在最大值左边的子数组前缀上构建左子树。递归地在最大值右边的子数组后缀上构建右子树。......
  • 1、时间函数-DATEPART
    时间函数-DATEPART1、语法selectdatepart(datepart,date)datepart:所需要的输出的时间格式,如year、month、day、hour等。date:所要查询的时间字段(cloumn)。2、案例获取年份SELECTDATEPART(year,GETDATE())ASCurrentYear;获取月份SELECTDATEPART(month,GETDATE(......
  • 算法训练 | 二叉树Part3 | 104.二叉树的最大深度、111.二叉树的最小深度、222.完全二
    目录104.二叉树的最大深度递归法⭐迭代法111.二叉树的最小深度递归法⭐迭代法222.完全二叉树的节点个数普通二叉树完全二叉树嵌入式学习分享个人主页:Orion嵌入式随想录-小红书(xiaohongshu.com)104.二叉树的最大深度题目链接:104.二叉树的最大深度-力扣(Le......
  • 算法训练 | 二叉树Part4 | 10.平衡二叉树、257.二叉树的所有路径、404.左叶子之和
    目录110.平衡二叉树递归法迭代法257.二叉树的所有路径递归法迭代法404.左叶子之和递归法迭代法110.平衡二叉树题目链接:leetcode.cn文章讲解:代码随想录递归法解题思路高度平衡二叉树定义为:一个二叉树每个节点的左右两个子树的高度差的绝对值不超过1。要求......
  • 算法训练 | 二叉树Part2 | 层序遍历、226.翻转二叉树、101.对称二叉树
    目录广度优先226.翻转二叉树递归法⭐迭代法层序法101.对称二叉树后序遍历法⭐迭代法嵌入式学习分享个人主页:Orion嵌入式随想录-小红书(xiaohongshu.com)广度优先解题思路层序遍历一个二叉树。就是从左到右一层一层的去遍历二叉树。需要借用一个辅助数据......
  • 57天【代码随想录算法训练营34期】第十章 单调栈part01
    739.每日温度单调栈指的是只增加或只减少的stack,相当于一个memoclassSolution:defdailyTemperatures(self,temperatures:List[int])->List[int]:answer=[0]*len(temperatures)stack=[0]foriinrange(1,len(temperatures)):......