Last active
March 21, 2020 14:15
-
-
Save KiptoonKipkurui/4f857e433d186cdd79501c0bd4bff8b9 to your computer and use it in GitHub Desktop.
code to get the oauth token from twitter api
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <summary> | |
/// Gets bearer token for application-only authentication from Twitter API 1.1, obtaining key and secret from web.config/app.config. | |
/// * NOTE: This token should be cached by the application -- for up to 15 mins. | |
/// * Dependant on web.config appSettings params twitterConsumerKey and twitterConsumerSecret. | |
/// * Twitter API client oAuth settings: https://dev.twitter.com/app | |
/// * Application-only authentication: https://dev.twitter.com/docs/auth/application-only-auth | |
/// * API endpoint oauth2/token: https://dev.twitter.com/docs/api/1.1/post/oauth2/token | |
/// </summary> | |
/// <returns>oAuth bearer token for Twitter API authentication.</returns> | |
public async Task<string> GetBearerToken() | |
{ | |
JToken token = JObject.Parse( | |
await GetBearerTokenJson( | |
options.ConsumerKey,options.ConsumerSecret)); | |
return token.SelectToken("access_token").Value<string>(); | |
} | |
/// <summary> | |
/// Gets bearer token for application-only authentication from Twitter API 1.1. | |
/// * NOTE: This token should be cached by the application -- for up to 15 mins. | |
/// * Twitter API client oAuth settings: https://dev.twitter.com/app | |
/// * Application-only authentication: https://dev.twitter.com/docs/auth/application-only-auth | |
/// * API endpoint oauth2/token: https://dev.twitter.com/docs/api/1.1/post/oauth2/token | |
/// </summary> | |
/// <param name="consumerKey">Token obtained from authentication.</param> | |
/// <param name="consumerSecret">Token obtained from authentication.</param> | |
/// <returns>oAuth bearer token for Twitter API authentication.</returns> | |
public async Task<string> GetBearerToken(string consumerKey, string consumerSecret) | |
{ | |
JToken token = JObject.Parse( | |
await GetBearerTokenJson(consumerKey, consumerSecret)); | |
return token.SelectToken("access_token").Value<string>(); | |
} | |
private async static Task<string> GetBearerTokenJson(string consumerKey, string consumerSecret) | |
{ | |
var webrequest = CreateRequest("/oauth2/token",HttpMethod.Get); | |
webrequest.Headers.Add("Authorization", "Basic " + GetBasicAuthToken(consumerKey, consumerSecret)); | |
WriteRequest(webrequest, "grant_type=client_credentials"); | |
return await ReadResponse(webrequest); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment