【WEEK13】 【DAY4】Shiro Part 4【English Version】

news2024/11/18 23:46:08

2024.5.23 Thursday
Continued from 【WEEK13】 【DAY3】Shiro Part 3【English Version】

Contents

  • 15.6. Integrate Shiro with MyBatis
    • 15.6.1. Modify pom.xml
    • 15.6.2. Create application.yaml
    • 15.6.3. Connect to the database
    • 15.6.4. Modify application.properties
    • 15.6.5. Create pojo folder and mapper folders (two places)
      • 15.6.5.1. Create User.java
      • 15.6.5.2. Create UserMapper.java
      • 15.6.5.3. Create UserMapper.xml
    • 15.6.6. Create service folder
      • 15.6.6.1. Create UserService.java
      • 15.6.6.2. Create UserServiceImpl.java
      • 15.6.6.3. Unit Test
    • 15.6.7. Connect to a real database
      • 15.6.7.1. Modify UserRealm.java
      • 15.6.7.2. Modify the User table
      • 15.6.7.3. Restart ShiroSpringbootApplication.java
      • 15.6.7.4. Currently using general encryption

15.6. Integrate Shiro with MyBatis

15.6.1. Modify pom.xml

Import 5 dependencies

<!--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>

15.6.2. Create application.yaml

Insert image description here

Use the YAML file configuration previously used, copy and paste it, and make some modifications at the end. At this point, all contents of application.properties can be commented out without affecting use.

spring:
  datasource:
    username: root
    password: 123456
    # If there is a time zone error, add a time zone configuration and connect it with other configurations using &
    # For example: serverTimezone=UTC
    url: jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
    driver-class-name: com.mysql.cj.jdbc.Driver
    type: com.alibaba.druid.pool.DruidDataSource

    # Spring Boot does not inject these attribute values by default, so you need to bind them yourself
    # Druid-specific configuration
    initialSize: 5
    minIdle: 5
    maxActive: 20
    maxWait: 60000
    timeBetweenEvictionRunsMillis: 60000
    minEvictableIdleTimeMillis: 300000
    validationQuery: SELECT 1 FROM DUAL
    testWhileIdle: true
    testOnBorrow: false
    testOnReturn: false
    poolPreparedStatements: true

    # Configure monitoring statistical interception filters: stat: statistical monitoring; log4j: log recording; wall: defense against SQL injection
    # If an error like java.lang.ClassNotFoundException: org.apache.log4j.Priority occurs
    # Import the log4j dependency, Maven address: https://mvnrepository.com/artifact/log4j/log4j
    filters: stat,wall,log4j
    maxPoolPreparedStatementPerConnectionSize: 20
    useGlobalDataSourceStat: true
    connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500

