Skip to content

Instantly share code, notes, and snippets.

@bjoerntx
Last active March 5, 2021 22:15
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/b9580ba7e24665b93473779dc6445f92 to your computer and use it in GitHub Desktop.
Save bjoerntx/b9580ba7e24665b93473779dc6445f92 to your computer and use it in GitHub Desktop.
[HttpGet]
[Route("AccessToken")]
public async System.Threading.Tasks.Task<ActionResult> AccessTokenAsync() {
// security credentials
string clientId = "";
string clientSecret = "";
string serviceUrl = "https://trial.dsserver.io";
string ClientCredentials = "client_credentials";
AccessTokenResponse token;
HttpClient m_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 = await m_client.SendAsync(tokenRequest);
// retrieve and return the token
var tokenResponseStream = await tokenResponse.Content.ReadAsStringAsync();
token = JsonConvert.DeserializeObject<AccessTokenResponse>(tokenResponseStream);
return Ok(token);
}
public string UrlEncode(Dictionary<string, string> dict) {
return string.Join("&", dict.Keys.Select(k => $"{k}={WebUtility.UrlEncode(dict[k])}"));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment