Spring Security 6.1.x 系列 (1)—— 初识Spring Security

news2024/9/9 0:22:30

一、 Spring Security 概述

Spring SecuritySpring组织提供的一个开源安全框架,基于Spring开发,所以非常适合在Spring Boot中使用。

官方文档地址:https://docs.spring.io/spring-security/reference/index.html

GitHub地址:https://github.com/spring-projects/spring-security

目前最新的版本是6.1.4,提供了许多新功能,需使用JDK 17及以上版本。

Spring Security作为一个功能完善的安全框架,具有以下特性:

  • 认证(Authentication):解决 “你是谁” 的问题,验证系统中是否有这个“用户”(用户/设备/系统),也就是我们常说的“登录”。
  • 授权(Authorization):权限控制/鉴别,解决的是系统中某个用户能够访问哪些资源,即“你能干什么”的问题。Spring Security 支持基于 URL 的请求授权、方法访问授权、对象访问授权。
  • 加密:对重要信息进行加密处理,如对密码进行加密、匹配等。
  • 会话管理:对用户认证、会话信息进行存储管理。
  • RememberMe: 实现“记住我”功能,并可以实现token令牌持久化。
  • 抵御攻击:对常见的网络攻击进行防御。

二、入门示例搭建

2.1 层级结构

.
├── springboot3-cloud-example
│   ├── spring-security
│   │   ├── hello-security
│   │   │   ├── src
│   │   │   └── pom.xml      
│   │   └── pom.xml  
|   └── pom.xml
  • springboot3-cloud-example:顶级项目
  • spring-security:父级项目起到目录划分作用
  • hello-securitySpring Security入门示例

