Spring 5 Security OAuth2 登录重定向循环

Geo*_*rge 7 java spring spring-security spring-boot spring-security-oauth2

我想使用 Spotify Web API,但我在 Spring Security Configuration 方面遇到了问题。这是我的安全依赖项:

 /* springBootVersion = '2.1.2.RELEASE' */
implementation "org.springframework.security:spring-security-oauth2-client"
implementation 'org.springframework.security:spring-security-oauth2-jose:5.1.6.RELEASE'
implementation "org.springframework.security.oauth.boot:spring-security-oauth2-autoconfigure:2.1.7.RELEASE"
Run Code Online (Sandbox Code Playgroud)

这是我application.yml文件中的安全性:

spring:
  security:
    oauth2:
      client:
        registration:
          spotify:
            provider: spotify-provider
            client-id: <client-id>
            client-secret: <client-secret>
            client-authentication-method: basic
            authorization-grant-type: authorization_code
            redirect-uri: http://localhost:8080/
            scope: <comma delimited scopes>
        provider:
          spotify-provider:
            authorization-uri: https://accounts.spotify.com/authorize
            token-uri: https://accounts.spotify.com/api/token
            user-info-uri: https://api.spotify.com/v1/me
Run Code Online (Sandbox Code Playgroud)

我的问题是,在我登录并重定向回我的应用程序后,它卡在 URL 上http://localhost:8080/oauth2/authorization/spotify并显示错误

localhost 将您重定向了太多次。

这是我的 java 安全配置的样子:

@Configuration
public class SpotifySecurityConfig extends WebSecurityConfigurerAdapter {

  @Override
  protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests()
            .anyRequest()
            .authenticated()
            .and()
            .oauth2Login();
  }
}
Run Code Online (Sandbox Code Playgroud)

Geo*_*rge 6

重定向循环是因为/oauth2/authorization/端点是安全的,因此它触发返回到 Web API 以获取访问令牌。

我已将我的配置更新为:

@Configuration
public class SpotifySecurityConfig extends WebSecurityConfigurerAdapter {

  @Override
  protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests()
            .antMatchers("/home", "/login**","/callback/", "/webjars/**", "/error**", "/oauth2/authorization/**")
            .permitAll()
            .anyRequest()
            .authenticated()
            .and()
            .oauth2Login();
  }
}
Run Code Online (Sandbox Code Playgroud)

第二个问题是redirect-uriWeb API 将访问令牌发送到 Spring 以用于获取刷新令牌的 URI。我以为是登录成功。Spring 已经有处理刷新令牌的实现,但我不知道它应该使用什么端点。出于某种原因,redirect-uri 不能为空,没有默认值,我会收到此错误:

IllegalArgumentException:redirectUriTemplate 不能为空

要使用 Spring 的刷新令牌实现,我需要将重定向 uri 设置为:

redirect-uri: '{baseUrl}/login/oauth2/code/{registrationId}'
Run Code Online (Sandbox Code Playgroud)

redirect-uri-templateredirect-uri(它们是同一个变量)的别名。

redirect-uri在另一个stackoverflow帖子中找到了:

在 Spring Security 5 OAuth Client 和 Spring Boot 2.0 中,authorizationGrantType 不能为 null