19

我决定试一试新的 Google Oauth2 中间件,它几乎破坏了一切。这是我来自 startup.auth.cs 的提供程序配置。打开后,包括 google 提供程序在内的所有提供程序都会在 Challenge 上获得 500 个内部服务器。但是,内部服务器错误的详细信息不可用,我无法弄清楚如何为 Katana 中间件打开任何调试或跟踪。在我看来,他们似乎急于将 google Oauth 中间件推出市场。

  //// GOOGLE
        var googleOptions = new GoogleOAuth2AuthenticationOptions
        {
            ClientId = "228",
            ClientSecret = "k",
            CallbackPath = new PathString("/users/epsignin")
            SignInAsAuthenticationType = DefaultAuthenticationTypes.ExternalCookie,
            Provider = new GoogleOAuth2AuthenticationProvider
            {
                OnAuthenticated = context =>
                {
                    foreach (var x in context.User)
                    {
                        string claimType = string.Format("urn:google:{0}", x.Key);
                        string claimValue = x.Value.ToString();
                        if (!context.Identity.HasClaim(claimType, claimValue))
                            context.Identity.AddClaim(new Claim(claimType, claimValue, XmlSchemaString, "Google"));
                    }
                    return Task.FromResult(0);
                }
            }
        };

        app.UseGoogleAuthentication(googleOptions);

动作方法代码:

 [AllowAnonymous]
    public ActionResult ExternalProviderSignIn(string provider, string returnUrl)
    {
       var ctx = Request.GetOwinContext();
        ctx.Authentication.Challenge(
            new AuthenticationProperties
            {
                RedirectUri = Url.Action("EPSignIn", new { provider })
            },
            provider);
        return new HttpUnauthorizedResult();
    }
4

5 回答 5

28

这花了我几个小时才弄清楚,但问题是CallbackPath@CrazyCoder 提到的。我意识到CallbackPathinpublic void ConfigureAuth(IAppBuilder app) 必须与在ChallengeResult. 如果它们相同,则会在 OWIN 中引发 500 错误。

我的代码ConfigureAuth(IAppBuilder app)

var googleOptions = new Microsoft.Owin.Security.Google.GoogleOAuth2AuthenticationOptions
{
    ClientId = "xxx",
    ClientSecret = "yyy",
    CallbackPath = new PathString("/callbacks/google"), //this is never called by MVC, but needs to be registered at your oAuth provider

    Provider = new GoogleOAuth2AuthenticationProvider
    {
        OnAuthenticated = (context) =>
        {
            context.Identity.AddClaim(new Claim("picture", context.User.GetValue("picture").ToString()));
            context.Identity.AddClaim(new Claim("profile", context.User.GetValue("profile").ToString()));
            return Task.FromResult(0);
        }      
    }
};

googleOptions.Scope.Add("email");

app.UseGoogleAuthentication(googleOptions);

我的“回调”控制器代码是:

// GET: /callbacks/googlereturn - callback Action
[AllowAnonymous]
public async Task<ActionResult> googlereturn()
{
        return View();
}

//POST: /Account/GooglePlus
public ActionResult GooglePlus()
{
    return new ChallengeResult("Google", Request.Url.GetLeftPart(UriPartial.Authority) + "/callbacks/googlereturn", null);  
    //Needs to be a path to an Action that will handle the oAuth Provider callback
}

private class ChallengeResult : HttpUnauthorizedResult
{
    public ChallengeResult(string provider, string redirectUri)
        : this(provider, redirectUri, null)
    {
    }

    public ChallengeResult(string provider, string redirectUri, string userId)
    {
        LoginProvider = provider;
        RedirectUri = redirectUri;
        UserId = userId;
    }

    public string LoginProvider { get; set; }
    public string RedirectUri { get; set; }
    public string UserId { get; set; }

    public override void ExecuteResult(ControllerContext context)
    {
        var properties = new AuthenticationProperties() { RedirectUri = RedirectUri };
        if (UserId != null)
        {
            properties.Dictionary[XsrfKey] = UserId;
        }
        context.HttpContext.GetOwinContext().Authentication.Challenge(properties, LoginProvider);
    }
}
  • 回调/谷歌似乎由 OWIN 处理
  • 回调/googlereturn 似乎由 MVC 处理

现在一切正常,虽然很想知道“引擎盖下”到底发生了什么

