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

2024.5.23 Thursday

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

Table of 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
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).

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

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

C++:List的使用和模拟实现

✨✨✨学习的道路很枯燥&#xff0c;希望我们能并肩走下来! 文章目录 目录 文章目录 前言 一 list的介绍及使用 1.1 list的介绍 1.2 list的使用 1.2.1 list的构造 1.2.2 list iterator的使用 1.2.3 list capacity 1.2.4 list element access 1.2.5 list modifiers …

智能家居6 -- 配置 ini文件优化设备添加

不知道什么是ini的朋友可以先看这篇:一文带你入门ini格式-CSDN博客 准备 如下图: 在src 下面添加 ini.c 在inc 下面添加 ini.h 在 receive_interface.c 里面包含头文件&#xff0c;把之前添加的设备类注释掉 这时候就可以把相关设备的(.c .h)文件给删掉了 如下图: 修改/添…

2024上海初中生古诗文大会倒计时4个月:单选题真题解析(持续)

现在距离2024年初中生古诗文大会还有4个多月时间&#xff0c;我们继续来看10道选择题真题和详细解析&#xff0c;以下题目截取自我独家制作的在线真题集&#xff0c;都是来自于历届真题&#xff0c;去重、合并后&#xff0c;每道题都有参考答案和解析。 为帮助孩子自测和练习&…

isscc2024 short course4 In-memory Computing Architectures

新兴的ML加速器方法&#xff1a;内存计算架构 1. 概述 内存计算&#xff08;In-memory Computing&#xff09;架构是一种新兴的机器学习加速器方法&#xff0c;通过将计算能力集成到存储器中&#xff0c;以减少数据移动的延迟和能耗&#xff0c;从而提高计算效率和性能。这种方…

PY32F003+RTL8710(AT) 实现获取天气情况

一、RTL8710主要AT指令 1、ATSR&#xff1a;模块重启 2、ATSE1&#xff1a;开启回显 3、ATPW1&#xff1a;station模式 4、ATPNssid,password,,&#xff1a;连接到AP 5、ATPK1&#xff1a;设置自动接收 6、ATPC0,v1.yiketianqi.com,80&#xff1a;与网站建立TCP连接 7、ATPT125…

Redis(1)-Jedis连接配置

问题 阿里云安装并启用Redis后&#xff0c;尝试在本地用Jedis调用&#xff0c;发现报错 public class Jedis01 {Testpublic void connect(){Jedis jedis new Jedis("101.37.31.211", 6379); // 公网ipjedis.auth("123"); // 密码String ping jedis.pin…

Offline RL : Context-Former: Stitching via Latent Conditioned Sequence Modeling

paper 基于HIM的离线RL算法&#xff0c;解决基于序列模型的离线强化学习算法缺乏对序列拼接能力。 Intro 文章提出了ContextFormer&#xff0c;旨在解决决策变换器&#xff08;Decision Transformer, DT&#xff09;在轨迹拼接&#xff08;stitching&#xff09;能力上的不足…

【控制实践——二轮平衡车】【三】基于PID的直立控制

传送门 系列博客前言直立运动分析基于PID控制器的直立控制角度环控制角速度控制总结 电机转速的控制前言电机转速控制 结语 系列博客 【控制实践——二轮平衡车】【一】运动分析及动力学建模 【控制实践——二轮平衡车】【二】实物设计和开源结构&代码 【控制实践——二轮…

题目----力扣--回文链表

题目 给你一个单链表的头节点 head &#xff0c;请你判断该链表是否为 回文链表 。如果是&#xff0c;返回 true &#xff1b;否则&#xff0c;返回 false 。 示例 1&#xff1a; 输入&#xff1a;head [1,2,2,1] 输出&#xff1a;true示例 2&#xff1a; 输入&#xff1a;…

Vue3实战笔记(42)—Vue + ECharts:流量数据可视化的强大组合

