(C# ASP.NET Core) C# Console App Connectivity for Basic and JWT Authentication

In this tutorial we present a C# console application that connects to the web api that we have done in the previous tutorial. This app will first obtain a JWT Token by sending it's login credentials in a basic authorization header, and then it will use that token in a bearer header to obtain authorization to the second api protected by JWT Authorization. Please go through the previous turorial where we have explained both the web apis.
(Rev. 31-Oct-2024)

Categories | About |     |  

Parveen,

Setting up the project

Create a simple C# console application and install the newtonsoft.json nuget package for including support for json.


PM> Install-Package Newtonsoft.Json -Version 13.0.1

Video Explanation (see it happen!)

Please watch the following youtube video:

The web api that we have to call

Recall from the previous tutorial that we have added two web api.

/token
The first api is protected by a basic authorization scheme. So the caller app has to send his login-id and password in an authorization header. This api sends a jwt token in a json property called access_token.
/info
The second api is protected by jwt authorization. The caller has to send a valid jwt token in a bearer header. Once he is authenticated, the handler executes and sends a welcome message.

The Source Code

Next I will come to the source code. You can obtain the Program.cs file of the client application from the downloads attached to this video. Open the program.cs file, and let's examine it line by line.

First we have the URL of the server application. After that an HttpClient has been created.


// Program.cs file of the console app 

// Install-Package Newtonsoft.Json 
static async Task Main(string[] args)
{
    // replace with your URL 
    const String WEBAPI_URL = "https://localhost:7264";

    Console.WriteLine("Connecting Basic Auth...");

    using (var client = new HttpClient())
    {
        // hard-coded values are same as 
        // in the web api project 
        // see BasicAuthHandler.cs file 
        // of the attached ASP.NET Core Project 
        String uid = "hoven";
        String pwd = "1234";

        // create base64 header 
        String header = Convert.ToBase64String(
            Encoding.UTF8.GetBytes($"{uid}:{pwd}"));

        // add the basic authorization header 
        client.DefaultRequestHeaders.Authorization =
            new AuthenticationHeaderValue("Basic", header);

        HttpResponseMessage response;

        try
        {
            // call the api endpoint 
            response = await client.GetAsync($"{WEBAPI_URL}/token");
        }
        catch
        {
            Console.WriteLine($"Is the server running? {WEBAPI_URL}");

            return;
        }

        String jwtToken = String.Empty;

        using (response)
        {
            try
            {
                response.EnsureSuccessStatusCode();
            }
            catch
            {
                Console.WriteLine("ERR EnsureSuccessStatusCode");

                return;
            }

            // read the json response string 
            // {"access_token" : "ey......"} 
            String jsonResponse = 
                await response.Content.ReadAsStringAsync();

            // convert string to json object 
            var jsonObject = 
                JsonConvert.DeserializeObject<dynamic>(jsonResponse);

            // the token is in the property - access_token 
            jwtToken = jsonObject.access_token;

            Console.WriteLine("\r\n");
            Console.WriteLine($"DEBUG: JWT = {jwtToken}");
            Console.WriteLine("\r\n");

        }

        Console.WriteLine("Sending JWT Auth...");

        // set the bearer header now 
        client.DefaultRequestHeaders.Authorization =
            new AuthenticationHeaderValue("Bearer", jwtToken);

        // make a GET request 
        response = await client.GetAsync($"{WEBAPI_URL}/info");

        // throws exception if response != 200OK 
        // try-catch not shown 
        response.EnsureSuccessStatusCode();

        // read the response from the api because you are 
        // authorized now 
        String info = await response.Content.ReadAsStringAsync();

        Console.WriteLine("\r\n\r\n");
        Console.WriteLine($"API Response: {info}");
        Console.WriteLine("\r\n\r\n");

    }
}

We have to send a basic header containing user-id and password. This is the same pair of user-id and password that we hard-coded when we implemented basic authentication in the attached web-api project.

Next we have created a an authorization header with the Basic scheme.

After that a GET request is sent to obtain the jwt token.The EnsureSuccessCode function throws an exception if the response code is not 200 OK.

After that the json response string is read from the response. It contains the jwt token in a property called access_token.

After that json deserialization is done to obtain the jwt token, and then in the next line it is displayed as a debug output.

Next the jwt token is set as a bearer authorization header.

An HTTP GET request is finally made to the info end-point. The response string is then displayed on the console.

Run the Projects

Let's now test the project. First of all run the web-api project and allow the home page to open. This ensures that the web-api is now listening for the requests.

Both these projects are available in the downloads attached to this tutorial.


// response from the console app 

Connecting Basic Auth...

DEBUG: JWT = eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9....0YZweLY

Sending JWT Auth...

API Response: "Welcome hoven! JWT Authorized!"

Press any key to continue . . .

Next run the console application with Ctrl+F5. If everything goes fine, you will see the messages from the two api calls. The first containing the jwt token, and the second containing a welcome message.

JWT Authorization has thus been tested OK. Thanks!


This Blog Post/Article "(C# ASP.NET Core) C# Console App Connectivity for Basic and JWT Authentication" by Parveen is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.