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.pswp.cn/web/44125.shtml
繁體地址,請注明出處:http://hk.pswp.cn/web/44125.shtml
英文地址,請注明出處:http://en.pswp.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>…