除非您有其他要求,否则我的建议是让 OWIN 使用默认重定向路径并确保您自己不使用它们。

于 2014-05-11T17:40:32.017 回答
7

无需在 中CallbackPath指定UseGoogleAuthentication

CallbackPath = new PathString("/Account/ExternalLoginCallback")

只需将授权重定向的 Google 设置保留URIs为:

http(s)://yoururl:orPort/登录-google

Owin 在内部处理 signin-google 并重定向到您在 ChallengeResult 类的代码中提到的 redirectUri。这是帐户/外部登录回调。

于 2015-08-05T07:46:05.447 回答
3

通过一个简单的更改从教程中得到它的工作香草 - 只需将这个发布到任何使用这种方法的 nubes 。我认为在这种情况下与 oauth2 相关的问题在很大程度上体现在最新的模板/api 中——我的意思是,如果你从头开始,你可能很幸运——继续阅读:

我刚刚完成了本教程 https://azure.microsoft.com/en-us/documentation/articles/web-sites-dotnet-deploy-aspnet-mvc-app-membership-oauth-sql-database/

并引用了这个 http://blogs.msdn.com/b/webdev/archive/2014/07/02/changes-to-google-oauth-2-0-and-updates-in-google-middleware-for- 3-0-0-rc-release.aspx

一个变化: 它有效,但只有在最新版本的谷歌开发者网站中启用 google+ api 之后。

(只需转到 google api lib manager,登录并在 apis 目录中搜索 google+ api)。
注意:对我来说,Google+ api 默认是禁用的。

我没有做任何其他独特的事情。

干杯

于 2016-01-11T18:04:02.963 回答
1

到目前为止给出的答案让我走上了一条我希望我没有走过的非常黑暗的道路......解决方案很简单,确保以下三件事匹配:

1) 在 Google OATH 凭证 ( https://console.developers.google.com/ ) 中:

2)在你的AccountController

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult ExternalLogin(string provider, string returnUrl)
{
    return new ChallengeResult(provider, 
        Url.Action("ExternalLoginCallback", "Account", 
        new { ReturnUrl = returnUrl }));
}

注意动作是“ExternalLoginCallback”

3) 在你的App_Start\Startup.Auth.cs

app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
{
    ClientId = "yourclientid.apps.googleusercontent.com",
    ClientSecret = "yoursecret",
    Provider = new GoogleOAuth2AuthenticationProvider(),
    CallbackPath = new PathString("/Account/ExternalLoginCallback")
});

请注意,CallbackPath再次PathString与其他 2相同

最后,如果您仍然没有得到它,请在您的应用中将您的身份验证模式设置为无Web.config

<authentication mode="None" />

获取有关该问题的更多详细信息。

于 2015-03-01T10:43:23.333 回答
0

为简单起见,我使用带有身份验证的默认 ASP.NET MVC 5 模板,但希望可以针对不同的用例进行修改。

启动验证.cs

不要自定义重定向路径。无论如何,它都会被 /signin-google 取代,而我试图解决这个问题会导致“静默”(不在调试器中)内部服务器 500 错误。

app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
{
    ClientId = "whatevs.apps.googleusercontent.com",
    ClientSecret = "whatevs_secrut",
    Provider = new GoogleOAuth2AuthenticationProvider()
});

确保在您的> >部分中将http://whatever.com/signin-google添加到https://console.developers.google.com/ 。APIs & authCredentialsRedirect URIs

路由配置.cs

将路由添加到您的路由的永久重定向控制器操作。永久重定向是这里唯一足够的东西。仅仅直接指向回调 URL 是不够的。

public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

    routes.MapRoute(
        name: "Google API Sign-in",
        url: "signin-google",
        defaults: new { controller = "Account", action = "ExternalLoginCallbackRedirect" }
    );

    routes.MapRoute(
        name: "Default",
        url: "{controller}/{action}/{id}",
        defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
    );
}

AccountController.cs

永久重定向到内置回调方法,你应该没问题。

[AllowAnonymous]
public ActionResult ExternalLoginCallbackRedirect(string returnUrl)
{
    return RedirectPermanent("/Account/ExternalLoginCallback");
}

已经在 GitHub 上发布了一个模板项目供参考: https ://github.com/Pritchard/Test-AspNetGoogleOAuth2Authentication

于 2015-02-26T05:35:23.890 回答