微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在弹簧中使用 JWK?

如何解决如何在弹簧中使用 JWK?

我得到了在项目上实施 jwks 的任务。在我们的项目中,我们使用 oauth2 实施了令牌验证检查。我们使用 jks 格式的证书来获取公钥。我们的项目中没有使用私钥,因为我们需要检查令牌的有效性。我们的目标是摆脱 .jks 文件。 jwks 的资源太少,因此有些地方不清楚。 如果我理解正确,那么 jwks 意味着资源中有一个 jwks.json 文件,里面有键,我们从令牌头中通过 Kid 选择。根据文档,不清楚是什么类型的文件,是如何加载供kid检查的,也就是什么时候发生的。有谁有项目可以作为例子吗?提前致谢

https://docs.spring.io/spring-security-oauth2-boot/docs/2.2.x-SNAPSHOT/reference/html/boot-features-security-oauth2-authorization-server.html

解决方法

可以使用 spring-boot 资源服务器实现。

首先,你需要在你的项目中添加以下依赖

<dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-oauth2-resource-server</artifactId>
    </dependency>

其次,需要添加认证服务器配置。您提到的 JSON 文件必须位于身份验证服务器上,或者您可以使用身份验证服务器的 JWKs URL。 您的属性文件中应该有这样的配置。

spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https:/example.com/.well-known/openid-configuration/jwks
spring.security.oauth2.resourceserver.jwt.issuer-uri=https:/example.com

最后,需要遵循自然的 spring-security API 配置。您需要的是以下内容。

@Configuration
@EnableWebSecurity
public class SecureSecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Value("${spring.security.oauth2.resourceserver.jwt.jwk-set-uri}")
    private String jwtSetUri;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.requiresChannel().anyRequest().requiresInsecure().and().cors()
                .and().csrf().disable()
                .authorizeRequests()
                .antMatchers(HttpMethod.GET,"some path1").permitAll()
                .antMatchers(HttpMethod.POST,"some path2").permitAll()
                .antMatchers(HttpMethod.GET,"some path3").permitAll()
                .antMatchers("/**").hasAuthority("some scope") // if you need this scope.
                .anyRequest()
                .authenticated()
                .and()
                .oauth2ResourceServer()
                .jwt().decoder(jwtDecoder());
    }


    @Bean
    CorsConfigurationSource corsConfigurationSource() {
        final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration().applyPermitDefaultValues();
        config.addAllowedMethod("PUT");
        config.addAllowedMethod("DELETE");
        source.registerCorsConfiguration("/**",config);
        return source;
    }

    private JwtDecoder jwtDecoder() {
        return NimbusJwtDecoder.withJwkSetUri(jwtSetUri)
                .jwtProcessorCustomizer(p -> p.setJWSTypeVerifier(
                        new DefaultJOSEObjectTypeVerifier<>(new JOSEObjectType("at+jwt")))).build();
    }
}

此后,Spring 应使用身份验证服务器自动验证对 API 的每个请求。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。