mybatis:
  # type-aliases-package: P40.pojo
  mapper-locations: classpath:mapper/*.xml
# Pay attention to the indentation of the three lines above, which directly determines whether there is an error

15.6.3. Connect to the database

A new mybatis database has been created

CREATE DATABASE `mybatis`;
USE `mybatis`;

CREATE TABLE `user`(
    `id` INT(20) NOT NULL,
    `name` VARCHAR(30) DEFAULT NULL,
    `pwd` VARCHAR(30) DEFAULT NULL,
    PRIMARY KEY(`id`)
)ENGINE=INNODB DEFAULT CHARSET=utf8;

INSERT INTO `user`(`id`,`name`,`pwd`) VALUES
(1,'zhangsan','123456'),
(2,'lisi','2345678'),
(3,'wangwu','3456789');

Insert image description here

15.6.4. Modify application.properties

spring.application.name=shiro-springboot
#mybatis.type-aliases-package=P40.pojo
mybatis.mapper-locations=classpath:mapper/*.xml

Note here!!! The aliases starting from the second line cannot be used here (it will cause an error), so it should be commented out to run successfully!

15.6.5. Create pojo folder and mapper folders (two places)

Insert image description here

15.6.5.1. Create User.java

package com.P40.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
    private int id;
    private String name;
    private String pwd;
}

15.6.5.2. Create UserMapper.java

package com.P40.mapper;

import com.P40.pojo.User;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;

@Repository
@Mapper// Whether this mapper is commented or not doesn't matter
public interface UserMapper {
    public User queryUserByName(String name);
}

15.6.5.3. Create UserMapper.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.P40.mapper.UserMapper">
    <select id="queryUserByName" parameterType="String" resultType="com.P40.pojo.User">
        SELECT * FROM mybatis.user WHERE name = #{name}
    </select>
</mapper>

Insert image description here

15.6.6. Create service folder

Insert image description here

15.6.6.1. Create UserService.java

package com.P40.service;

import com.P40.pojo.User;

public interface UserService {
    public User queryUserByName(String name);
}

15.6.6.2. Create UserServiceImpl.java

package com.P40.service;

import com.P40.mapper.UserMapper;
import com.P40.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    UserMapper userMapper;

    @Override
    public User queryUserByName(String name) {
        return userMapper.queryUserByName(name);
    }
}

15.6.6.3. Unit Test

Modify ShiroSpringbootApplicationTests.java

package com.P40;

import com.P40.service.UserServiceImpl;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
class ShiroSpringbootApplicationTests {

    @Autowired
    UserServiceImpl userService;
    @Test
    void contextLoads() {
        System.out.println(userService.queryUserByName("lisi"));
    }

}

However, the test here cannot run 【Solved】Modified the yaml configuration file and UserMapper.xml file (the key is to remove the file aliases)
Insert image description here

15.6.7. Connect to a real database

15.6.7.1. Modify UserRealm.java

package com.P40.config;

import com.P40.pojo.User;
import com.P40.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

// UserRealm is a bean
// Custom UserRealm, must inherit AuthorizingRealm method, and then implement methods (alt+insert)
public class UserRealm extends AuthorizingRealm {

    @Autowired
    UserService userService;

    // Authorization
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("do doGetAuthorizationInfo Authorization");
        return null;
    }

    // Authentication
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("do doGetAuthorizationInfo Authentication");

        // Username, password -- Data reading. The following two lines are the user data obtained by simulating connecting to the database in the early stage of programming
//        String name = "root";
//        String password = "1";

        UsernamePasswordToken userToken = (UsernamePasswordToken) authenticationToken;

//        if (!userToken.getUsername().equals(name)){
//            return null;    //Throw UnknownAccountException exception (automatically)
//        }

        // Change to connect to a real database
        User user = userService.queryUserByName(userToken.getUsername());
        if(user == null){   // This user does not exist
            return null;    // UnknownAccountException
        }

        // Password authentication, Shiro operation
//        return new SimpleAuthenticationInfo("",password,"");
        return new SimpleAuthenticationInfo("",user.getPwd(),"");
    }
}

15.6.7.2. Modify the User table

Add a new row of data
Insert image description here

15.6.7.3. Restart ShiroSpringbootApplication.java

http://localhost:8080/toLogin
Login test according to the username and password in the User table
Insert image description here

Login successful
Insert image description here

Directly change the username in the URL to root, since the password is also 123456, the login status can be maintained:
Insert image description here
If changing the username to lisi, because the password for lisi is 2345678, it shows password error and cannot log in:
Insert image description here

Trying to log in with wangwu’s account, but entering the wrong username, it shows username error and cannot log in either:
Insert image description here

15.6.7.4. Currently using general encryption

CredentialsMatcher.java
Set breakpoints in MyController.java to check the execution process
Insert image description here
Or set breakpoints in UserRealm.java
Insert image description here

At this point, the password entered by the user on the web page is not encrypted in CredentialsMatcher, so the password appears explicitly in the URL (plaintext password).
Click the green “I” in the left sidebar to expand ten encryption methods, among which the default is SimpleCredentialsMatcher.
Insert image description here
In practical use, MD5 encryption results in the same ciphertext for the same plaintext password, a more secure method is MD5 salt encryption (the username is also appended to the end of the password encrypted with MD5).

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1710394.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

集合的交集、并集和差集运算

自学python如何成为大佬(目录):https://blog.csdn.net/weixin_67859959/article/details/139049996?spm1001.2014.3001.5501 集合最常用的操作就是进行交集、并集、差集和对称差集运算。进行交集运算时使用“&”符号&#xff0c;进行并集运算时使用“&#xff5c;”符号&…

redis--哨兵

概念 哨兵(Sentinel) 是一个分布式系统&#xff0c;可以在一个架构中运行多个哨兵(sentinel) 进程&#xff0c;这些进程使用流言协议(gossip protocols)来接收关于Master主服务器是否下线的信息&#xff0c;并使用投票协议(Agreement Protocols)来决定是否执行自动故障迁移,以…

力扣:15. 三数之和

15. 三数之和 给你一个整数数组 nums &#xff0c;判断是否存在三元组 [nums[i], nums[j], nums[k]] 满足 i ! j、i ! k 且 j ! k &#xff0c;同时还满足 nums[i] nums[j] nums[k] 0 。请 你返回所有和为 0 且不重复的三元组。 注意&#xff1a;答案中不可以包含重复的三…

OpenHarmony迎来首个互联网技术统一标准,鸿蒙OS生态走向如何?

开源三年半&#xff0c;OpenHarmony(以下简称“开源鸿蒙”)迎来了新进展。在5月25日召开的「OpenHarmony开发者大会」上&#xff0c;鸿蒙官宣了开源鸿蒙设备统一互联技术标准。 一直以来&#xff0c;各行业品牌操作系统相互独立、难以协同,成为其互联互通的痛点。为进一步解决…

【官方指南】3ds Max中纹理贴图问题及正确解决方案

在使用3ds Max进行设计和制作时&#xff0c;纹理贴图是一个非常重要的环节。然而&#xff0c;许多用户在使用过程中常会遇到各种纹理贴图问题。为此&#xff0c;Autodesk官方提供了一些有效的解决方案&#xff0c;可以解决90%的纹理贴图难题。这里小编都帮大家整理好了&#xf…

剪画小程序:”霸屏各大平台“的黏土滤镜是怎么制作的呢?

最近&#xff0c;网上出现大量“黏土”风格的人物照片。尤其是在社交平台&#xff0c;这类型的分享数量急剧上升。 这是马斯克开车的样子 还有这张是周杰伦七里香的专辑图片 一张照片&#xff0c;十几秒钟&#xff0c;就能还原出你在黏土世界的样子。 以上这些照片是用-【剪画…

基于微信小程序实现的【二手物品交易平台】后端 JAVA Springboot (内附设计LW + PPT+ 源码+ 演示视频 下载)

项目名称 项目名称&#xff1a; 基于微信小程序的二手物品交易平台 项目技术栈 该项目采用了以下核心技术栈&#xff1a; 后端框架/库&#xff1a; Java, SSM框架数据库&#xff1a; MySQL前端技术&#xff1a; 微信小程序技术其他相关技术&#xff1a; HTML, MyEclipse开发…

Ant Design Vue Pro流程分析记录

一、基本介绍 Ant Design Vue Pro提供了一套完整的解决方案&#xff0c;包括路由、状态管理、UI组件库、HTTP请求封装等&#xff0c;方便开发者快速搭建和维护企业级应用。 二、官网地址 Ant Design Pro of Vue 三、下载及安装 推荐使用Yarn 四、文件分布及说明 dist&#xf…

文件上传巩固及流量分析

1.[GXYCTF2019]BabyUpload 1&#xff09;打开题目也是没有任何提示&#xff0c; 2&#xff09;进入环境&#xff0c;看到下面页面猜测是文件上传漏洞&#xff0c;下面开始传文件 3&#xff09;首先上传一句话木马 a.php&#xff0c;代码如下&#xff1a; 下面这个代码中并没有…

pinia持久化未生效

pinia官方文档 https://prazdevs.github.io/pinia-plugin-persistedstate/zh/guide/ pinia持久化未生效的原因很有可能就是在main.js中重复创建了pinia&#xff0c;导致持久化未生效

基于jeecgboot-vue3的Flowable增加表单功能(一)

因为这个项目license问题无法开源&#xff0c;更多技术支持与服务请加入我的知识星球。 1、通过online表单设计进行&#xff0c;生成代码 主要注意2点&#xff0c;1个是查询需要选择哪些字段&#xff0c;同时创建人员需要选择用户选择 这里&#xff0c;SysForm增加下面的一个注…

反射、类加载、静态代理,jdk动态代理,cglib代理

一、 反射 反射是在程序运行状态下&#xff0c;动态获取类的结构&#xff08;属性&#xff0c;构造器&#xff0c;方法&#xff0c;注解&#xff09;&#xff0c;动态的创建类对象然后调用类中的属性方法。反射的起源Class&#xff0c;Class中包含类反射要使用的API 获取Class的…

AI 前沿发展摘要

&#x1f514; AI 前沿发展摘要 1⃣️ ChatScene: 一句话生成自动驾驶关键场景 主要功能: Chat Scene 能够在CARLA仿真环境中创建多样化和复杂的场景, 有效地弥合了交通场景文本描述和CARLA实际仿真之间的鸿沟 效果: 通过使用生成的安全关键场景来微调不同的基于RL的自动驾…

艾体宝干货 | 教程:使用ntopng和nProbe监控网络流量

本教程旨在分享如何通过 ntopng 和 nProbe 这两款工具&#xff0c;深入了解和掌握网络流量监控的艺术。我们将提供从基本概念到高级应用的全面指导&#xff0c;涵盖了在多种平台和设备上的部署和配置步骤。不论您是专业人员还是技术爱好者&#xff0c;跟随本教程&#xff0c;都…

『香橙派』基于Orange Pi AIpro打造高效个人云存储解决方案

&#x1f4e3;读完这篇文章里你能收获到 了解Orange Pi AIpro硬件优势&#xff0c;为构建高效云存储基础设施的理想平台。学会使用Orange Pi AIpro硬件平台&#xff0c;搭载Ubuntu Server系统&#xff0c;打造云存储环境。掌握利用Kodbox软件&#xff0c;享受文件管理、多格式…

如何将 Langfuse 链接到自有 PostgreSQL 数据库并升级 PostgreSQL 版本

在本文中,我们将介绍如何将 Langfuse 应用程序链接到自有的 PostgreSQL 数据库,并升级 PostgreSQL 以支持 jsonb 类型。 前提条件 运行 CentOS 7 的服务器已安装的 PostgreSQL 9.2 或更低版本需要将 Langfuse 连接到自有数据库,并升级 PostgreSQL 以支持 jsonb 类型1. 将 La…

迅为RK3562开发板专为3562编写10大分类2900+页文档

iTOP-3562开发板采用瑞芯微RK3562处理器&#xff0c;内部集成了四核A53Mali G52架构&#xff0c;主频2GHZ&#xff0c;内置1TOPSNPU算力&#xff0c;RK809动态调频。支持OpenGLES1.1/2.0/3.2、0penCL2.0、Vulkan 1.1内嵌高性能2D加速硬件。 内置独立NPU, 算力达 1TOPS,可用于轻…

2024中青杯数学建模竞赛B题药物属性预测思路代码论文分享

2024年中青杯数学建模竞赛B题论文和代码已完成&#xff0c;代码为B题全部问题的代码&#xff0c;论文包括摘要、问题重述、问题分析、模型假设、符号说明、模型的建立和求解&#xff08;问题1模型的建立和求解、问题2模型的建立和求解、问题3模型的建立和求解&#xff09;、模型…

设计模式:外观模式 导诊台。空指针异常

文章目录 UML类图目录结构思路Register.javaOutpatientService.javaPrice.javaPharmacy.javaFacade.java空指针异常 Test.java UML类图 目录结构 思路 照着写&#xff0c;然后getRegister&#xff08;&#xff09;方法的具体实现就是&#xff1a;打印一句话&#xff0c;然后到…

Java集合面试题集——2024最新大厂面试

文章目录 1. 集合框架2. ArrayList和LinkedList2.1 源码分析2.2 ArrayList listnew ArrayList(10)中的list扩容几次?2.3 如何实现数组和List之间的转换2.4 ArrayList和LinkedList的区别2.5 如何保证ArrayList的线程安全&#xff1f;2.6 CopyOnWriteArrayList是如何实现线程安全…