[英]Send post ajax request with antiforgery token in asp.net core do not access controller method
[英]How to send request to Twitter api using access token in ASP.NET core?
我正在一个项目中,该项目正在接收前端客户端的访问令牌,并使用该访问令牌,因此我必须向Twitter API发出请求才能获取用户详细信息,包括电子邮件地址和个人资料图片网址。
在Facebook的情况下,这只是正常的获取请求,在Google和Microsoft的情况下,我只需要在Header中添加访问令牌作为Bearer令牌,但是,我找不到用于Twitter的方法。
这是我必须提出要求的网址。
https://api.twitter.com/1.1/account/verify_credentials.json
这是Facebook,Google和Microsoft的代码。
private async Task<Profile> ProfileAsync(string token,string providerName)
{
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
if((providerName=="Google") || (providerName=="Microsoft"))
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
}
var formatters = new List<MediaTypeFormatter>()
{
new JsonMediaTypeFormatter()
};
string url;
Profile profile = null;
if (providerName=="Facebook")
{
url = $"https://graph.facebook.com/me?fields=id,name,email&access_token={token}";
}
else if(providerName=="Google")
{
url = $"https://www.googleapis.com/userinfo/v2/me";
}
else if(providerName=="Microsoft")
{
url = $"https://graph.microsoft.com/v1.0/me/";
}
else
{
throw new Exception("Unsupported grant type.");
}
HttpResponseMessage response = await client.GetAsync(url);
if (response.IsSuccessStatusCode)
{
profile = await response.Content.ReadAsAsync<Profile>(formatters);
}
if(providerName=="Microsoft")
{
profile.email = profile.userPrincipalName;
profile.name = profile.displayName;
}
return profile;
}
}
在Twitter中,您应该具有访问令牌和访问令牌密钥。 那么您可以调用验证API: https : //api.twitter.com/1.1/account/verify_credentials.json?include_email = true
使用任何Twitter库进行此验证都更加容易,例如: https : //github.com/CoreTweet/CoreTweet
或任何适用于Twitter的.NET库。
例如:
Tokens tokens = new Tokens()
{
AccessToken = "xxx",
AccessTokenSecret = "xxx",
ConsumerKey = "xxx",
ConsumerSecret = "xxx",
};
IDictionary<string, object> dict = new Dictionary<string, object>();
dict.Add("include_email", "true");
var response = tokens.Account.VerifyCredentials(dict); // will throw exception if not authorized
Console.WriteLine(response.ScreenName + " " + response.Email + " " + response.Id);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.