springboot3整合最新版jjwt(0.12.3)
Spring Boot 3整合JJWT(Java JSON Web Token)的步骤如下:
- 添加JJWT依赖到
pom.xml
文件中:
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.12.3</version>
</dependency>
- 创建JWT的工具类,用于生成和验证JWT:
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import java.security.Key;
import javax.crypto.spec.SecretKeySpec;
public class JwtTokenUtil {
private static final String SECRET_KEY = "your_secret_key";
public static String generateToken(String subject) {
SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
byte[] apiKeySecretBytes = SECRET_KEY.getBytes();
Key key = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());
return Jwts.builder().setSubject(subject).signWith(signatureAlgorithm, key).compact();
}
public static boolean validateToken(String token, String subject) {
try {
SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
byte[] apiKeySecretBytes = SECRET_KEY.getBytes();
Key key = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());
Jwts.parserBuilder().setSigningKey(key).build().parseClaimsJws(token).getBody().getSubject();
return true;
} catch (Exception e) {
return false;
}
}
}
- 在Spring Boot应用中使用JWT:
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class TokenController {
@GetMapping("/generate-token")
public String generateToken() {
return JwtTokenUtil.generateToken("some-subject");
}
@GetMapping("/validate-token")
public boolean validateToken(String token) {
return JwtTokenUtil.validateToken(token, "some-subject");
}
}
确保你的SECRET_KEY
是一个复杂且安全的密钥,并在实际环境中保管好。
以上代码提供了生成JWT和验证JWT的简单示例。在实际应用中,你可能需要根据自己的需求进行扩展,比如添加过期时间、c
评论已关闭