欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

詳解SpringBoot如何使用JWT實現(xiàn)身份認證和授權

 更新時間:2023年10月08日 10:20:54   作者:計算機畢設徐師兄  
JSON?Web?Token(JWT)是一種用于在網(wǎng)絡應用之間安全傳遞信息的開放標準,本文主要為大家介紹了如何在Spring?Boot中使用JWT實現(xiàn)身份認證和授權,需要的可以了解下

JSON Web Token(JWT)是一種用于在網(wǎng)絡應用之間安全傳遞信息的開放標準。它使用了一種緊湊且獨立于語言的方式在各方之間傳遞信息,通常用于在客戶端和服務器之間驗證用戶身份和授權訪問資源。本文將介紹如何在Spring Boot中使用JWT實現(xiàn)身份認證和授權。

什么是JWT

JWT是一個輕量級的令牌(token)協(xié)議,它使用JSON對象作為負載(payload)來傳遞信息,并使用數(shù)字簽名(digital signature)來驗證其真實性。JWT通常包括以下三個部分:

  • Header(頭部):包含了令牌的類型和使用的簽名算法。
  • Payload(負載):包含了一些聲明(claims),例如用戶ID、過期時間等。
  • Signature(簽名):用于驗證令牌的真實性,確保它未被篡改。

JWT的主要優(yōu)勢在于它的輕量性、易于使用以及可擴展性。它可以在不同的應用程序之間安全傳遞信息,無需每次都訪問數(shù)據(jù)庫或使用其他形式的驗證。

Spring Boot 中使用JWT的步驟

要在Spring Boot應用程序中使用JWT,需要執(zhí)行以下步驟:

步驟1:添加依賴項

首先,您需要在pom.xml文件中添加以下依賴項以使用JWT庫:

<dependency>
    <groupId>io.jsonwebtoken</groupId>
    <artifactId>jjwt-api</artifactId>
    <version>0.11.2</version>
</dependency>
<dependency>
    <groupId>io.jsonwebtoken</groupId>
    <artifactId>jjwt-impl</artifactId>
    <version>0.11.2</version>
</dependency>

步驟2:創(chuàng)建JWT工具類

接下來,您需要創(chuàng)建一個JWT工具類,用于生成和驗證JWT令牌。以下是一個示例的JWT工具類:

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.stereotype.Component;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
@Component
public class JwtUtils {
    private final String secret = "your_secret_key";
    private final long expirationTime = 86400000; // 1 day in milliseconds
    // 生成JWT令牌
    public String generateToken(String username) {
        Date now = new Date();
        Date expirationDate = new Date(now.getTime() + expirationTime);
        Map<String, Object> claims = new HashMap<>();
        claims.put("sub", username);
        return Jwts.builder()
                .setClaims(claims)
                .setIssuedAt(now)
                .setExpiration(expirationDate)
                .signWith(SignatureAlgorithm.HS512, secret)
                .compact();
    }
    // 從JWT令牌中提取用戶名
    public String extractUsername(String token) {
        Claims claims = Jwts.parser()
                .setSigningKey(secret)
                .parseClaimsJws(token)
                .getBody();
        return claims.getSubject();
    }
    // 驗證JWT令牌
    public boolean validateToken(String token) {
        try {
            Jwts.parser().setSigningKey(secret).parseClaimsJws(token);
            return true;
        } catch (Exception e) {
            return false;
        }
    }
}

在上述代碼中,JwtUtils類負責生成、解析和驗證JWT令牌。

步驟3:創(chuàng)建身份認證和授權邏輯

您需要創(chuàng)建身份認證和授權邏輯以確保只有合法用戶可以訪問受保護的資源。可以使用Spring Security等安全框架來實現(xiàn)這些功能。以下是一個示例的Spring Security配置類,用于使用JWT進行身份認證和授權:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
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.core.userdetails.UserDetailsService;
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 {
    private final JwtRequestFilter jwtRequestFilter;
    private final UserDetailsService userDetailsService;
    public SecurityConfig(JwtRequestFilter jwtRequestFilter, UserDetailsService userDetailsService) {
        this.jwtRequestFilter = jwtRequestFilter;
        this.userDetailsService = userDetailsService;
    }
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
            .authorizeRequests()
                .antMatchers("/authenticate").permitAll() // 放行認證接口
                .anyRequest().authenticated() // 所有其他請求需要認證
            .and()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
        http.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);
    }
}

在上述代碼中,SecurityConfig類配置了哪些端點需要進行身份認證,以及如何使用JWT進行認證。

步驟4:創(chuàng)建認證控制器

創(chuàng)建一個認證控制器,它負責生成JWT令牌并將其返回給客戶端。以下是一個示例的認證控制器:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;
@RestController
public class AuthController {
    private final AuthenticationManager authenticationManager;
    private final JwtUtils jwtUtils;
    private final UserDetailsService userDetailsService;
    @Autowired
    public AuthController(AuthenticationManager authenticationManager, JwtUtils jwtUtils, UserDetailsService userDetailsService) {
        this.authenticationManager = authenticationManager;
        this.jwtUtils = jwtUtils;
        this.userDetailsService =
 userDetailsService;
    }
    @PostMapping("/authenticate")
    public ResponseEntity<?> createAuthenticationToken(@RequestBody AuthRequest authenticationRequest) throws Exception {
        authenticate(authenticationRequest.getUsername(), authenticationRequest.getPassword());
        final UserDetails userDetails = userDetailsService.loadUserByUsername(authenticationRequest.getUsername());
        final String jwt = jwtUtils.generateToken(userDetails.getUsername());
        return ResponseEntity.ok(new AuthResponse(jwt));
    }
    private void authenticate(String username, String password) throws Exception {
        try {
            authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, password));
        } catch (Exception e) {
            throw new Exception("Invalid username or password");
        }
    }
}

