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小编出品,必属精品!

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

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

相关文章

在表格中把tab换成enter键------ivx

为了方便用户输入&#xff0c;把tab键替换成enter回车 方法如下&#xff1a; 添加一个fx函数 document.addEventListener(‘keydown’, function(event) { if (event.key ‘Enter’ && !event.shiftKey) { event.preventDefault(); var focusableElements document.q…

昇思25天打卡营-mindspore-ML- Day22-应用实践-自然语言处理-LSTM+CRF序列标注

昇思25天打卡营-mindspore-ML- Day22-应用实践-自然语言处理-LSTMCRF序列标注 今天学习了 LSTMCRF 序列标注方法&#xff0c;它是一种结合了循环神经网络&#xff08;RNN&#xff09;和条件随机场&#xff08;CRF&#xff09;的强大模型&#xff0c;用于处理序列标注问题&#…

【C++BFS】690. 员工的重要性

本文涉及知识点 CBFS算法 LeetCode690. 员工的重要性 你有一个保存员工信息的数据结构&#xff0c;它包含了员工唯一的 id &#xff0c;重要度和直系下属的 id 。 给定一个员工数组 employees&#xff0c;其中&#xff1a; employees[i].id 是第 i 个员工的 ID。 employees[…

RabbitMQ 高级功能

RabbitMQ 是一个广泛使用的开源消息代理&#xff0c;它支持多种消息传递协议&#xff0c;可以在分布式系统中用于可靠的消息传递。除了基本的消息队列功能外&#xff0c;RabbitMQ 还提供了一些高级功能&#xff0c;增强了其在高可用性、扩展性和灵活性方面的能力。以下是一些主…

软件架构之嵌入式系统设计(2)

软件架构之嵌入式系统设计&#xff08;2&#xff09; 12.4 嵌入式网络系统12.4.1 现场总线网12.4.2 家庭信息网11.4.3 无线数据通信网12.4.4 嵌入式 Internet 12.5 嵌入式数据库管理系统12.5.1 使用环境的特点12.5.2 系统组成与关键技术 12.6 实时系统与嵌入式操作系统12.6.1 嵌…

MyBatis(38)MyBatis 如何与 Spring Boot 集成,有哪些实践技巧

集成MyBatis与Spring Boot可以极大地提升开发效率&#xff0c;简化配置&#xff0c;并利用Spring Boot的自动配置特性优化项目结构和性能。下面我们将详细探讨如何实现这一集成&#xff0c;并分享一些实践技巧。 1. 添加依赖 首先&#xff0c;在pom.xml中添加MyBatis和Spring…

AI学习指南机器学习篇-聚类树的剪枝

AI学习指南机器学习篇-聚类树的剪枝 在机器学习领域&#xff0c;聚类是一种常用的无监督学习方法&#xff0c;通过对数据进行分组来发现数据中的结构和模式。聚类树是一种常用的聚类算法之一&#xff0c;它通过构建一个树状结构来展示聚类的层次关系&#xff0c;并能够帮助我们…

Linux 忘记root密码,通过单用户模式修改

银河麒麟桌面操作系统 V10&#xff08;sp1&#xff09;”忘记用户密码&#xff0c;需要修改用户密码所写&#xff0c;可用于 X86 架构和 arm 架构。 2. 选择第一项&#xff0c;在上图界面按“e”键进行编辑修改。 3. 在以 linux 开头这行的行末&#xff0c;添加“init/bin/bas…

Rockchip Android平台编译生成userdata.img

Rockchip Android平台编译生成userdata.img 适用版本 本修改方法适用于Android12及以上版本 代码修改 device/rockchip/rk3576&#xff1a; --- a/rk3576_u/BoardConfig.mkb/rk3576_u/BoardConfig.mk-28,4 28,7 PRODUCT_KERNEL_CONFIG pcie_wifi.configBOARD_GSENSOR_MXC…

SSE(Server-Send-Event)服务端推送数据技术

