最近在給 Docs4dev 添加用戶評論功能時,使用了 Github 提供的 OAuth2 認證來進行用戶身份認證,在本地開發(fā)環(huán)境中一切正常,但是一放到服務(wù)器就會認證失敗,查看日志后發(fā)現(xiàn) OAuth2 的 redirectUri 參數(shù)不匹配,在添加了相關(guān)日志后,發(fā)現(xiàn) Spring Boot 是通過 UrlUtils.buildFullRequestUrl(request) 從 HttpServletRequest 中獲取的 redirectUri :
OAuth2LoginAuthenticationFilter
String redirectUri = UriComponentsBuilder.fromHttpUrl(UrlUtils.buildFullRequestUrl(request))
.replaceQuery(null)
.build()
.toUriString();
但是,服務(wù)器上配置了 nginx 作為反向代理服務(wù)器,這就導致了在 Spring 中,無法正確獲取 scheme 和 host,這就導致了 redirectUri 無法正確匹配從而認證失敗。
找到了問題,解決它就很簡單了,我們只需要對 nginx 和 tomcat 進行簡單的設(shè)置就行了。
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
<Engine >
<Valve className="org.apache.catalina.valves.RemoteIpValve"
remoteIpHeader="X-Forwarded-For"
protocolHeader="X-Forwarded-Proto"
protocolHeaderHttpsValue="https"/>
</Engine >
如果你使用的是 Spring Boot 內(nèi)嵌的 Tomcat,可以在 application.yml 中進行設(shè)置:
server:
tomcat:
remote-ip-header: "X-Forwarded-For"
protocol-header: "X-Forwarded-Proto"
protocol-header-https-value: "https"
以上的設(shè)置只是為了讓 Tomcat 能獲取正確的 host 以及 schme ,這樣,Spring 就能獲取正確的 redirectUri 參數(shù)了。