2.2 顶级项目完整pom依赖

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

    <groupId>com.gm</groupId>
    <artifactId>springboot3-cloud-example</artifactId>
    <name>springboot3-cloud-example</name>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>pom</packaging>
    <description>SpringBoot3-Cloud进阶实战示例</description>

    <!--各版本对应关系 https://github.com/alibaba/spring-cloud-alibaba/wiki/%E7%89%88%E6%9C%AC%E8%AF%B4%E6%98%8E -->
    <properties>
        <spring-boot.version>3.1.4</spring-boot.version>
        <spring-cloud.version>2022.0.0</spring-cloud.version>
        <spring-cloud-alibaba.version>2022.0.0.0</spring-cloud-alibaba.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>17</maven.compiler.source>
        <maven.compiler.target>17</maven.compiler.target>
    </properties>

    <modules>
        <module>spring-security</module>
    </modules>

    <dependencies>
        <!--Lombok-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <dependencyManagement>
        <dependencies>
            <!-- spring boot 依赖 -->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-dependencies</artifactId>
                <version>${spring-boot.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>

            <!-- spring cloud 依赖 -->
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring-cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <!-- spring cloud alibaba 依赖 -->
            <dependency>
                <groupId>com.alibaba.cloud</groupId>
                <artifactId>spring-cloud-alibaba-dependencies</artifactId>
                <version>${spring-cloud-alibaba.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>

        </dependencies>
    </dependencyManagement>

    <build>
        <finalName>${project.name}</finalName>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <filtering>true</filtering>
            </resource>
        </resources>
        <pluginManagement>
            <plugins>
                <plugin>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-maven-plugin</artifactId>
                    <version>${spring-boot.version}</version>
                    <configuration>
                        <finalName>${project.build.finalName}</finalName>
                        <layers>
                            <enabled>true</enabled>
                        </layers>
                    </configuration>
                    <executions>
                        <execution>
                            <goals>
                                <goal>repackage</goal>
                            </goals>
                        </execution>
                    </executions>
                </plugin>
            </plugins>
        </pluginManagement>
    </build>

    <profiles>
        <profile>
            <id>dev</id>
            <properties>
                <!-- 环境标识,需要与配置文件的名称相对应 -->
                <profile.active>dev</profile.active>
                <nacos.username>nacos</nacos.username>
                <nacos.password>nacos</nacos.password>
            </properties>
            <activation>
                <!-- 默认环境 -->
                <activeByDefault>true</activeByDefault>
            </activation>
        </profile>
        <profile>
            <id>test</id>
            <properties>
                <!-- 环境标识,需要与配置文件的名称相对应 -->
                <profile.active>test</profile.active>
                <nacos.username>nacos</nacos.username>
                <nacos.password>nacos</nacos.password>
            </properties>
        </profile>
    </profiles>
</project>

2.3 父级项目完整pom依赖

<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<parent>
		<artifactId>springboot3-cloud-example</artifactId>
		<groupId>com.gm</groupId>
		<version>0.0.1-SNAPSHOT</version>
	</parent>
	<modelVersion>4.0.0</modelVersion>
	<packaging>pom</packaging>

	<artifactId>spring-security</artifactId>
	<modules>
		<module>hello-security</module>
    </modules>
</project>

2.4 入门示例

2.4.1 完整pom依赖

<?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>
        <artifactId>spring-security</artifactId>
        <groupId>com.gm</groupId>
        <version>0.0.1-SNAPSHOT</version>
    </parent>

    <artifactId>hello-security</artifactId>
    <packaging>jar</packaging>
    <description>入门示例</description>

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

spring-boot-starter-securitySpring Boot官方提供的启动器,提供了自动配置和依赖包管理功能,主要包含以下几个子模块:

  • spring-security-core: 核心包,包含核心认证和访问权限功能类和接口、远程支持和基本配置
  • spring-security-webWeb框架集成包,包含过滤器和相关的安全基础设施代码
  • spring-security-config:包含security命名空间解析代码和Java配置代码

2.4.2 创建访问接口

接下来我们随便编写一个web访问接口,方便后面进行测试。

package com.gm.security.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {

    @GetMapping("/hello")
    public String hello() {
        return "hello spring security";
    }
}

2.4.3 创建项目入口

package com.gm.security;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class HelloSecurityApplication {

    public static void main(String[] args) {
        SpringApplication.run(HelloSecurityApplication.class, args);
    }
}

2.4.4 运行项目

我们把项目启动起来后,在浏览器中对/hello进行访问,会发现/hello是无法直接访问的。在访问/hello之前会自动跳转到/login地址,进入到一个登录界面。这是因为Spring Boot中"约定大约配置"的规则,只要我们添加了Spring Security的依赖包,就会自动开启安全限制,在访问Web接口之前会进行安全拦截。只有输入了用户名和密码,才能访问项目中的Web接口,上述过程如下图所示:

在这里插入图片描述

此时登录界面中,要求我们输入用户名和密码。这个默认的用户名是user,密码是一个用UUID生成的随机字符串。在每次启动项目时,都可以在控制台中看到生成的随机密码,如下图所示:

在这里插入图片描述

2.4.5 随机密码生成机制

能有小伙伴会很好奇,这个随机的密码到底是在哪里生成的呢?

让我们分析一下Spring Security的源码,来看看这个密码的生成策略。这个默认的用户名和密码其实是在SecurityProperties类中定义的,源码如下图:

在这里插入图片描述

而控制台上打印的密码日志,是在UserDetailsServiceAutoConfiguration类的getOrDeducePassword方法中输出的。

我们只要把这个随机密码,复制粘贴到登录页面的密码框中,就可以访问/hello接口了。

在这里插入图片描述

2.5 配置Spring Security账户密码

从上面的源码分析可知,默认的登录密码是利用UUID生成的随机字符串,很明显如果我们使用这个字符串作为登录密码,就太麻烦了。那么有没有更方便的登录账户呢?

Spring Security框架允许我们自己配置用户名和密码,并且提供了2种方式来进行自定义用户名和密码:

  • 在配置文件中定义
  • 在配置类中定义

2.5.1 在配置文件中定义

application.yml配置文件新增以下内容:

spring:
  security:
    user:
      name: admin
      password: 123456

2.5.2 在配置类中定义

新建配置类SecurityConfig,新增以下内容:

package com.gm.security.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;

@Configuration
@EnableWebSecurity(debug = true)
public class SecurityConfig {

    @Bean
    public UserDetailsService userDetailsService() {
        UserDetails user = User.withDefaultPasswordEncoder()
                .username("admin").password("123456").roles("USER").build();
        return new InMemoryUserDetailsManager(new UserDetails[]{user});
    }
}

2.5.3 重启项目

实现以上2种方式的任何一种,我们重启项目,这时候利用我们自己配置的用户名和密码,就可以访问/hello接口了。

在后续章节中会对以上2种实现方式进行具体源码分析。

在这里插入图片描述

至此我们入门案例搭建完毕。我们只需要添加一个Spring Security依赖包,就可以实现Web安全控制。

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

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

相关文章

抖音小店怎么运营?运营全流程,不懂的快来看!

我是电商珠珠 抖音小店是抖音旗下的电商平台&#xff0c;对于抖音来说流量是充足的&#xff0c;所以很多人想要在抖音小店上下功夫。 但是关于抖音小店的流程很多人还不太熟悉&#xff0c;今天我就来给大家详细的讲一下。 一、入驻准备 在入驻的时候&#xff0c;需要办理一…

lv7 嵌入式开发-网络编程开发 09 UDP通信

目录 1 用到的相关API 1.1 write/read到send/recv 1.2 sendto与recvfrom 2 UDP通信的实现过程 3 服务端代码、客户端、makefile代码实现 1 用到的相关API 1.1 write/read到send/recv send函数原型&#xff1a; ssize_t send(int sockfd, const void *buf, size_t len, …

Ubuntu MySQL

在安装前&#xff0c;首先看你之前是否安装过&#xff0c;如果安装过&#xff0c;但是没成功&#xff0c;就要先卸载。 一、卸载 1.查看安装 dpkg --list | grep mysql 有东西&#xff0c;就说明您之前安装过mysql。 2.卸载 先停掉server sudo systemctl stop mysql.servic…

基于回溯搜索优化的BP神经网络(分类应用) - 附代码

基于回溯搜索优化的BP神经网络&#xff08;分类应用&#xff09; - 附代码 文章目录 基于回溯搜索优化的BP神经网络&#xff08;分类应用&#xff09; - 附代码1.鸢尾花iris数据介绍2.数据集整理3.回溯搜索优化BP神经网络3.1 BP神经网络参数设置3.2 回溯搜索算法应用 4.测试结果…

基于Java的飞机航班订票购票管理系统设计与实现(源码+lw+部署文档+讲解等)

文章目录 前言具体实现截图论文参考详细视频演示为什么选择我自己的网站自己的小程序&#xff08;小蔡coding&#xff09;有保障的售后福利 代码参考源码获取 前言 &#x1f497;博主介绍&#xff1a;✌全网粉丝10W,CSDN特邀作者、博客专家、CSDN新星计划导师、全栈领域优质创作…

使用appscan定时批量扫描方法

文章目录 一、批量扫描设置二、定时扫描设置 一、批量扫描设置 appscan的窗口模式中允许用户一次只能选择一个扫描目标&#xff0c;但是如果想批量扫描多个网站的时候可以通过appscan安装文件夹下的AppScanCMD.exe工具来操作&#xff0c;具体操作如下。 首先按常规操作添加2个…

2.2.2搭建交叉编译器

1 交叉编译器 交叉编译的存在,有2个原因,1个是不同的平台,架构不同,使用的指令集不同,ARM和MIPS的CPU无法运行X86指令休编码的程序,1个是一般arm平台上的存储/性能有限,无法提供一个可靠的编译环境。所以就出现了在x86上编译,在arm上运行的镜像,即交叉编译。在交叉编…

git 同时配置 gitee github

git 同时配置 gitee github 1、 删除C:\Users\dell\.ssh目录。 在任意目录右击——》Git Bash Here&#xff0c;打开Git Bash窗口&#xff0c;下方命令在Git Bash窗口输入。 2、添加git全局范围的用户名和邮箱 git config --global user.email "609612189qq.com" …

【Spring篇】简述IoC入门案例,DI入门案例

&#x1f38a;专栏【Spring】 &#x1f354;喜欢的诗句&#xff1a;天行健&#xff0c;君子以自强不息。 &#x1f386;音乐分享【如愿】 &#x1f384;欢迎并且感谢大家指出小吉的问题&#x1f970; 文章目录 &#x1f384;Spring Framework系统架构&#x1f386;Spring核心概…

C10K问题:高并发模型设计

一、循环服务器模型 #include <stdio.h> #include <stdlib.h> #include <string.h> #include <errno.h> #include <unistd.h> #include <signal.h> #include <sys/types.h> #include <sys/socket.h> //*******// #include &l…

DeckGL MVTLayer+Mapbox注入shader实现简单效果

1.数据获取与处理 可以从OSM下载相应的带高度的矢量建筑物轮廓数据&#xff0c;下载后进行数据处理&#xff0c;保留高度字段&#xff0c;其他字段根据需求选择&#xff08;比如说想实现选中建筑物弹出相应建筑物的信息&#xff0c;就把这些信息字段保留下来&#xff09;&…

腾讯云2023年双十一优惠活动整理

随着双十一的到来&#xff0c;各大电商平台纷纷推出优惠活动。作为国内领先的云计算服务提供商&#xff0c;腾讯云自然也不会错过。以下是对腾讯云2023年双十一优惠活动的整理&#xff0c;希望能够帮助大家轻松上云&#xff01; 一、腾讯云双十一活动入口 直达腾讯云双十一活动…

使用Pytorch从零实现Vision Transformer

在这篇文章中,我们将基于Pytorch框架从头实现Vision Transformer模型,并附录完整代码。 Vision Transformer(ViT)是一种基于Transformer架构的深度学习模型,用于处理计算机视觉任务。它将图像分割成小的图像块(patches),然后使用Transformer编码器来处理这些图像块。V…

基于Java的剧本杀预约系统设计与实现(源码+lw+部署文档+讲解等)

文章目录 前言具体实现截图论文参考详细视频演示为什么选择我自己的网站自己的小程序&#xff08;小蔡coding&#xff09;有保障的售后福利 代码参考源码获取 前言 &#x1f497;博主介绍&#xff1a;✌全网粉丝10W,CSDN特邀作者、博客专家、CSDN新星计划导师、全栈领域优质创作…

2023年CSP-J真题详解+分析数据

目录 亲身体验 江苏卷 选择题 阅读程序题 阅读程序(1&#xff09; 判断题 单选题 阅读程序(2) 判断题 单选题 阅读程序(3) 判断题 单选题 完善程序题 完善程序(1) 完善程序(2) 2023CSP-J江苏卷详解 小结 亲身体验 2023年的CSP-J是在9月16日9:30--11:30进行…

x64内核实验3-页机制的研究(1)

x64内核实验3-页机制的研究&#xff08;1&#xff09; CR4寄存器 在白皮书的第三卷2.5章对控制寄存器有详细的介绍&#xff0c;下面是白皮书中CR寄存器的结构图&#xff08;这里要说明一下cr4的第12位是由被使用的这个位在2.5章的后半部分有介绍是控制是否开启5级分页的位否则…

[Spring] Spring5——JdbcTemplate 简介

目录 一、JdbcTemplate 概述 1、什么是 JdbcTemplate 2、准备运行环境 二、添加功能 1、示例 三、修改和删除功能 1、示例 四、查询功能 1、查询记录数 2、查询返回 bean 对象 3、查询返回集合 4、测试 五、批量增删改功能 1、批量添加 2、批量修改 3、批量删除…

Context应用上下文理解

文章目录 一、Context相关类的继承关系Context类ContextIml.java类ContextWrapper类ContextThemeWrapper类 二、 什么时候创建Context实例创建Context实例的时机 小结 Context类 &#xff0c;说它熟悉&#xff0c;是应为我们在开发中时刻的在与它打交道&#xff0c;例如&#x…

全方位介绍工厂的MES质量检验管理系统

一、MES质量检验管理系统的定义&#xff1a; MES质量检验管理系统是基于制造执行系统的框架和功能&#xff0c;专注于产品质量的控制和管理。它通过整合和优化质量检验流程&#xff0c;提供实时的数据采集、分析和反馈&#xff0c;帮助工厂实现高效的质量管理。该系统涵盖了从…

解决高分屏DPI缩放PC端百度网盘界面模糊的问题

第一步 更新最新版本 首先&#xff0c;在百度网盘官网下载最新安装包&#xff1a; https://pan.baidu.com/download 进行覆盖安装 第二步 修改兼容性设置 右键百度网盘图标&#xff0c;点击属性&#xff0c;在兼容性选项卡中点击更改所有用户的设置 弹出的选项卡中选择更改高…