在spring webflux中的webClient实例化期间如何设置访问令牌一次?

问题描述 投票:0回答:1

我尝试在春季webflux中将WebClient与oauth2一起使用。我从url访问令牌中获取令牌,并将其设置到webclient中。但是我不喜欢在其他安全端点的每次调用中都获取此访问令牌。意味着我只想在Web客户端实例化期间以及访问令牌到期时才第一次获取它。

这里是我正在使用的代码:

@Configuration
public class OauthEmployeConfig{

    /**
    ** ... String baseUrl, String accessUrl for the access token url
    **/

    @Bean
    public WebClient webClient(UserRegistration userRegistr) {

        ClientRequest clientRequest = ClientRequest
            .create(HttpMethod.POST, URI.create(accessUrl))
            .header(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE)
            .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED_VALUE)
            .headers(headers -> headers.setBasicAuth(userRegistr.getClientId(), userRegistr.getClientSecret()))
            .body(BodyInserters.fromFormData("grant_type", userRegistr.getAuthorizGrantType())
                .with("scope", userRegistr.getScope().replaceAll(",", "")))
            .build();

        return WebClient.builder()
            .baseUrl(baseUrl)
            .defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
            .defaultHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE)
            .filter((request, next) -> next.exchange(clientRequest)
                .flatMap(response -> response.body(org.springframework.security.oauth2.core.web.reactive.function.OAuth2BodyExtractors.oauth2AccessTokenResponse()))
                .map(accessToken -> accessToken.getAccessToken().getTokenValue())
                .map(token -> setBearer(request, token))
                .flatMap(next::exchange))
            .filter(logRequest())
            .filter(handleResponseError())
            .build();
    }

    private ClientRequest setBearer(ClientRequest request, String token) {
    return ClientRequest.from(request)
        .header("Authorization", "Bearer " + token).build();
    }


    private static ExchangeFilterFunction handleResponseError() {
        return ExchangeFilterFunction.ofResponseProcessor(
            response -> response.statusCode().isError()
                ? response.bodyToMono(String.class)
                    .flatMap(errorBody -> Mono.error(new RuntimeException(errorBody, response.statusCode())))
                : Mono.just(response));
    }

     private static ExchangeFilterFunction logRequest() {
        return ExchangeFilterFunction.ofRequestProcessor(clientRequest -> {
          clientRequest.headers().forEach((name, values) -> values.forEach(value -> LOG.info("{}={}", name, value)));
          return Mono.just(clientRequest);
        });
    }
}
spring-boot spring-security spring-security-oauth2 spring-webflux spring-webclient
1个回答
0
投票

我遵循了this toturial,因此我必须更改代码。

所以我的代码看起来像:

application.properties]

spring.security.oauth2.client.registration.chris.authorization-grant-type=client_credentials
spring.security.oauth2.client.registration.chris.client-id=chris-client-id
spring.security.oauth2.client.registration.chris.client-secret=chris-secret

spring.security.oauth2.client.provider.chris.token-uri=http://localhost:8085/oauth/token

Configuration类:]

@Configuration
   public SecurityConfig {

    @Bean
    WebClient webClient(ReactiveClientRegistrationRepository clientRegistrations) {
     ServerOAuth2AuthorizedClientExchangeFilterFunction oauth =
      new ServerOAuth2AuthorizedClientExchangeFilterFunction(
       clientRegistrations,
       new UnAuthenticatedServerOAuth2AuthorizedClientRepository());
     oauth.setDefaultClientRegistrationId("chris");
     return WebClient.builder()
      .filter(oauth)
      .filter(logRequest())
      .filter(handleResponseError())
      .build();
    }

    private static ExchangeFilterFunction handleResponseError() {
     return ExchangeFilterFunction.ofResponseProcessor(
      response -> response.statusCode().isError() ?
      response.bodyToMono(String.class)
      .flatMap(errorBody -> Mono.error(new RunTimeException(errorBody, response.statusCode()))) :
      Mono.just(response));
    }

    private static ExchangeFilterFunction logRequest() {
     return ExchangeFilterFunction.ofRequestProcessor(clientRequest -> {
         // To log the headers details like Token ...
      clientRequest.headers().forEach((name, values) -> values.forEach(value -> LOGGER.info("{}={}", name, value)));
      return Mono.just(clientRequest);
     });
    }
   }

通过网络客户端拨打电话:

...
webClient.get()
  .uri("http://localhost:8084/retrieve-resource")
  .attributes(
    ServerOAuth2AuthorizedClientExchangeFilterFunction
      .clientRegistrationId("chris")) // With this, automatically will be able to see your token in the header : Bearer wxopyav....
  .retrieve()
...
© www.soinside.com 2019 - 2024. All rights reserved.