Spring Boot中的安全配置与实现
Spring Boot中的安全配置与实现
大家好,我是免费搭建查券返利机器人省钱赚佣金就用微赚淘客系统3.0的小编,也是冬天不穿秋裤,天冷也要风度的程序猿!今天我们将深入探讨Spring Boot中的安全配置与实现,看看如何保护你的应用免受潜在的安全威胁。
一、Spring Boot中的安全框架简介
Spring Boot集成了Spring Security,这是一个强大的认证和授权框架,用于保护基于Spring的应用程序。Spring Security提供了许多功能,如基于角色的访问控制、表单登录、HTTP Basic认证、OAuth 2.0支持等。
1. Maven依赖
首先,确保在pom.xml文件中添加Spring Security的依赖:
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-security</artifactId>
</dependency>
二、基本的安全配置
1. 创建安全配置类
创建一个继承自WebSecurityConfigurerAdapter的配置类,用于定义安全策略。
package cn.juwatech.springboot.config;import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {@Overrideprotected void configure(AuthenticationManagerBuilder auth) throws Exception {auth.inMemoryAuthentication().withUser("user").password(passwordEncoder().encode("password")).roles("USER").and().withUser("admin").password(passwordEncoder().encode("admin")).roles("ADMIN");}@Overrideprotected void configure(HttpSecurity http) throws Exception {http.authorizeRequests().antMatchers("/admin/**").hasRole("ADMIN").antMatchers("/user/**").hasRole("USER").anyRequest().authenticated().and().formLogin().loginPage("/login").permitAll().and().logout().permitAll();}@Beanpublic PasswordEncoder passwordEncoder() {return new BCryptPasswordEncoder();}
}
2. 配置登录页面
创建一个简单的登录页面login.html,放置在src/main/resources/templates目录下:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head><title>Login</title>
</head>
<body><div><h2>Login</h2><form th:action="@{/login}" method="post"><div><label>Username: <input type="text" name="username"></label></div><div><label>Password: <input type="password" name="password"></label></div><div><input type="submit" value="Sign in"></div></form></div>
</body>
</html>
三、基于注解的安全控制
Spring Security支持基于注解的安全控制,使用@PreAuthorize和@Secured注解可以在方法级别进行权限控制。
1. 使用@Secured注解
在服务类的方法上使用@Secured注解,指定角色权限。
package cn.juwatech.springboot.service;import org.springframework.security.access.annotation.Secured;
import org.springframework.stereotype.Service;@Service
public class UserService {@Secured("ROLE_ADMIN")public String adminMethod() {return "Admin access only";}@Secured("ROLE_USER")public String userMethod() {return "User access only";}
}
2. 使用@PreAuthorize注解
使用@PreAuthorize注解支持SpEL(Spring Expression Language)表达式,实现更复杂的权限控制。
package cn.juwatech.springboot.service;import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Service;@Service
public class SecureService {@PreAuthorize("hasRole('ADMIN')")public String adminOnly() {return "Admin access only";}@PreAuthorize("hasRole('USER') and #id == principal.id")public String userOnly(Long id) {return "User access for ID: " + id;}
}
四、使用JWT进行安全认证
JWT(JSON Web Token)是一种轻量级的认证机制,常用于移动和Web应用的认证。
1. 添加JWT依赖
在pom.xml中添加JWT相关依赖:
<dependency><groupId>io.jsonwebtoken</groupId><artifactId>jjwt</artifactId><version>0.9.1</version>
</dependency>
2. 创建JWT工具类
实现一个JWT工具类,负责生成和解析JWT。
package cn.juwatech.springboot.security;import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.stereotype.Component;import java.util.Date;@Component
public class JwtUtil {private String secretKey = "secret";public String generateToken(String username) {return Jwts.builder().setSubject(username).setIssuedAt(new Date()).setExpiration(new Date(System.currentTimeMillis() + 1000 * 60 * 60 * 10)).signWith(SignatureAlgorithm.HS256, secretKey).compact();}public Claims extractClaims(String token) {return Jwts.parser().setSigningKey(secretKey).parseClaimsJws(token).getBody();}public String extractUsername(String token) {return extractClaims(token).getSubject();}public boolean isTokenExpired(String token) {return extractClaims(token).getExpiration().before(new Date());}public boolean validateToken(String token, String username) {return (username.equals(extractUsername(token)) && !isTokenExpired(token));}
}
3. 集成JWT认证
在Spring Security配置中集成JWT认证。
package cn.juwatech.springboot.config;import cn.juwatech.springboot.security.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {@Autowiredprivate JwtUtil jwtUtil;@Overrideprotected void configure(AuthenticationManagerBuilder auth) throws Exception {auth.inMemoryAuthentication().withUser("user").password(passwordEncoder().encode("password")).roles("USER").and().withUser("admin").password(passwordEncoder().encode("admin")).roles("ADMIN");}@Overrideprotected void configure(HttpSecurity http) throws Exception {http.csrf().disable().authorizeRequests().antMatchers("/login").permitAll().antMatchers("/admin/**").hasRole("ADMIN").antMatchers("/user/**").hasRole("USER").anyRequest().authenticated().and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);http.addFilterBefore(new JwtRequestFilter(jwtUtil), UsernamePasswordAuthenticationFilter.class);}@Beanpublic PasswordEncoder passwordEncoder() {return new BCryptPasswordEncoder();}
}
四、总结
通过本文,我们全面了解了在Spring Boot中实现安全配置的各种方法,包括基本的安全配置、基于注解的权限控制以及如何集成JWT进行认证。Spring Security提供了丰富的功能,使得应用程序的安全性得到有效保障。
微赚淘客系统3.0小编出品,必属精品!
相关文章:
Spring Boot中的安全配置与实现
Spring Boot中的安全配置与实现 大家好,我是免费搭建查券返利机器人省钱赚佣金就用微赚淘客系统3.0的小编,也是冬天不穿秋裤,天冷也要风度的程序猿!今天我们将深入探讨Spring Boot中的安全配置与实现,看看如何保护你的…...
DepthAnything(2): 基于ONNXRuntime在ARM(aarch64)平台部署DepthAnything
DepthAnything(1): 先跑一跑Depth Anything_depth anything离线怎么跑-CSDN博客 目录 1. 写在前面 2. 安装推理组件 3. 生成ONNX 4. 准备ONNXRuntime库 5. API介绍 6. 例程 1. 写在前面 DepthAnything是一种能在任何情况下处理任何图像的简单却又强大的深度估计模型。 …...
JAVA简单封装UserUtil
目录 思路 一、TokenFilterConfiguration 二、FilterConfig 三、TokenContextHolder 四、TokenUtil 五、UserUtil 思路 配置Token过滤器(TokenFilterConfiguration):实现一个Token过滤器配置,用于拦截HTTP请求,从请求头中提取Token&…...
【TOOLS】Chrome扩展开发
Chrome Extension Development 1. 入门教程 入门案例,可以访问【 谷歌插件官网官方文档 】查看官方入门教程,这里主要讲解大概步骤 Chrome Extenson 没有固定的脚手架,所以项目的搭建需要根据开发者自己根据需求搭建项目(例如通过…...
分享WPF的UI开源库
文章目录 前言一、HandyControl二、AduSkin三、Adonis UI四、Panuon.WPF.UI五、LayUI-WPF六、MahApps.Metro七、MaterialDesignInXamlToolkit八、FluentWPF九、DMSkin总结 前言 分享WPF的UI开源库。 一、HandyControl HandyControl是一套WPF控件库,它几乎重写了所…...
[ACM独立出版]2024年虚拟现实、图像和信号处理国际学术会议(ICVISP 2024)
最新消息ICVISP 2024-已通过ACM出版申请投稿免费参会,口头汇报或海报展示(可获得相应证明证书) ————————————————————————————————————————— [ACM独立出版]2024年虚拟现实、图像和信号处理国际学术会议(ICVI…...
JVM:类加载器
文章目录 一、什么是类加载器二、类加载器的应用场景三、类加载器的分类1、分类2、启动类加载器3、Java中的默认类加载器(1)扩展类加载器(2)应用程序类加载器(3)arthas中类加载器相关的功能 四、双亲委派机…...
支持向量机 (support vector machine,SVM)
支持向量机 (support vector machine,SVM) flyfish 支持向量机是一种用于分类和回归的机器学习模型。在分类任务中,SVM试图找到一个最佳的分隔超平面,使得不同类别的数据点在空间中被尽可能宽的间隔分开。 超平面方…...
宝塔面板以www用户运行composer
方式一 执行命令时指定www用户 sudo -u www composer update方式二 在网站配置中的composer选项卡中选择配置运行...
昇思25天打卡营-mindspore-ML- Day24-基于 MindSpore 实现 BERT 对话情绪识别
学习笔记:基于MindSpore实现BERT对话情绪识别 算法原理 BERT(Bidirectional Encoder Representations from Transformers)是由Google于2018年开发的一种预训练语言表示模型。BERT的核心原理是通过在大量文本上预训练深度双向表示࿰…...
【精品资料】模块化数据中心解决方案(33页PPT)
引言:模块化数据中心解决方案是一种创新的数据中心设计和部署策略,旨在提高数据中心的灵活性、可扩展性和效率。这种方案通过将数据中心的基础设施、计算、存储和网络资源封装到标准化的模块中,实现了快速部署、易于管理和高效运维的目标 方案…...
N6 word2vec文本分类
🍨 本文为🔗365天深度学习训练营 中的学习记录博客🍖 原作者:K同学啊# 前言 前言 上周学习了训练word2vec模型,这周进行相关实战 1. 导入所需库和设备配置 import torch import torch.nn as nn import torchvision …...
excel、word、ppt 下载安装步骤整理
请按照我的步骤开始操作,注意以下截图红框标记处(往往都是需要点击的地方) 第一步:下载 首先进入office下载网址: otp.landian.vip 然后点击下载 拉到下方 下载站点(这里根据自己的需要选择下载&#x…...
【python学习】标准库之日期和时间库定义、功能、使用场景和示例
引言 datetime模块最初是由 Alex Martelli 在 Python 2.3 版本引入的,目的是为了解决之前版本中处理日期和时间时存在的限制和不便 在datetime模块出现之前,Python 主要使用time模块来处理时间相关的功能,但 time模块主要基于 Unix 纪元时间&…...
Android --- Kotlin学习之路:基础语法学习笔记
------>可读可写变量 var name: String "Hello World";------>只读变量 val name: String "Hello World"------>类型推断 val name: String "Hello World" 可以写成 val name "Hello World"------>基本数据类型 1…...
嵌入式智能手表项目实现分享
简介 这是一个基于STM32F411CUE6和FreeRTOS和LVGL的低成本的超多功能的STM32智能手表~ 推荐 如果觉得这个手表的硬件难做,又想学习相关的东西,可以试下这个新出的开发板,功能和例程demo更多!FriPi炸鸡派STM32F411开发板: 【STM32开发板】 FryPi炸鸡派 - 嘉立创EDA开源硬件平…...
`nmap`模块是一个用于与Nmap安全扫描器交互的库
在Python中,nmap模块是一个用于与Nmap安全扫描器交互的库。Nmap(Network Mapper)是一个开源工具,用于发现网络上的设备和服务。虽然Python的nmap模块可能不是官方的Nmap库(因为Nmap本身是用C/C编写的)&…...
JVM系列 | 对象的创建与存储
JVM系列 | 对象的生命周期1 对象的创建与存储 文章目录 前言对象的创建过程内存空间的分配方式方式1 | 指针碰撞方式2 | 空闲列表 线程安全问题 | 避免空间冲突的方式方式1 | 同步处理(加锁)方式2 | 本地线程分配缓存 对象的内存布局Part1 | 对象头Mark Word类型指针…...
【JavaScript 算法】快速排序:高效的排序算法
🔥 个人主页:空白诗 文章目录 一、算法原理二、算法实现三、应用场景四、优化与扩展五、总结 快速排序(Quick Sort)是一种高效的排序算法,通过分治法将数组分为较小的子数组,递归地排序子数组。快速排序通常…...
Excel如何才能忽略隐藏行进行复制粘贴?
你有没有遇到这样的情况:数据很多,将一些数据隐藏后,进行复制粘贴,结果发现粘贴后的内容仍然将整个数据都显示出来了!那么,Excel如何才能忽略隐藏行进行复制粘贴? 打开你的Excel表格 Excel如何…...
[python] 配置管理框架Hydra使用指北
1 基础教程1.1 快速入门简单示例以下代码是一个简单的Hydra应用示例,它会打印出配置信息,其中my_app函数是编写业务逻辑的入口。from omegaconf import DictConfig, OmegaConf import hydrahydra.main(version_baseNone) def my_app(cfg: DictConfig) -&…...
3倍效率提升!用Intel Texture Works插件在Photoshop中实现专业级纹理压缩
3倍效率提升!用Intel Texture Works插件在Photoshop中实现专业级纹理压缩 【免费下载链接】Intel-Texture-Works-Plugin Intel has extended Photoshop* to take advantage of the latest image compression methods (BCn/DXT) via plugin. The purpose of this plu…...
使用Linux系统部署灵毓秀-牧神-造相Z-Turbo的完整指南
使用Linux系统部署灵毓秀-牧神-造相Z-Turbo的完整指南 本文详细讲解如何在Linux服务器上一步步部署灵毓秀-牧神-造相Z-Turbo,从环境准备到最终运行,让你快速上手这个专业的文生图工具。 1. 开始之前:了解你要部署的工具 灵毓秀-牧神-造相Z-T…...
HoRain云--SVN检出操作完全指南
🎬 HoRain 云小助手:个人主页 ⛺️生活的理想,就是为了理想的生活! ⛳️ 推荐 前些天发现了一个超棒的服务器购买网站,性价比超高,大内存超划算!忍不住分享一下给大家。点击跳转到网站。 目录 ⛳️ 推荐 …...
RVC模型推理性能对比:不同GPU服务器配置下的速度与效果评测
RVC模型推理性能对比:不同GPU服务器配置下的速度与效果评测 最近在折腾RVC模型,发现一个挺实际的问题:同样的模型,放在不同的GPU服务器上跑,效果和速度能差多少?这直接关系到我们做项目时的成本预算和体验…...
百川2-13B模型微调实战:定制化软件测试用例生成
百川2-13B模型微调实战:定制化软件测试用例生成 最近和几个做测试开发的朋友聊天,他们都在吐槽同一个问题:写测试用例太费时间了。尤其是面对一个新功能或者一个复杂的接口,从理解需求到设计用例,再到编写测试数据和边…...
Z-Image-Turbo创意作品展:当AI遇见中国传统水墨
Z-Image-Turbo创意作品展:当AI遇见中国传统水墨 精选20组Z-Image-Turbo生成的中国风水墨作品,展示AI在传统艺术领域的创新应用 1. 开场白:AI与水墨的奇妙邂逅 最近试用了Z-Image-Turbo这个AI图像生成模型,专门用它创作了一批中国…...
ULID CLI工具完全指南:命令行操作与批量生成技巧
ULID CLI工具完全指南:命令行操作与批量生成技巧 【免费下载链接】javascript Universally Unique Lexicographically Sortable Identifier 项目地址: https://gitcode.com/gh_mirrors/javas/javascript ULID(Universally Unique Lexicographical…...
Win11Debloat:5分钟让你的Windows 11系统焕然一新
Win11Debloat:5分钟让你的Windows 11系统焕然一新 【免费下载链接】Win11Debloat 一个简单的PowerShell脚本,用于从Windows中移除预装的无用软件,禁用遥测,从Windows搜索中移除Bing,以及执行各种其他更改以简化和改善你…...
别再只用鼠标点!Blender 3.6.5效率翻倍的键盘流操作指南(拯救你的右手腕)
Blender 3.6.5键盘流操作指南:解放右手的高效建模艺术 刚接触Blender时,我们总是不自觉地依赖鼠标点击菜单和工具栏——这就像用勺子吃牛排,虽然也能完成,但效率低下且容易疲劳。真正的Blender高手往往双手不离键盘,仅…...
