C# AuthenicationApiClient.GetTokenAsync() Fails

Problem: I am attempting to utilize the AuthenticationApiClient to fetch a token that I can use for the ManagementApiClient. I utilized the “quick-start” code snippet from the Auth0 website that uses RestSharp to make the equivalent call to GetTokenAsync from the AuthenticationAPIClient and it works fine. However, now that I’ve switched to the SDK provided by Auth0, I am receiving a socket exception with the message, ‘One or more errors occurred. (No such host is known).’

I’ve read the documentation, and even dug around the source in Github. I’m not quite sure where I could be going wrong here. Any solutions? Below is the relevant information.

SDK: Auth0.AuthenticationApi
Version: 5.11
Platform: C# .NET Core 2.2
Code Type: New, never worked
Stack Trace:

at System.Net.Http.ConnectHelper.ConnectAsync(String host, Int32 port, CancellationToken cancellationToken)
at System.Threading.Tasks.ValueTask1.get_Result() at System.Net.Http.HttpConnectionPool.CreateConnectionAsync(HttpRequestMessage request, CancellationToken cancellationToken) at System.Threading.Tasks.ValueTask1.get_Result()
at System.Net.Http.HttpConnectionPool.WaitForCreatedConnectionAsync(ValueTask1 creationTask) at System.Threading.Tasks.ValueTask1.get_Result()
at System.Net.Http.HttpConnectionPool.SendWithRetryAsync(HttpRequestMessage request, Boolean doRequestAuth, CancellationToken cancellationToken)
at System.Net.Http.RedirectHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
at System.Net.Http.HttpClient.FinishSendAsyncBuffered(Task1 sendTask, HttpRequestMessage request, CancellationTokenSource cts, Boolean disposeCts) at Auth0.Core.Http.ApiConnection.RunAsync[T](String resource, HttpMethod httpMethod, Object body, IDictionary2 urlSegments, IDictionary2 queryStrings, IDictionary2 parameters, IDictionary2 headers, IList1 fileParameters, JsonConverter converters)
at Auth0.Core.Http.ApiConnection.PostAsync[T](String resource, Object body, IDictionary2 parameters, IList1 fileParameters, IDictionary2 urlSegments, IDictionary2 headers, IDictionary`2 queryStrings)
at Console_Core.Program.GetTokenStandard() in C:\Development\Testing\Console_Core\Console_Core\Program.cs:line 79

Code:

        var baseUri = Configuration["Auth0:Domain"];
        var client = new AuthenticationApiClient(baseUri);

        var request = new ClientCredentialsTokenRequest
        {
            Audience = Configuration["Auth0:Audience"],
            ClientId = Configuration["Auth0:ClientId"],
            ClientSecret = Configuration["Auth0:ClientSecret"]
        };

        var token = await client.GetTokenAsync(request);

        return token;

Compared to the modified “quick start” code that works:

        var baseUri = Configuration["Auth0:Domain"] + @"oauth/token";
        var client = new RestClient(baseUri);
        var request = new RestRequest(Method.POST);
        request.AddHeader("content-type", "application/json");

        var body = new AccessTokenRequestBody
        {
            Audience = Configuration["Auth0:Audience"],
            ClientId = Configuration["Auth0:ClientId"],
            ClientSecret = Configuration["Auth0:ClientSecret"]
        };

        var json = JsonConvert.SerializeObject(body);

        request.AddParameter("application/json", json, ParameterType.RequestBody);
        IRestResponse response = client.Execute(request);

        var token = JsonConvert.DeserializeObject<AccessTokenResponse>(response.Content);

        return token;

    public class AccessTokenRequestBody
    {
        [JsonProperty("client_id")]
        public string ClientId { get; set; }

        [JsonProperty("client_secret")]
        public string ClientSecret { get; set; }

        [JsonProperty("audience")]
        public string Audience { get; set; } 

        [JsonProperty("grant_type")]
        public string GrantType { get; } = "client_credentials";
    }
1 Like

So, I’m not sure why, but after two days of messing with this, I found a solution to fix the problem. I simply have to supply a HttpClient instance for the ApiClient. Solution:

        var httpClient = new HttpClient();
        var uri = new Uri(Configuration["Auth0:Domain"]);
        var client = new AuthenticationApiClient(uri, httpClient);

EDIT: After reading the source more closely, the reason it doesn’t work without supplying a Client is because the constructor that only takes a Uri calls another constructor, which takes in the Uri and a HttpMessageHandler, the latter of which is null. I’m not sure of the purpose of this, but naturally that’s going to cause a failure.

try creating the authenticationapiclient as per the below code.

AuthenticationApiClient authenticationApiClient =
new AuthenticationApiClient( new Uri($“https://{auth0Domain}/”));

2 Likes

Thank you a lot @mmohanan for sharing it with the rest of community!

This topic was automatically closed 15 days after the last reply. New replies are no longer allowed.