Last active
March 5, 2021 22:15
-
-
Save bjoerntx/b9580ba7e24665b93473779dc6445f92 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
[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