【问题标题】:Spring get actual scheme from reverse proxySpring从反向代理获取实际方案
【发布时间】:2019-01-25 07:29:44
【问题描述】:

我有一个在 Widfly 服务器上运行的 Spring Boot Web 应用程序。我通过生成链接到 Facebook 登录端点的“使用 Facebook 登录”按钮来实现 Facebook OAuth 登录。

https://www.facebook.com/v2.5/dialog/oauth?client_id=****&response_type=code&redirect_uri=http://example.com/login/facebook

我使用以下 java 代码生成 redirect_uri 的值。

public static String getFacebookRedirectUrl() {
    RequestAttributes attrs = RequestContextHolder.getRequestAttributes();
    if (attrs instanceof ServletRequestAttributes) {
        HttpServletRequest request = ((ServletRequestAttributes) attrs).getRequest();
        return request.getScheme() + "://"
                + request.getServerName() + ":"
                + request.getServerPort()
                + request.getContextPath()
                + "/login/facebook";
    } else {
        throw new RuntimeException("Cannot determine facebook oauth redirect url");
    }
}

我的网站在内部部署到 http://my-ip-address:8080,并有一个反向代理 (nginx) 将请求从 https://example.com 转发到 http://my-ip-address:8080

问题是redirect-uri 总是生成为http://example.com/login/facebook 而不是https://example.com/login/facebook(不是https)。

当用户通过https访问网站时,请帮助建议如何使request.getScheme()正确返回https。以下是反向代理配置/etc/nginx/sites-enalbed/mysite.com

server {
    listen 80;
    listen 443;
    server_name example.com www.example.com;

    ssl on;
    ssl_certificate         /etc/nginx/cert.crt;
    ssl_certificate_key     /etc/nginx/cert.key;


    location / {
        proxy_pass http://my-ip-address:8080;
        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;
    }
}

【问题讨论】:

    标签: spring redirect nginx https reverse-proxy


    【解决方案1】:

    request.getScheme() 将始终为 http,因为您通过 http 进行代理,但您在标头中传递请求方案,因此请使用它。

    return request.getScheme() + "://" 更改为return request.getHeader('X-Forwarded-Proto') + "://"

    不确定 java 是如何解释标头的,所以 X-Forwarded-Proto 可能会变成 X_Forwarded_ProtoxForwardedProto 或其他东西,但你明白了......

    【讨论】:

    • 感谢您的建议。不幸的是,我不能依赖标头,因为它特定于反向代理引擎。我在测试环境中使用 Nginx,但我无法控制生产环境和其他测试环境。
    猜你喜欢
    • 2020-02-20
    • 1970-01-01
    • 1970-01-01
    • 2012-12-05
    • 2011-11-30
    • 1970-01-01
    • 2018-07-12
    • 2017-08-03
    • 2016-04-11
    相关资源
    最近更新 更多