Asp.net-Mvc-5
在預設 MVC5 應用程序中的帳戶關聯步驟中從外部提供商 Google 和 Facebook 獲取電子郵件
顯然,您可以通過將範圍添加到對
FacebookAuthenticationOptions像中的 Facebook 提供程序來執行此操作Startup.Auth.cs:<http://blogs.msdn.com/b/webdev/archive/2013/10/16/get-more-information-from-social-providers-used-in-the-vs-2013-project-templates.aspx>
List<string> scope = new List<string>() { "email" }; var x = new FacebookAuthenticationOptions(); x.Scope.Add("email"); ... app.UseFacebookAuthentication(x);如何與 Google 提供商做同樣的事情?類/對像沒有
x.Scope屬性!GoogleAuthenticationOptions
請在這篇文章的底部查看更新!
以下適用於我的Facebook:
StartupAuth.cs:
var facebookAuthenticationOptions = new FacebookAuthenticationOptions() { AppId = "x", AppSecret = "y" }; facebookAuthenticationOptions.Scope.Add("email"); app.UseFacebookAuthentication(facebookAuthenticationOptions);ExternalLoginCallback 方法:
var externalIdentity = HttpContext.GetOwinContext().Authentication.GetExternalIdentityAsync(DefaultAuthenticationTypes.ExternalCookie); var emailClaim = externalIdentity.Result.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Email); var email = emailClaim.Value;對於Google:
啟動驗證.cs
app.UseGoogleAuthentication();ExternalLoginCallback 方法(與 facebook 相同):
var externalIdentity = HttpContext.GetOwinContext().Authentication.GetExternalIdentityAsync(DefaultAuthenticationTypes.ExternalCookie); var emailClaim = externalIdentity.Result.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Email); var email = emailClaim.Value;如果我在這裡設置斷點:
var email = emailClaim.Value;我在調試器中看到了 Facebook 和 Google 的電子郵件地址。
更新 1:舊的答案讓我感到困惑,所以我用我自己的項目中的程式碼更新了它,我剛剛調試過並且我知道它可以工作。
更新 2:使用新的ASP.NET Identity 2.0 RTM版本,您不再需要本文中的任何程式碼。獲取電子郵件的正確方法是簡單地執行以下操作:
- 啟動.Auth.cs
app.UseFacebookAuthentication( appId: "x", appSecret: "y"); app.UseGoogleAuthentication();
- AccountController.cs
// // GET: /Account/ExternalLoginCallback [AllowAnonymous] public async Task<ActionResult> ExternalLoginCallback(string returnUrl) { var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync(); if (loginInfo == null) { return RedirectToAction("Login"); } // Sign in the user with this external login provider if the user already has a login var result = await SignInHelper.ExternalSignIn(loginInfo, isPersistent: false); switch (result) { case SignInStatus.Success: return RedirectToLocal(returnUrl); case SignInStatus.LockedOut: return View("Lockout"); case SignInStatus.RequiresTwoFactorAuthentication: return RedirectToAction("SendCode", new { ReturnUrl = returnUrl }); case SignInStatus.Failure: default: // If the user does not have an account, then prompt the user to create an account ViewBag.ReturnUrl = returnUrl; ViewBag.LoginProvider = loginInfo.Login.LoginProvider; return View("ExternalLoginConfirmation", new ExternalLoginConfirmationViewModel { Email = loginInfo.Email }); } }