繁体   English   中英

如何为 OAuth 2.0 设置密码授予凭证?

[英]How to set password grant credentials for OAuth 2.0?

我正在尝试设置 Spring WebClient 实例以使用 OAuth 2.0 身份验证和密码授予类型,但我不确定如何正确设置用户名和密码。

在我的应用程序中,相关参数以Map<String, String>的形式接收,而不是从任何application.yaml文件加载。 出于这个原因,我试图以编程方式进行(即,不使用 bean)——我的方法一开始可能是错误的。

这是我的非工作解决方案:

{
    OAuth20Info oAuth20Info = (OAuth20Info) parameters.getAuthenticationInfo();

    ClientRegistration registration = ClientRegistrations.fromOidcIssuerLocation(oAuth20Info.getHost() + ":" + oAuth20Info.getPort()) // host, port
        .clientId(oAuth20Info.getClientId()) // clientId
        .tokenUri(oAuth20Info.getTokenUrlPath()) // tokenUrlPath
        .authorizationGrantType(AuthorizationGrantType.PASSWORD) // grantType
        // TODO: How to set: username, password?
        .build();

    ReactiveClientRegistrationRepository clientRegistrations = new InMemoryReactiveClientRegistrationRepository(registration);

    ServerOAuth2AuthorizedClientExchangeFilterFunction oauth =
        new ServerOAuth2AuthorizedClientExchangeFilterFunction(
            clientRegistrations,
            new UnAuthenticatedServerOAuth2AuthorizedClientRepository());

    return WebClient.builder().filter(oauth).build();
}

因此,我不知道我需要在哪里设置用户名和密码。 据此:“最新的 OAuth 2.0 安全最佳当前实践完全不允许密码授予”,所以我不确定它是否受支持。

我希望能够在构建器中为ClientRegistration实例设置用户名和密码,但这是不可能的。

那么如何设置用户名和密码值以便使用密码授予类型凭据访问某些受保护的资源呢? 提前致谢。

我的依赖项的相关部分:

<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-webflux</artifactId>
  <version>5.2.3.RELEASE</version>
</dependency>
<dependency>
  <groupId>io.projectreactor.netty</groupId>
  <artifactId>reactor-netty</artifactId>
  <version>0.9.4.RELEASE</version>
</dependency>
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-web</artifactId>
  <version>5.1.7.RELEASE</version>
</dependency>
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-core</artifactId>
  <version>5.1.7.RELEASE</version>
</dependency>
<dependency>
  <groupId>org.springframework.security</groupId>
  <artifactId>spring-security-oauth2-client</artifactId>
  <version>5.2.2.RELEASE</version>
</dependency>
<dependency>
  <groupId>org.springframework.security.oauth</groupId>
  <artifactId>spring-security-oauth2</artifactId>
  <version>2.3.7.RELEASE</version>
</dependency>
<dependency>

你可以试试:

        WebClient.builder()
            .filter(ExchangeFilterFunctions
                .basicAuthentication(configuration.getClientId(), configuration.getClientSecret()))
            .build()
            .post()
            .uri(...)
            ...

您可以使用 ExchangeFilterFunctions class 将授权 header 添加到请求中。

另一种方式:

        WebClient.builder()
            .defaultHeaders(header -> header.setBasicAuth(userName, password))
            ...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM