spring-security - Spring security - 使用 WebClient 访问通过 Oauth2 "Password"授权类型保护的资源

标签 spring-security spring-webclient spring-oauth2

如何使用 WebClient 访问通过 Oauth2“密码”授权类型保护的资源?

与 Oauth2“客户端凭据”连接有效。在本例中,我需要密码授予类型。

我收到此错误:

401 Unauthorized from GET http://localhost:8086/test2 at org.springframework.web.reactive.function.client.WebClientResponseException.create(WebClientResponseException.java:198) ~[spring-webflux-5.3.19.jar:5.3.19]
    Suppressed: reactor.core.publisher.FluxOnAssembly$OnAssemblyException: 
Error has been observed at the following site(s):
    *__checkpoint ⇢ 401 from GET http://localhost:8086/test2 

我通过 Keycloack 配置了访问类型为“public”的身份验证服务器。我检查了通过 postman 访问 token 。您可以通过this post了解更多详情.

enter image description here

网络安全配置(适用于授予类型的客户端凭据):

@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter{
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers("*").permitAll();
    }
}

Web 客户端被创建为 Bean。它适用于客户端凭据授予类型。

@Configuration
public class WebClientOAuth2Config {
    @Bean("method2")
    WebClient webClientGrantPassword( @Qualifier("authclientmgr2") OAuth2AuthorizedClientManager authorizedClientManager2) {
        ServletOAuth2AuthorizedClientExchangeFilterFunction oauth2Client2 =
                        new ServletOAuth2AuthorizedClientExchangeFilterFunction(
                        authorizedClientManager2);
        oauth2Client2.setDefaultClientRegistrationId("businesspartners");
        return WebClient.builder().apply(oauth2Client2.oauth2Configuration()).build();
    }

    @Bean("authclientmgr2")
    public OAuth2AuthorizedClientManager authorizedClientManager2(
                    ClientRegistrationRepository clientRegistrationRepository,
                    OAuth2AuthorizedClientRepository authorizedClientRepository) {

        OAuth2AuthorizedClientProvider authorizedClientProvider = OAuth2AuthorizedClientProviderBuilder.builder()
                        .clientCredentials()
                        .build();

        DefaultOAuth2AuthorizedClientManager authorizedClientManager = new DefaultOAuth2AuthorizedClientManager(
                        clientRegistrationRepository, authorizedClientRepository);
        authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);

        return authorizedClientManager;
    }
}

Controller 访问资源服务器:

@RestController
public class Test2Controller {
  @Autowired
  private @Qualifier("method2") WebClient webClient2;

  @GetMapping("/test2")
  public String test2() {
    return webClient2.get().uri("http://localhost:8086/test2")
            .attributes(clientRegistrationId("businesspartners"))
            .retrieve().bodyToMono(String.class).block();
  }
}

application.yml 配置是:

server:
  port: 8081

spring:
  security:
    oauth2:
      client:
        registration:
          businesspartners:
            client-id: myclient2
            authorization-grant-type: password
            client-name: johan
            client-secret: password
        provider:
          businesspartners:
            issuer-uri: http://localhost:28080/auth/realms/realm2
            token-uri: http://localhost:28080/auth/realms/realm2/protocol/openid-connect/token

maven 依赖项包括:

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-oauth2-client</artifactId>
</dependency>
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-webflux</artifactId>
</dependency>

最佳答案

不确定是否可以使用 application.yml 来完成此操作,但以下是如何在代码中配置它

private ServerOAuth2AuthorizedClientExchangeFilterFunction oauth(
        String clientRegistrationId, SecurityConfig config) {
    var clientRegistration = ClientRegistration
            .withRegistrationId(clientRegistrationId)
            .clientAuthenticationMethod(ClientAuthenticationMethod.NONE)
            .tokenUri(config.getTokenUri() + "/token")
            .clientId(config.getClientId())
            .authorizationGrantType(AuthorizationGrantType.PASSWORD)
            .build();

    var authRepository = new InMemoryReactiveClientRegistrationRepository(clientRegistration);
    var authClientService = new InMemoryReactiveOAuth2AuthorizedClientService(authRepository);

    var authClientManager = new AuthorizedClientServiceReactiveOAuth2AuthorizedClientManager(
            authRepository, authClientService);

    var clientAuthProvider = new PasswordReactiveOAuth2AuthorizedClientProvider();
    authClientManager.setAuthorizedClientProvider(clientAuthProvider);
    authClientManager.setContextAttributesMapper(authorizeRequest ->  Mono.just(
            Map.of(
                    OAuth2AuthorizationContext.USERNAME_ATTRIBUTE_NAME, config.getUsername(),
                    OAuth2AuthorizationContext.PASSWORD_ATTRIBUTE_NAME, config.getPassword()
            )
    ));

    var oauth = new ServerOAuth2AuthorizedClientExchangeFilterFunction(authClientManager);
    oauth.setDefaultClientRegistrationId(clientRegistrationId);
    return oauth;
}

