Skip to content

Instantly share code, notes, and snippets.

@bjoerntx
Created March 12, 2024 09:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bjoerntx/caa228d0f4640e1efd931a0a26083624 to your computer and use it in GitHub Desktop.
Save bjoerntx/caa228d0f4640e1efd931a0a26083624 to your computer and use it in GitHub Desktop.
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