在上述代碼中,AuthController類包含了生成JWT令牌的邏輯。

步驟5:創(chuàng)建受保護的資源和授權邏輯

最后,您可以創(chuàng)建受保護的資源和相應的授權邏輯。在Spring Security配置中,您可以使用@PreAuthorize注解來限制訪問資源的權限。以下是一個示例:

@RestController
public class ResourceController {
    @GetMapping("/hello")
    @PreAuthorize("hasRole('USER')")
    public String helloUser() {
        return "Hello, User!";
    }
    @GetMapping("/admin")
    @PreAuthorize("hasRole('ADMIN')")
    public String helloAdmin() {
        return "Hello, Admin!";
    }
}

在上述代碼中,@PreAuthorize注解確保只有具有相應角色的用戶可以訪問/hello和/admin端點。

測試JWT認證和授權

現(xiàn)在,您可以測試JWT認證和授權功能。首先,您可以使用/authenticate端點來獲取JWT令牌,然后將該令牌包含在請求的Authorization頭中,以訪問受保護的資源。如果令牌有效并且用戶具有所需的權限,將允許訪問資源。

結論

JWT是一種強大的工具,可用于實現(xiàn)身份認證和授權功能。在Spring Boot中使用JWT可以簡化安全性的實現(xiàn),使您能夠輕松地保護應用程序的資源。通過遵循本文中的步驟,您可以在Spring Boot應用程序中成功使用JWT。

到此這篇關于詳解SpringBoot如何使用JWT實現(xiàn)身份認證和授權的文章就介紹到這了,更多相關SpringBoot JWT身份認證內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

  • JAVA?OOM內存溢出問題深入解析

    JAVA?OOM內存溢出問題深入解析

    這篇文章主要為大家介紹了JAVA?OOM內存溢出問題深入解析,在生產(chǎn)環(huán)境搶修中,我們經(jīng)常會碰到應用系統(tǒng)java內存OOM的情況,這個問題非常常見,今天我們就這個問題來深入學習探討一下
    2023-10-10
  • 使用Mybatis-Plus時的SqlSessionFactory問題及處理

    使用Mybatis-Plus時的SqlSessionFactory問題及處理

    這篇文章主要介紹了使用Mybatis-Plus時的SqlSessionFactory問題及處理方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-12-12
  • Java BigDecimal類的使用和注意事項

    Java BigDecimal類的使用和注意事項

    這篇文章主要講解Java中BigDecimal類的用法,并簡單介紹一些注意事項,希望能給大家做一個參考。
    2016-06-06
  • Java基礎學習之ArrayList類概述與常用方法

    Java基礎學習之ArrayList類概述與常用方法

    這篇文章主要為大家簡單的介紹Java中ArrayList類的概述、常用方法及存儲字符串并遍歷,文中的示例代碼講解詳細,感興趣的小伙伴可以了解一下
    2022-08-08
  • 手工搭建Servlet實現(xiàn)

    手工搭建Servlet實現(xiàn)

    現(xiàn)在作為一個Java程序員,我們已經(jīng)習慣了使用IDE和Web框架進行開發(fā),IDE幫助我們做了編譯、打包的工作。Spring框架則幫助我們實現(xiàn)了Servlet接口,并把Servlet容器注冊到了Web容器中。本文主要介紹了Servlet手工搭建,感興趣的可以了解一下
    2021-07-07
  • Java Floyd算法求有權圖(非負權)的最短路徑并打印

    Java Floyd算法求有權圖(非負權)的最短路徑并打印

    這篇文章主要介紹了Java Floyd算法求有權圖(非負權)的最短路徑并打印,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2019-07-07
  • fastjson 使用方法詳細介紹

    fastjson 使用方法詳細介紹

    Fastjson是一個Java語言編寫的JSON處理器,由阿里巴巴公司開發(fā)。接下來通過本文給大家分享fastjson 使用方法詳細介紹,感興趣的朋友一起看看吧
    2017-11-11
  • springboot自動裝配的源碼與流程圖

    springboot自動裝配的源碼與流程圖

    在日常的開發(fā)過程中Spring Boot自動裝配的特性給我們開發(fā)減少了很多重復性的工作,這篇文章主要給大家介紹了關于springboot自動裝配的相關資料,需要的朋友可以參考下
    2021-08-08
  • java10下編譯lombok注解代碼分享

    java10下編譯lombok注解代碼分享

    這篇文章給大家分享了java10下編譯lombok注解的代碼,有興趣的朋友可以測試以下,學習參考下吧。
    2018-04-04
  • 使用RestTemplate調用RESTful?API的代碼示例

    使用RestTemplate調用RESTful?API的代碼示例

    在開發(fā)?Web?應用程序時,調用?RESTful?API?是一個常見的任務,本文將介紹如何使用?RestTemplate?調用?RESTful?API,并提供示例代碼,感興趣的同學可以跟著小編一起來看看
    2023-06-06

最新評論