我的spring引导不使用KeyClope验证jwt令牌?

mbzjlibv  于 2021-10-10  发布在  Java
关注(0)|答案(3)|浏览(297)

我有一个springboot+keybeat项目,我发现springboot没有用keybeat验证jwt。例如,如果我从keydove获得一个令牌并关闭keydove,我仍然可以使用这个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
ohtdti5x

ohtdti5x1#

jwt令牌已缓存在springboot应用程序中,这是默认的缓存存储。为了从springboot应用程序中删除此令牌,用户应使用一些自定义缓存(如redis cache)来在应用程序中配置,而不是默认配置。无法删除存储在默认缓存中的令牌。只有在令牌内设置的超时之后,令牌才会自动失效

s4n0splo

s4n0splo2#

JWT意味着离线验证,这是通常发生的事情。接收应用程序(jwt的使用者)不需要经常访问授权服务器才能验证jwt。尽管spring无法与您的KeyClope对话,但这并不意味着令牌未经验证。正如其他人所指出的,spring缓存用于验证jwts签名的密钥,如果可以,它将使用缓存。
如果出于某种原因,您希望您的服务/api在线验证jwt(可能是因为您希望实现一种机制来撤销令牌),那么您可以切换到使用不透明令牌和令牌内省。在每个请求中,您的服务都必须调用keydape以将不透明令牌交换为jwt。请注意,此解决方案将使用更多的资源,只有在有充分理由的情况下,您才应该使用它。

kmbjn2e3

kmbjn2e33#

您可以查看 JwtDecoders.fromOidcIssuerLocation(issuerUri) .
发生的情况是,在应用程序启动时提取密钥,应用程序缓存它们以便在启动后执行验证。记住这一点,即使关闭keydape,jwt仍然会被验证,因为密钥仍然被缓存。

相关问题