首页 > 解决方案 > GoogleOAuth2AuthenticationHandler + SSL 终止 - redirect_uri_mismatch

问题描述

我在 HAProxy 之后隐藏了一个应用程序。

存在 SSL 终止。我的应用程序是https://myapp.domain.com但在 HttpContext.Request 应用程序中将其识别为http://myapp.domain.com(没有 SSL,因为它在代理级别终止)。

问题是我使用 Microsoft.Owin.Security.Google 库。当它使用 http 而不是 https 生成 redirect_uri 时。

我检查了 GoogleOAuth2AuthenticationHandler => ApplyResponseChallengeAsync() 方法的实现,它清楚地表明这个 redirect_uri 是从服务器端数据生成的:

    string str1 = this.Request.Scheme + Uri.SchemeDelimiter + (object) this.Request.Host + (object) this.Request.PathBase;
    string str2 = str1 + (object) this.Request.Path + (object) this.Request.QueryString;
    string str3 = str1 + (object) this.Options.CallbackPath;

问题是如何强制该提供者获取有效的 url 方案?

标签: c#asp.net-mvcauthenticationoauth

解决方案


我找到了解决我的问题的方法。此上下文中的Request.Scheme不是HttpRequest而是IOwinRequest

它可以在 Startup.cs 文件中全局覆盖:

    app.Use((context, next) =>
    {
        context.Request.Scheme = context.Request.GetRealScheme(true);
        return next();
    });

其中GetRealScheme()是我的扩展方法:

    private const string HeaderProtoKey = "X-Forwarded-Proto";

    public static string GetRealScheme(this IOwinRequest request, bool skipPostfix = false)
    {
        if (request == null)
            return null;

        string headerProtocol = request.Headers[HeaderProtoKey] ?? string.Empty;

        string result = headerProtocol.ToLower().Contains("https")
            ? "https://"
            : request.Scheme;

        return skipPostfix
            ? result.Replace("://", string.Empty)
            : result;
    }

需要注意的一件重要事情!

此代码应在身份验证设置之前应用。


推荐阅读