【发布时间】:2021-08-16 19:13:07
【问题描述】:
我有一个 Spring Boot + Keycloak 项目,我发现 Spring Boot 没有使用 keycloak 验证 JWT。例如,如果我从 Keycloak 获得令牌并关闭 Keycloak,我仍然可以使用此 JWT 令牌访问我的端点。我有这个安全配置器类:
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true, jsr250Enabled = true)
@RequiredArgsConstructor
public class KeycloakSecurityConfigurer extends WebSecurityConfigurerAdapter {
private final RoleConverter converter;
@Value("${spring.security.oauth2.keycloak.jwt.issuer-uri}")
private String issuerUri;
@Override
public void configure(final HttpSecurity http) throws Exception {
http.headers().frameOptions().disable()
.and()
.csrf().disable()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.oauth2ResourceServer(
oauth2ResourceServer -> oauth2ResourceServer.jwt(
jwt -> jwt.jwtAuthenticationConverter(jwtAuthenticationConverter())));
http.authorizeRequests().antMatchers("/**").authenticated();
}
private Converter<Jwt, ? extends AbstractAuthenticationToken> jwtAuthenticationConverter() {
JwtAuthenticationConverter jwtConverter = new JwtAuthenticationConverter();
jwtConverter.setJwtGrantedAuthoritiesConverter(converter);
return jwtConverter;
}
@Bean
public JwtDecoder jwtDecoder() {
return JwtDecoders.fromOidcIssuerLocation(issuerUri);
}
}
“转换器”没什么特别的,只是从 JWT 令牌中提取角色并返回它们的列表。
如何强制 Spring Security 验证 JWT 令牌?
application.yml:
spring:
security:
oauth2:
keycloak:
jwt:
issuer-uri: http://localhost:8180/auth/realms/test-realm
【问题讨论】:
-
你能告诉我们你的
application.yml文件吗? -
添加到问题
标签: java spring spring-boot spring-security jwt