SSE&#xff08;Server-Send-Event&#xff09;服务端推送数据技术 大家是否遇到过服务端需要主动传输数据到客户端的情况&#xff0c;目前有三种解决方案。 客户端轮询更新数据。服务端与客户端建立 Socket 连接双向通信服务端与客户建立 SSE 连接单向通信 几种方案的比较&…

【前端】fis框架学习

文章目录 1. 介绍 1. 介绍 FIS是专为解决前端开发中自动化工具、性能优化、模块化框架、开发规范、代码部署、开发流程等问题的工具框架。 使用FIS我们可以快速的完成各种前端项目的资源压缩、合并等等各种性能优化工作&#xff0c;同时FIS还提供了大量的开发辅助功能 首先我们…

Nginx上配置多个网站

一、需求描述 我们只有一台安装了Nginx的服务器,但是我们需要实现在这台服务器上部署多个网站,用以对外提供服务。 二、Nginx上配置多个网站分析 一般网站的格式为:【http://ip地址:端口号/URI】(比如:http://192.168.3.201:80),IP地址也可用域名表示;那么要实现在Nginx…

QT实现WebSocket通信

文章目录 WebSocket服务端WebSocket客户端html websocket客户端在Qt5中实现WebSocket通信可以通过使用QtWebSockets模块来实现。这个模块提供了一个WebSocket客户端和服务器的实现,可以很方便地在你的应用程序中集成WebSocket功能。 使用的时候,首先在pro工程文件中添加对应的…

【Vue】vue-element-admin概述

一、项目简介 定位&#xff1a;vue-element-admin是一个后台集成解决方案&#xff0c;旨在提供一种快速开发企业级后台应用的方案&#xff0c;让开发者能更专注于业务逻辑和功能实现&#xff0c;而非基础架构的搭建。技术栈&#xff1a;该项目基于Vue.js、Element UI、Vue Rou…

Redis 7.x 系列【24】哨兵模式配置项

有道无术&#xff0c;术尚可求&#xff0c;有术无道&#xff0c;止于术。 本系列Redis 版本 7.2.5 源码地址&#xff1a;https://gitee.com/pearl-organization/study-redis-demo 文章目录 1. 前言2. 配置项2.1 protected-mode2.2 port2.3 daemonize2.4 pidfile2.5 loglevel2.…

i18n、L10n、G11N 和 T9N 的含义

注&#xff1a;机翻&#xff0c;未校对。 Looking into localization for the first time can be terrifying, if only due to all of the abbreviations. But the meaning of i18n, L10n, G11N, and T9N, are all very easy to understand. 第一次研究本地化可能会很可怕&…

深入探索Python Web抓取世界:利用BeautifulSoup与Pandas构建全面的网页数据采集与分析流程

引言 在信息爆炸的时代&#xff0c;网络成为了一个无尽的知识宝库&#xff0c;其中包含了大量有价值的公开数据。Python作为一种灵活多变且具有强大生态系统支持的编程语言&#xff0c;尤其擅长于数据的收集、处理与分析工作。本文将聚焦于Python的两大利器——BeautifulSoup和…

如何做一个迟钝不受伤的打工人?

一、背景 在当前激烈的职场环境中&#xff0c;想要成为一个相对“迟钝”且不易受伤的打工人&#xff0c;以下是一些建议&#xff0c;但请注意&#xff0c;这里的“迟钝”并非指智力上的迟钝&#xff0c;而是指在应对复杂人际关系和压力时展现出的豁达与钝感力&#xff1a; 尊重…

【测开能力提升-fastapi框架】fastapi路由分发

1.7 路由分发 apps/app01.py from fastapi import APIRouterapp01 APIRouter()app01.get("/food") async def shop_food():return {"shop": "food"}app01.get("/bed") async def shop_food():return {"shop": "bed&…

部署stable-diffusion时遇到RuntimeError: Couldn‘t clone Stable Diffusion XL.问题

错误信息如下&#xff1a; venv "E:\AI\stable-diffusion-webui-master\venv\Scripts\Python.exe" fatal: ambiguous argument HEAD: unknown revision or path not in the working tree. Use -- to separate paths from revisions, like this: git <command>…