然后在WebClient中使用

WebClient webClient = WebClient.builder()
      .filter(oauth("businesspartners", securityConfig))
      .build();

其中 SecurityConfig 的定义如下

@lombok.Value
@lombok.Builder
static class SecurityConfig {
    String tokenUri;
    String clientId;
    String username;
    String password;
}

这是使用WireMock的完整测试

@Slf4j
@SpringBootTest(webEnvironment = NONE)
@AutoConfigureWireMock(port = 0) // random port
class WebClientTest {

    @Value("${wiremock.server.port}")
    private int wireMockPort;

    @Test
    void authClientTest() {
        String authResponse = """
                {
                  "token_type": "Bearer",
                  "expires_in": 3599,
                  "ext_expires_in": 3599,
                  "access_token": "token",
                  "refresh_token": "token"
                }""";

        stubFor(post(urlPathMatching("/token"))
                .withRequestBody(
                        containing("client_id=myclient2")
                                .and(containing("grant_type=password"))
                                .and(containing("password=password"))
                                .and(containing("username=username"))
                )
                .withHeader(HttpHeaders.CONTENT_TYPE, containing(MediaType.APPLICATION_FORM_URLENCODED.toString()))
                .willReturn(aResponse()
                        .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
                        .withStatus(200)
                        .withBody(authResponse)
                )
        );

        stubFor(get(urlPathMatching("/test"))
                .willReturn(aResponse()
                        .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
                        .withStatus(200)
                        .withBody("{}")
                )
        );

        SecurityConfig config = SecurityConfig.builder()
                .tokenUri("http://localhost:" + wireMockPort)
                .clientId("myclient2")
                .username("username")
                .password("password")
                .build();

        WebClient webClient = WebClient.builder()
                .baseUrl("http://localhost:" + wireMockPort)
                .filter(oauth("test", config))
                .build();

        Mono<String> request = webClient.get()
                .uri("/test")
                .retrieve()
                .bodyToMono(String.class);

        StepVerifier.create(request)
                .assertNext(res -> log.info("response: {}", res))
                .verifyComplete();
    }

    private ServerOAuth2AuthorizedClientExchangeFilterFunction oauth(
            String clientRegistrationId, SecurityConfig config) {
        var clientRegistration = ClientRegistration
                .withRegistrationId(clientRegistrationId)
                .clientAuthenticationMethod(ClientAuthenticationMethod.NONE)
                .tokenUri(config.getTokenUri() + "/token")
                .clientId(config.getClientId())
                .authorizationGrantType(AuthorizationGrantType.PASSWORD)
                .build();

        var authRepository = new InMemoryReactiveClientRegistrationRepository(clientRegistration);
        var authClientService = new InMemoryReactiveOAuth2AuthorizedClientService(authRepository);

        var authClientManager = new AuthorizedClientServiceReactiveOAuth2AuthorizedClientManager(
                authRepository, authClientService);

        var clientAuthProvider = new PasswordReactiveOAuth2AuthorizedClientProvider();
        authClientManager.setAuthorizedClientProvider(clientAuthProvider);
        authClientManager.setContextAttributesMapper(authorizeRequest ->  Mono.just(
                Map.of(
                        OAuth2AuthorizationContext.USERNAME_ATTRIBUTE_NAME, config.getUsername(),
                        OAuth2AuthorizationContext.PASSWORD_ATTRIBUTE_NAME, config.getPassword()
                )
        ));

        var oauth = new ServerOAuth2AuthorizedClientExchangeFilterFunction(authClientManager);
        oauth.setDefaultClientRegistrationId(clientRegistrationId);
        return oauth;
    }

    @lombok.Value
    @lombok.Builder
    static class SecurityConfig {
        String tokenUri;
        String clientId;
        String username;
        String password;
    }
}

关于spring-security - Spring security - 使用 WebClient 访问通过 Oauth2 "Password"授权类型保护的资源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75275169/

相关文章:

spring-boot - 如何使用 Spring WebClient get 从端点接收 Map<String, Integer>?

java - Oauth2 拒绝登录页面请求我该如何修复

spring - 如何在 Spring OAuth2 上更改 response_type

spring - 如何实现基于 View 的Spring Security链接?

Spring WebClient : What is the default multiplier for Retry. 退避?

spring-security - 使用 spring-security-oauth2-client 检索 facebook 个人资料信息

java - Spring OAuth2 自定义认证管理器 ClassCastException

java - 如何识别GET请求中地址中的参数是什么? request.getParameterMap() 总是返回 null

java - 基于 Spring Security token 的身份验证

Spring-Boot WebClient block() 方法返回错误 java.lang.IllegalStateException