oauth2 Nginx代理问题 (https->http)
-
最近在给系统正式环境部署用户认证时,登录出现问题。在本地开发环境中一切正常,但是一放到服务器就会认证失败,查看日志后发现
OAuth2
的redirectUri
参数不匹配 -
经了解springboot是通过 是通过
UrlUtils.buildFullRequestUrl(request)
从HttpServletRequest
中获取的redirectUri
:
OAuth2LoginAuthenticationFilter
String redirectUri = UriComponentsBuilder.fromHttpUrl(UrlUtils.buildFullRequestUrl(request))
.replaceQuery(null)
.build()
.toUriString();
- 服务器上配置了
nginx
作为反向代理服务器,这就导致了在Spring
中,无法正确获取scheme
和host
,这就导致了redirectUri
无法正确匹配从而认证失败。
解决问题
1:首先https转发代理http 协议,要支持跨域,并设置springboot的Tomcat的 protocol-header-https-value: “https” 为https
**Nginx **
proxy_set_header HOST $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
Tomcat
- 1.如果是springboot 内嵌的Tomcat ,application.yml 须配置一下参数
server:
tomcat:
remote-ip-header: "X-Forwarded-For"
protocol-header: "X-Forwarded-Proto"
protocol-header-https-value: "https
- 2.如果是Tomcat,配置以下参数就行
<Engine >
<Valve className="org.apache.catalina.valves.RemoteIpValve"
remoteIpHeader="X-Forwarded-For"
protocolHeader="X-Forwarded-Proto"
protocolHeaderHttpsValue="https"/>
</Engine >
什么解决了?当然还要注意最后一步。、
就是注意Nginx代理的前缀 :比如我现在是 https://craywen.top/pms
通过pms nginx 匹配路由 (^~ /pms ) 代理到http://127.0.0.1:8099 时
这个要注意,代码后的redirectUri
是会带上 pms的 ,有两种解决办法
1: 在Nginx 配置重定向url
rewrite ^/user/(.*)$ /$1 break;
proxy_pass http://user;
2:在oauth2 的白名单中添加 /pms
- 参考 https://www.jianshu.com/p/cf0056c64fa4