亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

使用Spring Security和JWT實現(xiàn)安全認證機制

 更新時間:2024年11月04日 11:23:42   作者:( ????? )920  
在現(xiàn)代 Web 應用中,安全認證和授權是保障數(shù)據(jù)安全和用戶隱私的核心機制,Spring Security 是 Spring 框架下專為安全設計的模塊,具有高度的可配置性和擴展性,而 JWT則是當前流行的認證解決方案,所以本文介紹了如何使用Spring Security和JWT實現(xiàn)安全認證機制

引言

在現(xiàn)代 Web 應用中,安全認證和授權是保障數(shù)據(jù)安全和用戶隱私的核心機制。Spring Security 是 Spring 框架下專為安全設計的模塊,具有高度的可配置性和擴展性。而 JWT(JSON Web Token) 則是當前流行的認證解決方案,因其無狀態(tài)、可擴展性強等特點被廣泛應用于微服務和移動應用中。

本文將從以下幾個部分詳細介紹如何使用 Spring Security 和 JWT 實現(xiàn)一個完整的認證機制:

  1. JWT 認證流程概述
  2. Spring Security 的基本配置
  3. JWT 生成與解析
  4. 基于 Spring Security 的 JWT 安全配置
  5. 實現(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. 測試與驗證

  1. 獲取 Token:使用客戶端(例如 Postman)請求 /login 接口,得到包含 JWT Token 的響應頭。
  2. 訪問受保護接口:將 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源碼解析之HashMap的put、resize方法詳解,文中有非常詳細的代碼示例,對正在學習java的小伙伴們有很大的幫助,需要的朋友可以參考下
    2021-04-04
  • SpringBoot中讀取application.properties配置文件的方法

    SpringBoot中讀取application.properties配置文件的方法

    這篇文章主要介紹了SpringBoot中讀取application.properties配置文件的三種方法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習吧
    2023-02-02
  • Mybatis-Plus通過SQL注入器實現(xiàn)批量插入的實踐

    Mybatis-Plus通過SQL注入器實現(xiàn)批量插入的實踐

    本文主要介紹了Mybatis-Plus通過SQL注入器實現(xiàn)批量插入的實踐,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2022-08-08
  • RabbitMq的5種模式及實例解讀

    RabbitMq的5種模式及實例解讀

    這篇文章主要介紹了RabbitMq的5種模式及實例解讀,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2023-09-09
  • Java并發(fā)編程之CountDownLatch原理詳解

    Java并發(fā)編程之CountDownLatch原理詳解

    這篇文章主要介紹了Java并發(fā)編程之CountDownLatch原理詳解,CountDownLatch類中使用了一個繼承自AQS的共享鎖Sync對象,構造CountDownLatch對象時會將傳入的線程數(shù)值設為AQS的state值,需要的朋友可以參考下
    2023-12-12
  • 如何用Springboot快速整合shiro安全框架

    如何用Springboot快速整合shiro安全框架

    這篇文章主要介紹了如何用SpringBoot快速整合shiro安全框架,shiro原名Apache Shiro 是一個Java 的安全(權限)框架。Shiro 可以非常容易的開發(fā)出足夠好的應用,感興趣的同學可以參考閱讀
    2023-04-04
  • java中replaceAll替換圓括號實例代碼

    java中replaceAll替換圓括號實例代碼

    正則表達式的保留字符主要有:圓括號、方括號、花括號、豎線、橫線、點號、加號、星號、反斜桿等等,下面這篇文章主要給大家介紹了關于java中replaceAll替換圓括號的相關資料,需要的朋友可以參考下
    2022-10-10
  • SpringBoot自動裝配Import示例詳解

    SpringBoot自動裝配Import示例詳解

    SpringBoot中@Import注解的使用可以幫助開發(fā)者將指定的Bean或配置類導入到IOC容器中,該注解支持四種用法:導入Bean、導入配置類、實現(xiàn)ImportSelector接口和實現(xiàn),感興趣的朋友一起看看吧
    2024-09-09
  • 詳解java實現(xiàn)HTTP請求的三種方式

    詳解java實現(xiàn)HTTP請求的三種方式

    這篇文章主要介紹了java實現(xiàn)HTTP請求的三種方式,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2019-04-04
  • 自己動手在Spring-Boot上加強國際化功能的示例

    自己動手在Spring-Boot上加強國際化功能的示例

    這篇文章主要介紹了自己動手在Spring-Boot上加強國際化功能的示例,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2018-04-04

最新評論