From 6a71b3403ab0d9c55870cc9efc951c929f1e7c85 Mon Sep 17 00:00:00 2001 From: "Brendan J. Baker" Date: Fri, 21 Sep 2018 20:06:40 -0400 Subject: [PATCH] Fix OAuth1 redirect URL when server is behind a proxy. This is the same fix for OAuth1AuthenticationService that was applied to OAuth2AuthenticationService in commit 385e7ca (SOCIAL-447). Specifically, if the "Host" header is present in the request, the "X-Forwarded-Proto" and "X-Forwarded-Port" headers are used to generate the callback URL. This is because a reverse proxy may receive a request via HTTPS on port 443, but an internal application server will see the request as coming via HTTP over port 8080 (for example), and that information will subsequently be used to generate an incorrect redirect URL. --- .../provider/OAuth1AuthenticationService.java | 29 ++++++++++++++++++- 1 file changed, 28 insertions(+), 1 deletion(-) diff --git a/spring-social-security/src/main/java/org/springframework/social/security/provider/OAuth1AuthenticationService.java b/spring-social-security/src/main/java/org/springframework/social/security/provider/OAuth1AuthenticationService.java index 6527785e3..b68d0d9a4 100644 --- a/spring-social-security/src/main/java/org/springframework/social/security/provider/OAuth1AuthenticationService.java +++ b/spring-social-security/src/main/java/org/springframework/social/security/provider/OAuth1AuthenticationService.java @@ -115,7 +115,7 @@ public SocialAuthenticationToken getAuthToken(HttpServletRequest request, HttpSe } protected String buildReturnToUrl(HttpServletRequest request) { - StringBuffer sb = request.getRequestURL(); + StringBuffer sb = getProxyHeaderAwareRequestURL(request); sb.append("?"); for (String name : getReturnToUrlParameters()) { @@ -134,6 +134,33 @@ protected String buildReturnToUrl(HttpServletRequest request) { return sb.toString(); } + protected StringBuffer getProxyHeaderAwareRequestURL(HttpServletRequest request) { + String host = request.getHeader("Host"); + if (StringUtils.isEmpty(host)) { + return request.getRequestURL(); + } + StringBuffer sb = new StringBuffer(); + String schemeHeader = request.getHeader("X-Forwarded-Proto"); + String portHeader = request.getHeader("X-Forwarded-Port"); + String scheme = StringUtils.isEmpty(schemeHeader) ? "http" : schemeHeader; + String port = StringUtils.isEmpty(portHeader) ? "80" : portHeader; + if (scheme.equals("http") && port.equals("80")){ + port = ""; + } + if (scheme.equals("https") && port.equals("443")){ + port = ""; + } + sb.append(scheme); + sb.append("://"); + sb.append(host); + if (StringUtils.hasLength(port)){ + sb.append(":"); + sb.append(port); + } + sb.append(request.getRequestURI()); + return sb; + } + private OAuthToken extractCachedRequestToken(HttpServletRequest request) { OAuthToken requestToken = (OAuthToken) request.getSession().getAttribute(OAUTH_TOKEN_ATTRIBUTE); request.getSession().removeAttribute(OAUTH_TOKEN_ATTRIBUTE);