美文网首页
Identity Server 4 与Spring Resour

Identity Server 4 与Spring Resour

作者: 寻找无名的特质 | 来源:发表于2023-03-12 06:03 被阅读0次

使用Identity Server 4 作为 认证服务器,Spring Resource Server 作为资源服务器,理论上应该可以,但在实际应用时遇到一些坑,记录如下。

首先是在Scope配置上,在Identity Server 4中增加的Scope,在Resource Server 设置时,需要增加SCOPE_前缀:

@Bean
    SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
                .csrf().disable()
                .cors()
                .and()
                .securityMatcher("/messages/**")
                .authorizeHttpRequests()
                .requestMatchers("/messages/**").hasAuthority("SCOPE_message.read")
                .and()
                .oauth2ResourceServer()
                .jwt();
        return http.build();
    }

第二,Spring Resource Server 缺省不支持at+jwt的token格式,而Identity Server 4 发布的access_token使用的是at+jwt,通过认证的客户端使用access_token访问时,会提示401错误,错误的说明是不支持at+jwt。这需要我们自行编写对at+jwt的解码代码。

    @Value("${spring.security.oauth2.resourceserver.jwt.jwk-set-uri}")
    private String jwkSetUri;
      @Bean
        public JwtDecoder jwtDecoder() {
            return NimbusJwtDecoder.withJwkSetUri(this.jwkSetUri)
                    .jwtProcessorCustomizer(customizer -> {
                        customizer.setJWSTypeVerifier(new DefaultJOSEObjectTypeVerifier<>(new JOSEObjectType("at+jwt")));
                    })
                    .build();
        }

在application.properties.yml中定义jwk-set-uri:

spring:
  security:
    oauth2:
      resourceserver:
        jwt:
          issuer-uri: http://host.docker.internal:7010
          jwk-set-uri: http://host.docker.internal:7010/.well-known/openid-configuration/jwks

相关文章

网友评论

      本文标题:Identity Server 4 与Spring Resour

      本文链接:https://www.haomeiwen.com/subject/oqfnhdtx.html