如何使用SpringBootWebClient访问oauth2安全RESTAPI

hfsqlsce  于 2021-08-25  发布在  Java
关注(0)|答案(0)|浏览(389)

我需要使用oauth2保护RESTAPI。授权授予类型为密码。在获得访问令牌后,我应该使用它请求安全的资源。主要思想是我需要在访问令牌过期时自动获取并刷新它。我认为它不应该保存在会话或数据库中的某个地方。因为spring security 5.2.*提供了这种开箱即用的机会。为了做到这一点,我跟随了这篇文章。
当我运行应用程序时,它一直说我没有授权,即使我在application.yml中指定了属性。

021-07-06 16:33:15.292  INFO 25636 --- [           main] d.e.o.Oauth2clientApplication            : Starting Oauth2clientApplication using Java 15.0.1 on F-LAPASOV with PID 25636 (C:\Users\f.lapasov\IdeaProjects\logwso2\oauth2client\target\classes started by f.lapasov in C:\Users\f.lapasov\IdeaProjects\logwso2\oauth2client)
2021-07-06 16:33:15.294  INFO 25636 --- [           main] d.e.o.Oauth2clientApplication            : No active profile set, falling back to default profiles: default
2021-07-06 16:33:15.924  INFO 25636 --- [           main] ctiveUserDetailsServiceAutoConfiguration : 

Using generated security password: 8bd88c3a-37c6-45b6-9721-ceca17e8e0bf

2021-07-06 16:33:16.173  INFO 25636 --- [           main] o.s.b.web.embedded.netty.NettyWebServer  : Netty started on port 9797
2021-07-06 16:33:16.181  INFO 25636 --- [           main] d.e.o.Oauth2clientApplication            : Started Oauth2clientApplication in 1.168 seconds (JVM running for 1.613)
2021-07-06 16:33:16.359  INFO 25636 --- [           main] ConditionEvaluationReportLoggingListener : 

Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2021-07-06 16:33:16.375 ERROR 25636 --- [           main] o.s.boot.SpringApplication               : Application run failed

java.lang.IllegalStateException: Failed to execute CommandLineRunner
    at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:794) ~[spring-boot-2.5.2.jar:2.5.2]
    at org.springframework.boot.SpringApplication.callRunners(SpringApplication.java:775) ~[spring-boot-2.5.2.jar:2.5.2]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:345) ~[spring-boot-2.5.2.jar:2.5.2]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1343) ~[spring-boot-2.5.2.jar:2.5.2]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1332) ~[spring-boot-2.5.2.jar:2.5.2]
    at dev.egov.oauth2client.Oauth2clientApplication.main(Oauth2clientApplication.java:17) ~[classes/:na]
Caused by: org.springframework.web.reactive.function.client.WebClientResponseException$Unauthorized: 401 Unauthorized from GET http://ip:808/app/rest/v2/services/student/get?pin=123456789
    at org.springframework.web.reactive.function.client.WebClientResponseException.create(WebClientResponseException.java:198) ~[spring-webflux-5.3.8.jar:5.3.8]
    Suppressed: reactor.core.publisher.FluxOnAssembly$OnAssemblyException: 
Error has been observed at the following site(s):
    |_ checkpoint ⇢ 401 from GET http://ip:808/app/rest/v2/services/student/get?pinfl=1234567898 [DefaultWebClient]
Stack trace:
        at org.springframework.web.reactive.function.client.WebClientResponseException.create(WebClientResponseException.java:198) ~[spring-webflux-5.3.8.jar:5.3.8]
      *******************************

下面给出了pom.xml文件的片段


**************

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

    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <optional>true</optional>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
   **************

属性文件如下所示:

spring:
  security:
    oauth2:
      client:
        registration:
          bael:
            client-id: client
            client-secret: secret
            authorization-grant-type: password
        provider:
          bael:
            token-uri: http://ip:port/app/rest/v2/oauth/token
server:
  port: 9797

webclient的配置类:

@Configuration
public class WebClientConfig {

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

我的服务级别:

@Service
public class WebClientService {
    @Autowired
    private WebClient webClient;

    public String callApi(ApiRequest apiRequest) {
        return webClient
                .get()
                .uri("http://ip:port/app/rest/v2/services/student/get",uriBuilder ->
                        uriBuilder
                                .queryParam("pin", apiRequest.getPinfl()).build()
                )
                .attributes(ServerOAuth2AuthorizedClientExchangeFilterFunction.clientRegistrationId("bael"))
                .retrieve()
                .bodyToMono(String.class).block();
    }
}

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题