使用 Owin + OAuth + Google 在 ExternalLogin 上从 HTTP 重定向到 HTTPS

Fer*_*ndo 5 c# google-authentication owin asp.net-mvc-5

我的应用程序托管使用ARR将所有页面重定向到 HTTPS。

问题在于它的配置方式,ASP.Net MVC 理解请求是 HTTP,甚至是 HTTPS。

当我检查转到 google 身份验证的 URL 时,它是这样的:

&redirect_uri=http%3A%2F%mydomain.com\signing-google

我正在尝试重定向到谷歌,将“手动”更改为 HTTPS。

我试过这个:

public class ChallengeResult : HttpUnauthorizedResult
{
   ...

    public override void ExecuteResult(ControllerContext context)
    {
        var properties = new AuthenticationProperties { RedirectUri = RedirectUri };
        if (UserId != null)
            properties.Dictionary[XsrfKey] = UserId;

        var owin = context.HttpContext.GetOwinContext();

        owin.Request.Scheme = "https"; //hotfix

        owin.Authentication.Challenge(properties, LoginProvider);
    }
}
Run Code Online (Sandbox Code Playgroud)

和这个:

 app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
            {
                ClientId = Secrets.GoogleClientId,
                ClientSecret = Secrets.GoogleClientSecret,
                Provider = new GoogleOAuth2AuthenticationProvider()
                {
                    OnApplyRedirect = async context =>
                    {
                        string redirect = context.RedirectUri;

                        redirect = redirect.Replace("redirect_uri=http", "redirect_uri=https");
                        context.Response.Redirect(redirect);
                    }
                }
            });
Run Code Online (Sandbox Code Playgroud)

这两种方式都很奇怪,谷歌可以再次重定向到我的应用程序,但是,当我尝试获取loginInfo数据时,数据为空。

 public async Task<ActionResult> ExternalLoginCallback(string returnUrl)
    {
        if (string.IsNullOrEmpty(returnUrl))
            returnUrl = "~/";

        var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();
        if (loginInfo == null)
        {
            //always return null, if I change from HTTP to HTTPS manually
        }
Run Code Online (Sandbox Code Playgroud)

我试图查看GetExternalLoginInfoAsync()实现,但我没有找到,因为在我执行此解决方法时它总是返回 null。

JCo*_*ine 4

在查看同一问题的不同变体之后,我找到了解决方案,至少在我的特定场景中是这样。

MVC 托管在带有负载均衡器的 AWS EB 上。

public void ConfigureAuth(IAppBuilder app)
{
    app.Use((ctx, next) =>
    {
        ctx.Request.Scheme = "https";
        return next();
    });

    // your other middleware configuration

    // app.UseFacebookAuthentication();
    // app.UseGoogleAuthentication();

    // other providers
}
Run Code Online (Sandbox Code Playgroud)

我将 Use() 函数放在所有其他配置之前,可能只需要将其放在 OAuth 提供程序配置之上。

我的猜测是操纵redirect_uri回调数据的签名直接导致问题。