2014-02-23 38 views
16

我决定尝试新的Google Oauth2中间件,它几乎破坏了所有内容。这是我从startup.auth.cs提供的配置文件。打开时,包括Google提供程序在内的所有提供程序都会在挑战中获得500个内部服务器。但是,内部服务器错误的细节不可用,我不知道如何打开Katana中间件的任何调试或跟踪。对我来说,就像他们急于将Google Oauth中间件出门一样。GoogleOauth2问题获取内部服务器500错误

//// GOOGLE 
     var googleOptions = new GoogleOAuth2AuthenticationOptions 
     { 
      ClientId = "228", 
      ClientSecret = "k", 
      CallbackPath = new PathString("https://stackoverflow.com/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); 

ActionMethod代码:

[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(); 
    } 
+0

我不确定具体问题是什么 - 您可以尝试设置Google软件包的符号并查看它出错的位置。以下是一些设置katana符号的说明 - https://katanaproject.codeplex.com/wikipage?title=Debugging&referringTitle=Documentation – Praburaj

+0

这似乎是CallBackPath的一个问题。是否有可能为此提供商设置回叫路径时,它将为所有提供商全局设置该支持。没有深入src,只是一个想法... – CrazyCoderz

+0

当你说全球所有提供商的道具=>你想同样为所有提供者设置?没有办法为所有提供者自动设置相同的内容,但如果需要,可以手动设置它们。你应该确保你有这个redirect uri被注册到各个门户的相应应用程序设置中。如果您没有明确提供一个中间件,则每个中间件都有默认的CallBackPath。例如,这个谷歌中间件的默认值是/ signin-google。 – Praburaj

回答

26

这花了我小时弄清楚,但问题是由@CrazyCoder提到CallbackPath。我意识到CallbackPath中的public 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使用默认的重定向路径,并确保你不自己使用它们。

+0

对不起,我忘了很久以前回答。 – CrazyCoderz

+0

他们仍然没有固定的方式工作 – CrazyCoderz

+0

澄清什么解决了这个问题: 1)重定向URL设置在account.live.com应用程序区域(API设置)被设置为“http:// /帐户/ MicrosoftLoginCallback“ 2)回调路径设置为”PathString(“/ Account/MicrosoftLoginCallback”);“对于IAppBuilder: app.UseMicrosoftAccountAuthentication(新MicrosoftAccountAuthenticationOptions {CallbackPath = msCallbackPath,ClientId =,ClientSecret =} 3)用于挑战的RedirectUri必须从“MicrosoftLoginCallback”更改为“MSLoginCallback”,仅在AccountController操作和身份验证中。挑战()呼叫。 –

0

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

StartupAuth.cs

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

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

确保在您的APIs & auth>Credentials>Redirect URIs部分添加http://whatever.com/signin-googlehttps://console.developers.google.com/

RouteConfig.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

+1

这个答案是错误的。/ signin-google由OWIN处理,无论您是否添加此路由,它都会被忽略; OWIN在MVC路由首先会触及它之前处理请求。 OWIN在处理/ signin-google网址时不需要任何帮助 - 这不是问题。 –

+0

@ChrisMoschini请不要说这是不正确的,除非你真的尝试过。我有,它的工作原理,这就是为什么我不仅发布了对这个问题的回应,而且还将解决方案上传到了GitHub。重点在于,在ASP.NET MVC中,您仍然需要控制器操作来处理身份验证响应,并且向Microsoft提供的示例中提供自定义重定向路径到OWIN提供程序不起作用。我不是“帮助”OWIN找到/登录谷歌。我正在帮助HTTP管道将其自身重定向到Account/ExternalLoginCallbackRedirect。 –

+0

@ChrisMoschini为了澄清,您可以改为实施“Home/signin-google”的控制器操作。此答案解决的问题是重定向到其他控制器操作,这不能通过向OWIN提供程序提供重定向URI来完成。无论您给提供者什么URI,它都会被框架自动覆盖到'/ signin-google'。我希望澄清这个答案的目的,我将以善意为由假定这个混淆所在。 –

1

给出的答案到目前为止我走上我希望我没有走过......一个真正的黑暗之路的解决方法很简单化妆确保下列3件事匹配:

1)在谷歌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" /> 

,以获取有关该问题的更多细节。

6

没有必要指定CallbackPathUseGoogleAuthentication

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

只要保持谷歌设置为授权重定向URIs为:

HTTP(S):// yoururl:将ORPort/登录谷歌

欧文处理登录goog在内部并重定向到redirectUri,正如您在ChallengeResult类的代码中所述。这是Account/ExternalLoginCallback。

+2

这应该被标记为解决方案。为我工作就像一个魅力。 – ejcortes

+0

我也会注意到,当通过网络浏览器点击登录按钮时,提供者参数在拨打/ Account/ExternalLogin(例如https:// localhost:44300/Account/ExternalLogin?provider = Google&returnUrl = blah)时应为“Google” –

+0

当你说谷歌设置你指的是什么?对于没有任何经验的人来说,这个答案似乎缺乏清晰度。你在谈论CallBackPath吗? – jwize

3

通过一个简单的改变就可以从教程中获得它的工作香草 - 只需发布这个任何nubes到这种方法。我认为在这种情况下,与oauth2相关的问题在很大程度上充实了最新的模板/ apis - 我的意思是,如果您从头开始,您可能会碰运气 - 阅读:

我只是做了这个教程 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

的一个变化: 它的工作,但谷歌启用的API +在谷歌开发者网站的最新版本后只。

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

我没有做别的独特。

干杯