Search code examples
c#asp.net-coredotnet-httpclient

get oath2 token with client credentials


I have an API call with the following postman setup to get a token

enter image description here

I try to make it work with the following code, but I get 401 unauthorized error

private async Task<Token> GetElibilityToken()
{
    using (var httpClient = new HttpClient())
    {
        httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));

        string baseAddress = ApiCallsConsts.AccessTokenURL;

        string grant_type = "client_credentials";
        string client_id = "xxxxxxxxxxxxxxx";
        string client_secret = "yyyyyyyyyyyyyyy";

        var form = new Dictionary<string, string>
        {
            {"grant_type", grant_type},
            {"client_id", client_id},
            {"client_secret", client_secret},
        };

        HttpResponseMessage tokenResponse = await httpClient.PostAsync(baseAddress, new FormUrlEncodedContent(form));
        var jsonContent = await tokenResponse.Content.ReadAsStringAsync();
        Token tok = JsonConvert.DeserializeObject<Token>(jsonContent);
        return tok;
    }
}

Also I try to make it work with RestSharp nuget without luck.

private async Task<string> GetToken()
{
    try
    {

        string url = ApiCallsConsts.AccessTokenURL;
        string client_id = "xxxxxxxxxxxx";
        string client_secret = "yyyyyyyyyyyyyy";
        //request token
        var restclient = new RestClient(url);
        RestRequest request = new RestRequest(); 
        request.AddHeader("Accept", "application/json");
        request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
        request.AddParameter("client_id", client_id);
        request.AddParameter("client_secret", client_secret);
        request.AddParameter("grant_type", "client_credentials");
        var tResponse = await restclient.ExecutePostAsync(request);
        var responseJson = tResponse.Content;
        var token = JsonConvert.DeserializeObject<Dictionary<string, object>>(responseJson)["access_token"].ToString();
        return token;
    }
    catch (Exception ex)
    {
        return null;
    }

}

Solution

  • Here is the working code sample

    private async Task<Token> GetElibilityToken()
    {
        using (var httpClient = new HttpClient())
        {
            string baseAddress = ApiCallsConsts.AccessTokenURL;
    
            string grant_type = "client_credentials";
            string client_id = "xxxxxxxxxxxxx";
            string client_secret = "yyyyyyyyyyyyy";
    
            var clientCreds = System.Text.Encoding.UTF8.GetBytes($"{client_id}:{client_secret}");
            httpClient.DefaultRequestHeaders.Authorization =
              new AuthenticationHeaderValue("Basic", System.Convert.ToBase64String(clientCreds));
    
            var form = new Dictionary<string, string>
            {
                {"grant_type", grant_type}
            };
    
            HttpResponseMessage tokenResponse = await httpClient.PostAsync(baseAddress, new FormUrlEncodedContent(form));
            var jsonContent = await tokenResponse.Content.ReadAsStringAsync();
            Token tok = JsonConvert.DeserializeObject<Token>(jsonContent);
            return tok;
        }
    }