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

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

我的应用程序托管使用 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);
    }
}

还有这个:

 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。

最佳答案

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

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
}

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

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

关于c# - 使用 Owin + OAuth + Google 在 ExternalLogin 上从 HTTP 重定向到 HTTPS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33288829/

相关文章:

c# - 检索 Autofac 容器以解析服务

c# - 将 Http/2 与 ASP.NET 自托管 webapi 结合使用

c# - 网络 docker 容器上的 HttpClient 请求

C#:将 DataTable 传递给 SQL Server 非常慢

c# - 在 EF7 中添加多个相同类型的导航属性

c# - 为什么 EnumDropDownListFor 在 url 参数与模型中的字段相同时绑定(bind)不正确

c# - 在 MVC 5 的 Controller 中访问声明值

asp.net-mvc - 如何更改 Kendo MVC Treeview 的父字体

.net - 为什么 OWIN 的 SignInAsync() 不设置 IsAuthenticated (或其他身份验证变量)?

c# - XMLSerializer : Deserializing as derived type