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

时间:2015-10-22 19:09:21

标签: c# asp.net-mvc-5 owin google-authentication

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

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

当我检查进入谷歌身份验证的网址时,就是这样:

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

我正在尝试重定向到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);
    }
}

而且:

 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);
                    }
                }
            });

这两种方式令人惊讶,谷歌可以再次重定向到我的应用程序,但是,当我尝试获取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
        }

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

2 个答案:

答案 0 :(得分:0)

在研究了同一问题的不同变化之后,至少在我的特定情况下,我找到了解决方案。

通过负载均衡器托管在AWS EB上的MVC。

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
}

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

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

答案 1 :(得分:-1)

在您的Google Developers Console中,您配置了&#34;授权重定向URI。&#34;

您的URI应为&#34; https :// [您的域名] / signin-google&#34;

如果不是https,您的网站可能会丢失从Google传回的凭据信息,因为您在运行AccountController ExternalLoginCallback代码之前正在重定向到https。