I have a question I have a web api .net core project and I have implemented JWT bearer token in it and it works fine with postman , if I do not provide token with Authorization TAB of POSTMAN it gives 401 unthorized error , I would like to ask as when this service is consumed by any third party then how they can provide JWT token do I need to add parameters as jwt token with my methods or how if any sample example available ?
Loading

Amit MohantyRank #112 · 20K reputationPosted Mar 12, 2024, 6:28 AM EDT
The way to include the JWT token is by adding it to the Authorization header of the HTTP request as a bearer token. For example:
string apiUrl = "https://yourapi.com/api/resource"; string jwtToken = "your_jwt_token"; using (HttpClient client = new HttpClient()) { client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", jwtToken); try { HttpResponseMessage response = await client.GetAsync(apiUrl); if (response.IsSuccessStatusCode) { string responseBody = await response.Content.ReadAsStringAsync(); Console.WriteLine(responseBody); } else { Console.WriteLine($"Failed to call API. Status code: {response.StatusCode}"); } } catch (Exception ex) { Console.WriteLine($"An error occurred: {ex.Message}"); } }Amit MohantyRank #112 · 20K reputationPosted Mar 13, 2024, 1:39 AM EDT
Hey Pakeeza, the validation of the JWT token is handled by middleware in the pipeline before the request reaches your controller actions. This means that the authorization logic is usually implemented globally and not directly within each controller method. When a request comes in, the JWT token is validated automatically based on the configuration you've set up in your application startup. If the token is missing or invalid, ASP.NET Core will automatically respond with a 401 Unauthorized status code without reaching your controller methods.
Abhishek YadavRank #217 · 11.3K reputationPosted Mar 12, 2024, 6:16 AM EDT
add the token in header
Pakeeza172 reputationPosted Mar 12, 2024, 1:45 PM EDT
Thanks amit for the reply , do I need to add any logic in my controller method for checking the token or the consumer need to do this , as I have tested my API methods it gives 401 unauthorized status code if JWT token is not provided. Do I need to add any logic in my controller method to check either user provide the token & if provided then does it valid or it will be automatically done at consumer side.
Jaimin ShethiyaRank #177 · 13.7K reputationPosted Mar 13, 2024, 12:13 AM EDT
Add JWT Token in the API header request, and when your API will execute at that time in your application first check that token validate and it's successfully validated then on then your will accessible.
In C# side
request.Headers.Add("Authorization", "Bearer eyJhbGc....");