最近在給 Docs4dev 添加用戶評論功能時(shí)枫浙,使用了 Github
提供的 OAuth2
認(rèn)證來進(jìn)行用戶身份認(rèn)證,在本地開發(fā)環(huán)境中一切正常棺聊,但是一放到服務(wù)器就會(huì)認(rèn)證失敗,查看日志后發(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ù)器裸弦,這就導(dǎo)致了在 Spring
中祟同,無法正確獲取 scheme
和 host
,這就導(dǎo)致了 redirectUri
無法正確匹配從而認(rèn)證失敗理疙。
找到了問題晕城,解決它就很簡單了,我們只需要對 nginx
和 tomcat
進(jìn)行簡單的設(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
中進(jìn)行設(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ù)了滤蝠。