使用Spring Security和JWT實現(xiàn)安全認證機制
引言
在現(xiàn)代 Web 應用中,安全認證和授權是保障數(shù)據(jù)安全和用戶隱私的核心機制。Spring Security 是 Spring 框架下專為安全設計的模塊,具有高度的可配置性和擴展性。而 JWT(JSON Web Token) 則是當前流行的認證解決方案,因其無狀態(tài)、可擴展性強等特點被廣泛應用于微服務和移動應用中。
本文將從以下幾個部分詳細介紹如何使用 Spring Security 和 JWT 實現(xiàn)一個完整的認證機制:
- JWT 認證流程概述
- Spring Security 的基本配置
- JWT 生成與解析
- 基于 Spring Security 的 JWT 安全配置
- 實現(xiàn)用戶登錄和認證
1. JWT 認證流程概述
JWT 的認證流程如下:
- 用戶登錄:用戶通過用戶名和密碼發(fā)送請求給服務器。
- 服務器驗證:服務器驗證用戶身份,驗證通過后生成 JWT Token。
- Token 下發(fā):服務器將生成的 Token 返回給客戶端。
- 后續(xù)請求攜帶 Token:客戶端在后續(xù)請求中將 JWT Token 添加到請求頭中,服務器通過解析和驗證 Token 確認請求的合法性。
這種方式的核心優(yōu)勢在于 Token 是無狀態(tài)的,服務器無需維護用戶的會話信息,且 JWT 可在分布式系統(tǒng)中實現(xiàn)共享認證。
2. Spring Security 的基本配置
創(chuàng)建一個簡單的 Spring Boot 項目,并添加 Spring Security 和 JWT 的依賴:
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <dependency> <groupId>io.jsonwebtoken</groupId> <artifactId>jjwt</artifactId> <version>0.9.1</version> </dependency> </dependencies>
配置 SecurityConfig 類
創(chuàng)建 SecurityConfig
類以配置 Spring Security 基本設置:
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; @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.csrf().disable() .authorizeRequests() .antMatchers("/login").permitAll() .anyRequest().authenticated(); } }
上面的配置指定 /login
接口公開訪問,其余接口需要認證后才能訪問。
3. JWT 生成與解析
使用 JWT 庫生成和解析 Token。創(chuàng)建 JwtUtil
工具類,實現(xiàn)生成和驗證 JWT 的方法:
import io.jsonwebtoken.Claims; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.SignatureAlgorithm; import java.util.Date; public class JwtUtil { private static final String SECRET_KEY = "mySecretKey"; // 生成 JWT public static String generateToken(String username) { return Jwts.builder() .setSubject(username) .setIssuedAt(new Date()) .setExpiration(new Date(System.currentTimeMillis() + 86400000)) // 24小時有效期 .signWith(SignatureAlgorithm.HS256, SECRET_KEY) .compact(); } // 解析 JWT public static Claims parseToken(String token) { return Jwts.parser() .setSigningKey(SECRET_KEY) .parseClaimsJws(token) .getBody(); } }
4. 基于 Spring Security 的 JWT 安全配置
在 Spring Security 過濾鏈中添加 JWT 過濾器。實現(xiàn)一個 JwtAuthenticationFilter
類,在每次請求時攔截并驗證 Token:
import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.web.authentication.www.BasicAuthenticationFilter; import io.jsonwebtoken.Claims; public class JwtAuthenticationFilter extends BasicAuthenticationFilter { public JwtAuthenticationFilter(AuthenticationManager authManager) { super(authManager); } @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException { String token = request.getHeader("Authorization"); if (token == null || !token.startsWith("Bearer ")) { chain.doFilter(request, response); return; } Claims claims = JwtUtil.parseToken(token.replace("Bearer ", "")); String username = claims.getSubject(); if (username != null) { UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(username, null, new ArrayList<>()); SecurityContextHolder.getContext().setAuthentication(auth); } chain.doFilter(request, response); } }
將 JwtAuthenticationFilter
過濾器添加到 SecurityConfig
中:
@Override protected void configure(HttpSecurity http) throws Exception { http.csrf().disable() .authorizeRequests() .antMatchers("/login").permitAll() .anyRequest().authenticated() .and() .addFilter(new JwtAuthenticationFilter(authenticationManager())); }
5. 實現(xiàn)用戶登錄和認證
創(chuàng)建一個登錄控制器 AuthController
,驗證用戶后生成 JWT:
import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpServletResponse; @RestController public class AuthController { @PostMapping("/login") public void login(@RequestParam String username, @RequestParam String password, HttpServletResponse response) { // 這里簡單校驗用戶名密碼 if ("user".equals(username) && "password".equals(password)) { String token = JwtUtil.generateToken(username); response.setHeader("Authorization", "Bearer " + token); } else { response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); } } }
以上代碼實現(xiàn)了一個簡單的登錄接口,用戶登錄成功后將返回 JWT Token,并將該 Token 存儲在響應頭中。
6. 測試與驗證
- 獲取 Token:使用客戶端(例如 Postman)請求
/login
接口,得到包含 JWT Token 的響應頭。 - 訪問受保護接口:將 Token 添加到請求頭
Authorization
中,再次請求受保護接口,驗證是否可以成功訪問。
結論
通過以上步驟,我們實現(xiàn)了一個基于 Spring Security 和 JWT 的安全認證系統(tǒng)。在實際項目中,可以進一步擴展此功能,例如集成數(shù)據(jù)庫實現(xiàn)用戶管理、配置 JWT 自動續(xù)簽等。這種基于 JWT 的無狀態(tài)認證適用于分布式系統(tǒng)和微服務架構,有助于提高系統(tǒng)的安全性和可擴展性。
以上就是使用Spring Security和JWT實現(xiàn)安全認證機制的詳細內容,更多關于Spring Security JWT安全認證的資料請關注腳本之家其它相關文章!
相關文章
Java源碼解析之HashMap的put、resize方法詳解
這篇文章主要介紹了Java源碼解析之HashMap的put、resize方法詳解,文中有非常詳細的代碼示例,對正在學習java的小伙伴們有很大的幫助,需要的朋友可以參考下2021-04-04SpringBoot中讀取application.properties配置文件的方法
這篇文章主要介紹了SpringBoot中讀取application.properties配置文件的三種方法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習吧2023-02-02Mybatis-Plus通過SQL注入器實現(xiàn)批量插入的實踐
本文主要介紹了Mybatis-Plus通過SQL注入器實現(xiàn)批量插入的實踐,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2022-08-08Java并發(fā)編程之CountDownLatch原理詳解
這篇文章主要介紹了Java并發(fā)編程之CountDownLatch原理詳解,CountDownLatch類中使用了一個繼承自AQS的共享鎖Sync對象,構造CountDownLatch對象時會將傳入的線程數(shù)值設為AQS的state值,需要的朋友可以參考下2023-12-12