Spring Boot Oauth客户端在Google App Engine上不起作用

时间:2019-07-17 19:53:43

标签: spring spring-boot google-app-engine kotlin oauth-2.0

我有一个spring-boot-starter-oauth2-client的最小工作示例

  1. pom.xml
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-oauth2-client</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-oauth2-jose</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
  1. SecurityConfig
@Configuration
class SecurityConfig : WebSecurityConfigurerAdapter() {

    override fun configure(http: HttpSecurity) {
        http.authorizeRequests()
                .anyRequest().authenticated()
                .and()
                .oauth2Login()
    }

    override fun configure(web: WebSecurity?) {
        web?.ignoring()?.mvcMatchers("/actuator/health")
    }
}
  1. UserController
@RestController
@RequestMapping("/user")
class UserController {
    @GetMapping
    fun user(principal: Principal) : Principal {
        return principal
    }
}
  1. application.properties
spring.security.oauth2.client.registration.google.client-id=<client id>
spring.security.oauth2.client.registration.google.client-secret=<client secret>
  1. Google Cloud Platform配置

APIs & Services -> Credentials -> Oauth consent screen -> Authorized domains-我的应用程序上有dmain(<service>-dot-<project>.appspot.com

APIs & Services -> Credentials -> OAuth 2.0 client IDs-我的客户ID为:

Authorized redirect URIs

  • http://localhost:8080/login/oauth2/code/google
  • http://<service>-dot-<project>.appspot.com/login/oauth2/code/google

    1. App Engine配置

app.yaml

runtime: custom
env: flex
service: <my-service-name>
readiness_check:
  path: "/actuator/health"
  check_interval_sec: 5
  timeout_sec: 4
  failure_threshold: 4
  success_threshold: 2
  app_start_timeout_sec: 300
liveness_check:
  path: "/actuator/health"
  check_interval_sec: 30
  timeout_sec: 4
  failure_threshold: 2
  success_threshold: 2
resources:
  cpu: 1
  memory_gb: 2
  disk_size_gb: 10

和一个Dockerfile

FROM gcr.io/google-appengine/openjdk:8
COPY target/oauth-0.0.1-SNAPSHOT.jar $APP_DESTINATION

当我在localhost上运行该应用程序时,一切正常!没有戏!系统提示我使用Google电子邮件和密码登录,并且可以访问/ user端点。 但是,当我尝试在Google App Engine上部署相同的应用程序并访问/ user端点时,行为不一致: 有时我会收到由Spring Security生成的错误登录页面:

authorization_request_not_foundInvalid Credentials(单击Google按钮登录后)

Auth Request Not Found

Invalid Credentials

行为不同的原因可能是什么?

1 个答案:

答案 0 :(得分:0)

问题出在App Engine创建的多个实例中,并且我的应用程序无法在多个实例中正常运行。在当前设置下,登录信息存储在服务器的会话中,因此在多个实例中,负载均衡器可以将您发送到没有活动会话的实例。

我添加了:

manual_scaling:
  instances: 1

转到app.yaml,就可以了。

显然,正确的解决方法是使应用程序无状态。对此有待更新...