文章目录 前言vue3使用echarts标准demo&#xff1a;总结 前言 在前端开发中&#xff0c;数据可视化已经成为了一个不可或缺的部分。Vue.js作为一个轻量级且易于上手的渐进式JavaScript框架&#xff0c;与ECharts这个强大的数据可视化库的结合&#xff0c;使得在Vue应用中构建交…

叶面积指数(LAI)数据、NPP数据、GPP数据、植被覆盖度数据获取

引言 多种卫星遥感数据反演叶面积指数&#xff08;LAI&#xff09;产品是地理遥感生态网推出的生态环境类数据产品之一。产品包括2000-2009年逐8天数据&#xff0c;值域是-100-689之间&#xff0c;数据类型为32bit整型。该产品经过遥感数据获取、计算归一化植被指数、解译植被类…

几个速度比较快的 Linux 开源镜像站及支持的资源列表

搜狐开源镜像站 https://mirrors.sohu.com/ File Name CPAN/ FreeBSD/ QpenBSD/ RockyL apache/ archlinux/ centos/ ceph/ cygwin/ debian/ debian–cd/ debian-security/ deepin/ deepin-cd/ docker-ce/ fedora/ fedora-epel/ gentoo/ lib/ mysql/ nginx/ opensuse/ php/ ubu…

房地产支持政策加码不断,美克家居全力变革未来可期

2023年我国经济处于恢复发展阶段&#xff0c;而家具制造业“回温”速度明显慢于经济增速&#xff0c;在这一背景下&#xff0c;美克家居如此营收表现并不令人感到意外。而在充沛现金流支撑下&#xff0c;辅以全方位开展降本增效的年度经营规划&#xff0c;公司亏损收窄或已为期…

Doris集群安装部署

Doris集群安装部署 一、环境搭建 1、环境准备 主机名IP角色doris1192.168.100.131Frotend,Backenddoris2192.168.100.132Backenddoris3192.168.100.133Backend 2、Doris整体架构 Frontend&#xff08;FE&#xff09; 主要负责用户请求的接入、查询解析规划、元数据的管理…

插件:NGUI

一、版本 安装完毕后重启一下即可&#xff0c;否则可能创建的UI元素不生效 二、使用 Label文字 1、创建Canvs 2、只有根节点的这些脚本全部展开才能鼠标右键创建UI元素 3、选择字体 Sprite图片 1、选择图集 2、选择图集中的精灵 Panel容器 用来装UI的容器&#xff0c;一般UI…

汇编:加减乘除指令

加法指令 (ADD) ADD指令用于将两个操作数相加&#xff0c;结果存储在第一个操作数中。 语法&#xff1a; ADD destination, source 示例&#xff1a; assume cs:code ​ code segmentmov ax,3mov bx,2add ax,bx //相加&#xff0c;结果会放在ax中mov ax,4c00hint 21h co…

Training-Free Consistent Text-to-Image Generation # 论文阅读

URL https://arxiv.org/pdf/2402.03286 TL;DR 2024 年 2 月 nvidia 的文章。提出了一种不需要任何额外训练的主体保持方法&#xff0c;可以一次生成的 batch 中&#xff0c;通过多个 prompt 生成对应的多张图片&#xff0c;这些图片都可以拥有一个主体。 本文提出的方法通过…

怎么判断同步时序逻辑电路和异步时序逻辑电路?

&#x1f3c6;本文收录于「Bug调优」专栏&#xff0c;主要记录项目实战过程中的Bug之前因后果及提供真实有效的解决方案&#xff0c;希望能够助你一臂之力&#xff0c;帮你早日登顶实现财富自由&#x1f680;&#xff1b;同时&#xff0c;欢迎大家关注&&收藏&&…

基于Python卷积神经网络的Mnist手写数字识别

欢迎大家点赞、收藏、关注、评论啦 &#xff0c;由于篇幅有限&#xff0c;只展示了部分核心代码。 文章目录 一项目简介 二、功能三、系统四. 总结 一项目简介 一、项目背景与意义 手写数字识别是机器学习和计算机视觉领域中的一个经典问题。Mnist数据集是一个包含大量手写数…