Spring 5安全性OAuth2登录重定向循环

时间:2019-09-02 19:36:28

标签: java spring spring-boot spring-security 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"

这是我在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

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

  

本地主机将您重定向了太多次。

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

@Configuration
public class SpotifySecurityConfig extends WebSecurityConfigurerAdapter {

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

2 个答案:

答案 0 :(得分:2)

重定向循环是因为/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();
  }
}

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

  

IllegalArgumentException:redirectUriTemplate不能为空

要使用Spring的刷新令牌实现,我需要将redirect-uri设置为此:

redirect-uri: '{baseUrl}/login/oauth2/code/{registrationId}'

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

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

authorizationGrantType cannot be null in Spring Security 5 OAuth Client and Spring Boot 2.0

答案 1 :(得分:1)

尝试添加@ EnableOAuth2Sso批注:

@Configuration
@EnableOAuth2Sso
public class SpotifySecurityConfig extends WebSecurityConfigurerAdapter {

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