Secure API with JWT token ASP Net Core WebApi

Prathamesh Shende 376 Reputation points
2022-11-29T03:26:33.93+00:00

There are bunch of examples on web about securing api using jwt.
https://www.codemag.com/Article/2105051/Implementing-JWT-Authentication-in-ASP.NET-Core-5
https://www.youtube.com/watch?v=h2hGGPHLqqc

The issue I was facing after generating JWT token where do I put that string into code to run seamlessly? every tutorial they put in postman.

Problem:
I want to use api only in 2 apps where the login will be static. It just to use in our in-house project. So when ever some one tries to visit the api call it will show 401 Code. Unless user use login api first.

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,371 questions
0 comments No comments
{count} votes

Accepted answer
  1. Zhi Lv - MSFT 32,086 Reputation points Microsoft Vendor
    2022-11-29T08:15:50.47+00:00

    Hi @Prathamesh Shende ,

    The issue I was facing after generating JWT token where do I put that string into code to run seamlessly? every tutorial they put in postman.

    From the tutorials, we can know that, after getting the JWT token, we should add it to the request header using the Authorization property.

    So, it depends on which method you will using to call the API method (with the JWT token), JS or C# code?

    If you want calling the API method using HttpClient, you can refer the following sample code to add the JWT token to the request header:

             HttpClient client = new HttpClient();  
             client.BaseAddress = new Uri("https://localhost:44310/api/todo/");  
             client.DefaultRequestHeaders  
                     .Accept  
                     .Add(new MediaTypeWithQualityHeaderValue("application/json"));//ACCEPT header  
             var url = "relativeAddress"; //add the `[Route("relativeAddress")]` in the API action method.  
             HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, url);  
             //add jwt token to the header  
             var authString = "jwt token";  
             request.Headers.Add("Authorization", $"Bearer {authString}");   
             request.Content = new StringContent("{\"name\":\"John Doe\",\"age\":33}",  
                                                 Encoding.UTF8,  
                                                 "application/json");//CONTENT-TYPE header  
                   
             _logger.LogInformation("Create http request");  
             await client.SendAsync(request)  
                     .ContinueWith(async responseTask =>  
                     {  
                         Console.WriteLine("Response: {0}", responseTask.Result);  
                         var Content = await responseTask.Result.Content.ReadAsStringAsync();  
                     });  
    

    More detailed information, see my reply in this thread.
    If you want to use JQuery Ajax, the code like this:

    $.ajax({  
        type: "POST",  
        url: "https://localhost:44360/Reservation",  
        headers: {  
            Authorization: 'Bearer ' + token  
        },  
        dataType: 'json',  
        success: function (result, status, xhr) {  
            ShowData(result);  
        },  
        error: function (xhr, status, error) {  
             alert(error);  
        }  
    });  
    

    Refer to this article: How to call a JWT secured APIs with jQuery AJAX [with source codes].


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best regards,
    Dillion


0 additional answers

Sort by: Most helpful