如何在Spring Boot中启用JWT和JWKS?
时间: 2024-10-10 16:03:59 浏览: 57
要在Spring Boot项目中启用JWT(JSON Web Tokens)和JWKS(JSON Web Key Set),你需要做以下几个步骤:
- 添加依赖:首先,在你的
pom.xml
或build.gradle
文件中添加Spring Security和相关的JWT库,如spring-security-oauth2-jwt
。
// Gradle (Kotlin DSL)
implementation 'org.springframework.boot:spring-boot-starter-security'
implementation 'io.jsonwebtoken:jjwt-api'
implementation 'io.jsonwebtoken:jjwt-impl'
// Maven
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-api</artifactId>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-impl</artifactId>
<scope>runtime</scope> <!-- runtime-only dependency for JWT signing -->
</dependency>
- 配置Security:在
application.yml
或application.properties
中设置security.oauth2.resourceserver.jwt
属性来启用JWT,并指定令牌颁发者和刷新令牌策略等。
# application.yml
security:
oauth2:
resourceserver:
jwt:
issuer-uri: http://your-app.example.com/oauth2/token
jwk-set-url: http://your-app.example.com/oauth2/jwks
// 如果有自动刷新机制,可以配置token-refresh-token
# token-info-uri: http://your-app.example.com/oauth2/check-token
创建JWKs:如果你需要动态生成JWKs,可以使用
@Configuration
或@EnableWebSecurity
类来创建一个JwkProvider
,或者配置一个生产JWKs的外部服务。例如,如果使用Keycloak
作为认证服务器,那么JWKs会由Keycloak提供。验证JWT:为了验证JWT,Spring Security默认会检查
Authorization
头的Bearer Token。确保你的API控制器上已经启用JWT拦截器或处理程序。
@RestController
public class JwtController {
@GetMapping("/protected")
@PreAuthorize("hasRole('USER')")
public String protectedEndpoint() {
// 在这里处理请求,JWT会在授权检查后生效
return "Hello, user!";
}
}
相关推荐


















