[英]Get user's email from Twitter API for External Login Authentication ASP.NET MVC C#
我檢查了幾個相關問題以找到我問題的答案,但都無濟於事。 這個問題我們可以從 Twitter oauth API 獲取電子郵件 ID 嗎? 讓我盡可能獲得 Twitter 支持以允許我的應用程序在下面獲得許可: 使用此文檔作為指南和標記答案的代碼(稍微修改一下)
var resource_url = "https://api.twitter.com/1.1/account/verify_credentials.json";
var postBody = "include_email=true";//
resource_url += "?" + postBody;
生成簽名並發出請求以從 twitter 中獲取用戶的詳細信息,結果在我的 MVC 應用程序中出現401 Unauthorized 。
但是,當我使用 twitter 簽名生成器工具生成授權標頭並使用 fiddler 向https://api.twitter.com/1.1/account/verify_credentials.json?include_email=true發出 GET 請求時,我收到了電子郵件只有一次,我必須在 Twitter 中重新生成我的應用程序密鑰才能再次獲取它。
是否有關於如何生成有效簽名並提出有效請求以通過 .Net TwitterAuthentication 檢索 Twitter 用戶電子郵件的文檔?
在將我所有的頭發從頭上拔下來幾乎要禿頂之后,我終於開始工作了。 我發現簽名基本字符串與我的代碼生成的字符串略有不同。 經過一些調整,我能夠生成一個有效的簽名基本字符串。
在Startup.cs 中,我添加了 access_token 和 access_secret 作為聲明。 我沒有使用在我的應用程序中找到的那個,因為用戶在嘗試登錄或注冊時需要調用一個新的:
var twitterOptions = new Microsoft.Owin.Security.Twitter.TwitterAuthenticationOptions()
{
ConsumerKey = ConfigurationManager.AppSettings["consumer_key"],
ConsumerSecret = ConfigurationManager.AppSettings["consumer_secret"],
Provider = new Microsoft.Owin.Security.Twitter.TwitterAuthenticationProvider
{
OnAuthenticated = (context) =>
{
context.Identity.AddClaim(new System.Security.Claims.Claim("urn:twitter:access_token", context.AccessToken));
context.Identity.AddClaim(new System.Security.Claims.Claim("urn:twitter:access_secret", context.AccessTokenSecret));
return Task.FromResult(0);
}
},
BackchannelCertificateValidator = new Microsoft.Owin.Security.CertificateSubjectKeyIdentifierValidator(new[]
{
"A5EF0B11CEC04103A34A659048B21CE0572D7D47", // VeriSign Class 3 Secure Server CA - G2
"0D445C165344C1827E1D20AB25F40163D8BE79A5", // VeriSign Class 3 Secure Server CA - G3
"7FD365A7C2DDECBBF03009F34339FA02AF333133", // VeriSign Class 3 Public Primary Certification Authority - G5
"39A55D933676616E73A761DFA16A7E59CDE66FAD", // Symantec Class 3 Secure Server CA - G4
"add53f6680fe66e383cbac3e60922e3b4c412bed", // Symantec Class 3 EV SSL CA - G3
"4eb6d578499b1ccf5f581ead56be3d9b6744a5e5", // VeriSign Class 3 Primary CA - G5
"5168FF90AF0207753CCCD9656462A212B859723B", // DigiCert SHA2 High Assurance Server CA
"B13EC36903F8BF4701D498261A0802EF63642BC3" // DigiCert High Assurance EV Root CA
}),
CallbackPath = new PathString("/twitter/account/ExternalLoginCallback")
};
app.UseTwitterAuthentication(twitterOptions);
最后在我的控制器中,我只是調用了我的助手類來從 twitter 獲取姓名和電子郵件:
if (loginInfo.Login.LoginProvider.ToLower() == "twitter")
{
string access_token = loginInfo.ExternalIdentity.Claims.Where(x => x.Type == "urn:twitter:access_token").Select(x => x.Value).FirstOrDefault();
string access_secret = loginInfo.ExternalIdentity.Claims.Where(x => x.Type == "urn:twitter:access_secret").Select(x => x.Value).FirstOrDefault();
TwitterDto response = MyHelper.TwitterLogin(access_token, access_secret, ConfigurationManager.AppSettings["consumer_key"], ConfigurationManager.AppSettings["consumer_secret"]);
// by now response.email should possess the email value you need
}
輔助類方法:
這是我為了提出有效請求而調整的部分:
baseString = string.Concat("GET&", Uri.EscapeDataString(resource_url) + "&" + Uri.EscapeDataString(request_query), "%26", Uri.EscapeDataString(baseString));
public static TwitterDto TwitterLogin(string oauth_token, string oauth_token_secret, string oauth_consumer_key, string oauth_consumer_secret)
{
// oauth implementation details
var oauth_version = "1.0";
var oauth_signature_method = "HMAC-SHA1";
// unique request details
var oauth_nonce = Convert.ToBase64String(
new ASCIIEncoding().GetBytes(DateTime.Now.Ticks.ToString()));
var timeSpan = DateTime.UtcNow
- new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
var oauth_timestamp = Convert.ToInt64(timeSpan.TotalSeconds).ToString();
var resource_url = "https://api.twitter.com/1.1/account/verify_credentials.json";
var request_query = "include_email=true";
// create oauth signature
var baseFormat = "oauth_consumer_key={0}&oauth_nonce={1}&oauth_signature_method={2}" +
"&oauth_timestamp={3}&oauth_token={4}&oauth_version={5}";
var baseString = string.Format(baseFormat,
oauth_consumer_key,
oauth_nonce,
oauth_signature_method,
oauth_timestamp,
oauth_token,
oauth_version
);
baseString = string.Concat("GET&", Uri.EscapeDataString(resource_url) + "&" + Uri.EscapeDataString(request_query), "%26", Uri.EscapeDataString(baseString));
var compositeKey = string.Concat(Uri.EscapeDataString(oauth_consumer_secret),
"&", Uri.EscapeDataString(oauth_token_secret));
string oauth_signature;
using (HMACSHA1 hasher = new HMACSHA1(ASCIIEncoding.ASCII.GetBytes(compositeKey)))
{
oauth_signature = Convert.ToBase64String(
hasher.ComputeHash(ASCIIEncoding.ASCII.GetBytes(baseString)));
}
// create the request header
var headerFormat = "OAuth oauth_consumer_key=\"{0}\", oauth_nonce=\"{1}\", oauth_signature=\"{2}\", oauth_signature_method=\"{3}\", oauth_timestamp=\"{4}\", oauth_token=\"{5}\", oauth_version=\"{6}\"";
var authHeader = string.Format(headerFormat,
Uri.EscapeDataString(oauth_consumer_key),
Uri.EscapeDataString(oauth_nonce),
Uri.EscapeDataString(oauth_signature),
Uri.EscapeDataString(oauth_signature_method),
Uri.EscapeDataString(oauth_timestamp),
Uri.EscapeDataString(oauth_token),
Uri.EscapeDataString(oauth_version)
);
// make the request
ServicePointManager.Expect100Continue = false;
resource_url += "?include_email=true";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(resource_url);
request.Headers.Add("Authorization", authHeader);
request.Method = "GET";
WebResponse response = request.GetResponse();
return JsonConvert.DeserializeObject<TwitterDto>(new StreamReader(response.GetResponseStream()).ReadToEnd());
}
}
public class TwitterDto
{
public string name { get; set; }
public string email { get; set; }
}
這就是您獲取 Twitter 用戶電子郵件所需的全部內容。 我希望它可以幫助有人為此苦苦掙扎。 請注意,問題中提到的步驟也非常重要。
更新版本 .netcore 3.1
與上述解決方案相比,在 .netcore 中實現 twitter API 非常簡單。 首先,您需要在 Twitter 上創建一個應用Create Twitter App
提供所有必要的信息,例如應用程序名稱、描述、網站 URL( https://example.com將用於本地開發)等。 對於您的回調 url,請提供您正在使用的本地 url。 就我而言, https://localhost:44318/signin-twitter並確保您勾選“從用戶請求電子郵件地址”保存,然后在“密鑰和令牌”選項卡下重新生成消費者 API 密鑰,請參見下圖:
完成 Twitter 管理后,在 Visual Studio 的解決方案中安裝 nuget 包:
Install-Package Microsoft.AspNetCore.Authentication.Twitter
在 Visual Studio 中更新您的 .NetCore 應用程序啟動類(ConfigureServices 方法)以使用以下代碼初始化 Twitter 身份驗證機制:
services.AddAuthentication().AddTwitter(options =>
{
options.ConsumerKey = twitterConsumerApiKey;
options.ConsumerSecret = twitterConsumerSecretKey;
options.RetrieveUserDetails = true;
}); // twitterConsumerApiKey and twitterConsumerSecretkey can be found under the "Keys and tokens" tab of the Twitter App previously created.
該過程已完成,您應該能夠在身份驗證后收到用戶的電子郵件。 有關更多信息,請查看使用 ASP.NET Core 的 Twitter 外部登錄設置
在用戶使用 Twitter 登錄后,您必須更改代碼以調用 GET account/verify_credentials 方法。 將參數 include_email 設置為 true 很重要。 當此設置為 true 時,電子郵件將作為字符串在用戶對象中返回。 我正在使用這個庫https://www.nuget.org/packages/linqtotwitter這樣我就不必編寫代碼來處理 twitter api 請求
var twitterCtx = new TwitterContext(authTwitter);
var verifyResponse = await
(from acct in twitterCtx.Account
where (acct.Type == AccountType.VerifyCredentials) && (acct.IncludeEmail == true)
select acct)
.SingleOrDefaultAsync();
看看我是如何做到這一點的http://www.bigbrainintelligence.com/Post/get-users-email-address-from-twitter-oauth-ap
這是一個簡單而干凈的解決方案
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.