2014-02-23 39 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默認是禁用的。

我沒有做別的獨特。

乾杯