Java Spring部署EC2后Google OAuth2.0回调redirect_uri不匹配问题
问题排查与解决建议
1. 核对Google Cloud控制台的redirect_uri配置
- 登录Google Cloud Console找到你的OAuth 2.0客户端ID,必须精确添加
https://example.com:8888/Callback,协议、域名、端口、路径一个都不能错。 - 删除之前添加的HTTP版本redirect_uri,避免Google校验时出现混淆。
2. 修正LocalServerReceiver的HTTPS配置
LocalServerReceiver默认启动HTTP服务器,这会导致实际回调使用HTTP协议,和你配置的HTTPS redirect_uri不匹配。需要手动配置SSL:
// 加载Let's Encrypt生成的PKCS12证书 KeyStore keyStore = KeyStore.getInstance("PKCS12"); try (InputStream is = new FileInputStream("/path/to/your/letsencrypt.p12")) { keyStore.load(is, "your-keystore-password".toCharArray()); } LocalServerReceiver receiver = new LocalServerReceiver.Builder() .setHost("example.com") .setPort(8888) .setCallbackPath("/Callback") // 配置SSL上下文,让接收器使用HTTPS .setSslContext(SslContexts.custom() .loadKeyMaterial(keyStore, "your-keystore-password".toCharArray()) .build()) .build();
3. 检查EC2端口与防火墙配置
- 在EC2安全组中开放8888端口的TCP入站规则,测试阶段可允许所有IP,生产环境建议限制Google相关IP段。
- 配置EC2本地防火墙放行8888端口:
# firewalld方式 sudo firewall-cmd --add-port=8888/tcp --permanent sudo firewall-cmd --reload # iptables方式 sudo iptables -A INPUT -p tcp --dport 8888 -j ACCEPT sudo service iptables save
4. 改用Spring OAuth2原生回调机制(推荐服务器部署)
LocalServerReceiver更适合本地开发,服务器部署建议用Spring自带的OAuth2回调,避免手动管理端口和SSL:
- 修改
application.properties:server.port=443 server.ssl.key-store=/path/to/my/key-store server.ssl.key-store-password=my-password server.ssl.key-store-type=PKCS12 # 指定HTTPS回调地址 spring.security.oauth2.client.registration.google.redirect-uri=https://example.com/login/oauth2/code/google # 或者用占位符自动适配:{baseUrl}/login/oauth2/code/{registrationId} - 移除LocalServerReceiver代码,通过
@RegisteredOAuth2AuthorizedClient或OAuth2AuthorizedClientService获取授权客户端,对接Google Sheet API。
5. Nginx反向代理的正确配置(如需)
如果要用Nginx做代理隐藏端口,配置如下(避免之前的错误配置导致页面无法加载):
server { listen 443 ssl; server_name example.com; ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem; ssl_protocols TLSv1.2 TLSv1.3; ssl_ciphers HIGH:!aNULL:!MD5; # 转发回调请求到LocalServerReceiver的8888端口 location /Callback { proxy_pass https://localhost:8888/Callback; proxy_set_header X-Forwarded-For $remote_addr; proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header Host $host; } # 转发主页面到Spring应用的443端口 location / { proxy_pass https://localhost:443; proxy_set_header X-Forwarded-For $remote_addr; proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header Host $host; } } # HTTP请求强制跳转到HTTPS server { listen 80; server_name example.com; return 301 https://$server_name$request_uri; }
配置后重启Nginx:
sudo systemctl restart nginx
同时在Spring配置中添加:
server.forward-headers-strategy=framework
让Spring识别Nginx传递的X-Forwarded-Proto头,确保回调地址协议正确。
内容的提问来源于stack exchange,提问作者JxDev
相关产品推荐
相关产品推荐

