詳解SpringBoot如何使用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ù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
使用Mybatis-Plus時的SqlSessionFactory問題及處理
這篇文章主要介紹了使用Mybatis-Plus時的SqlSessionFactory問題及處理方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-12-12
使用RestTemplate調用RESTful?API的代碼示例
在開發(fā)?Web?應用程序時,調用?RESTful?API?是一個常見的任務,本文將介紹如何使用?RestTemplate?調用?RESTful?API,并提供示例代碼,感興趣的同學可以跟著小編一起來看看2023-06-06

