使用令牌进行 Spring OAuth2 身份验证

时间:2021-02-09 10:16:30

标签: reactjs spring spring-boot oauth-2.0

我有这个 SpringBoot 应用程序,它通过 Google 使用 OAuth2 登录。而且它本身就可以正常工作。

但是,我正在尝试将其与我的 React 前端连接,因此:尝试开发令牌交换。

安全配置

http.cors()
      .and()
      .authorizeRequests()
      .antMatchers(HttpMethod.GET, "/oauth/**")
      .authenticated()
      .anyRequest()
      .permitAll()
      .and()
      .oauth2Login();

现在,我通过这种方式获取令牌:

OAuth2AuthorizedClient client = authorizedClientService.loadAuthorizedClient(authentication.getAuthorizedClientRegistrationId(), authentication.getName());
String token = client.getAccessToken().getTokenValue();

并将其发送给我的 React 客户端。

问题是:如何在 SpringBoot 应用中接收和解释授权令牌? 现在,只要我附加 Authoriation 标头,它就会给我一个 CORS 问题...

1 个答案:

答案 0 :(得分:0)

您必须在您的 Spring Boot 应用程序中配置允许的 CORS 请求,或者为您的 React 前端提供来自同一域的服务。

我个人总是选择第二个选项,Spring Boot 应用程序在某些 url(例如 /static/js/)上提供 react 包。