Asp.net-Mvc
從 ASP.NET MVC 5 中的 Facebook v2.4 API 訪問 OAuth ExternalLoginCallback 中的電子郵件地址
使用 v2.3 的 Facebook API,如果設置了以下內容,使用者的電子郵件地址將在回調時返回
ExternalLoginCallback;app.UseFacebookAuthentication(new FacebookAuthenticationOptions { AppId = "XXX", AppSecret = "XXX", Scope = { "email" } });但是,任何只能針對 v2.4(7 月 8 日發布)的應用程序不再將電子郵件地址返回到
ExternalLoginCallback.我認為這可能與此處列出的 v2.4 更改有關;
聲明性欄位
為了嘗試提高移動網路的性能,v2.4 中的節點和邊緣要求您明確請求 GET 請求所需的欄位。例如,
GET /v2.4/me/feed預設不再包含點贊和評論,但GET /v2.4/me/feed?fields=comments,likes會返回數據。有關更多詳細資訊,請參閱有關如何請求特定欄位的文件。我現在如何訪問此電子郵件地址?
為了解決這個問題,我必須從 nuget安裝Facebook SDK for .NET並單獨查詢電子郵件地址。
在該
ExternalLoginCallback方法中,我添加了一個條件來填充來自 Facebook Graph API 的電子郵件地址;var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync(); if (loginInfo == null) { return RedirectToAction("Login"); } // added the following lines if (loginInfo.Login.LoginProvider == "Facebook") { var identity = AuthenticationManager.GetExternalIdentity(DefaultAuthenticationTypes.ExternalCookie); var access_token = identity.FindFirstValue("FacebookAccessToken"); var fb = new FacebookClient(access_token); dynamic myInfo = fb.Get("/me?fields=email"); // specify the email field loginInfo.Email = myInfo.email; }並得到
FacebookAccessTokenI 擴展ConfigureAuth;app.UseFacebookAuthentication(new FacebookAuthenticationOptions { AppId = "XXX", AppSecret = "XXX", Scope = { "email" }, Provider = new FacebookAuthenticationProvider { OnAuthenticated = context => { context.Identity.AddClaim(new System.Security.Claims.Claim("FacebookAccessToken", context.AccessToken)); return Task.FromResult(true); } } });