Created
March 12, 2024 09:43
-
-
Save bjoerntx/caa228d0f4640e1efd931a0a26083624 to your computer and use it in GitHub Desktop.
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
private string GetAccessTokenClientCredentials() | |
{ | |
// Security credentials | |
string clientId = ""; | |
string clientSecret = ""; | |
string serviceUrl = "https://trial.dsserver.io"; | |
string clientCredentials = "client_credentials"; | |
BearerToken token; | |
HttpClient client = new HttpClient(); | |
// Generate the payload | |
var payload = new Dictionary<string, string> | |
{ | |
["grant_type"] = clientCredentials, | |
}; | |
// Token endpoint | |
string requestUri = $"{serviceUrl}/oauth/token"; | |
// Create the request message | |
var tokenRequest = new HttpRequestMessage(HttpMethod.Post, requestUri) | |
{ | |
Content = new StringContent( | |
UrlEncode(payload), | |
Encoding.UTF8, | |
"application/x-www-form-urlencoded") | |
}; | |
// Add basic auth header containing client id and secret | |
string credentials = $"{clientId}:{clientSecret}"; | |
byte[] credentialsUtf8 = Encoding.UTF8.GetBytes(credentials); | |
string credentialsB64 = Convert.ToBase64String(credentialsUtf8); | |
tokenRequest.Headers.Authorization = | |
new AuthenticationHeaderValue("Basic", credentialsB64); | |
// Send the request | |
var tokenResponse = client.SendAsync(tokenRequest).Result; | |
// Retrieve and return the token | |
var tokenResponseStream = tokenResponse.Content.ReadAsStringAsync().Result; | |
token = JsonConvert.DeserializeObject<BearerToken>(tokenResponseStream); | |
return token.AccessToken; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment