Spring Boot Google Oauth2所有请求都返回401 Unauthorized

时间:2018-03-28 20:19:26

标签: spring spring-boot oauth-2.0 google-oauth spring-security-oauth2

我有一个非常简单的Spring Boot应用程序,我希望所有页面都可以通过Google Oauth2进行身份验证。我按照Spring Oauth2 tuotrial查看了code under the /simple implementation。 (我的application.yml文件是为Google而不是FB设置的)

对我的应用程序的任何请求都会返回401 Unauthorized响应,并转到localhost:8080 / login ...(Spring安全自动生成的登录页面,在Google开发人员控制台中设置为重定向URI)

我已经查看过试图回答这个问题的所有其他问题,但没有一个问题有帮助。

我的申请类:

@SpringBootApplication
@EnableOAuth2Sso
@RestController
public class ControlApplication  extends WebSecurityConfigurerAdapter {

    public static void main(String[] args) {
        SpringApplication.run(ControlApplication.class, args);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.antMatcher("/**").authorizeRequests().anyRequest().authenticated().and().formLogin().defaultSuccessUrl("/", false);
    }

}

我的application.yml:

security:
  oauth2:
    client:
      clientId: [MyClientID]
      clientSecret: [MyClientSecret]
      accessTokenUri: https://accounts.google.com/o/auth2/token
      userAuthorizationUri: https://accounts.google.com/o/oauth2/auth?hd=xyz.com
      redirectUri: http://localhost:8080
      clientAuthenticationScheme: form
      tokenName: oauth_token
      authenticationScheme: query
      scope:
        - email
        - profile
    resource:
      userInfoUri: https://www.googleapis.com/oauth2/v3/userinfo
      preferTokenInfo: true

1 个答案:

答案 0 :(得分:1)

解决。 (最后!)在调用Google Auth API时,问题似乎是acessTokenUri的错误配置。工作配置:

  accessTokenUri: https://www.googleapis.com/oauth2/v4/token
  userAuthorizationUri: https://accounts.google.com/o/oauth2/v2/auth?hd=xyz.com
  clientAuthenticationScheme: form
  scope:
    - openid
    - email
    - profile
resource:
  userInfoUri: https://www.googleapis.com/oauth2/v3/userinfo
  preferTokenInfo: true