JSON Web Tokens (JWT) are used for securely transmitting information between parties as a JSON object. JWT is typically used for authentication and authorization. In this article, I'll walk you through how to implement JWT authentication in an ASP.NET Core Web API.
Create an ASP.NET Core Web API Project
- Open Visual Studio and create a new project.
- Select ASP.NET Core Web API template.
- Configure the project as per your requirements and click Create
- To implement JWT, you will need the following NuGet package.
- Microsoft.AspNetCore.Authentication.JwtBearer
- Install it via NuGet Package Manager
- 3. Configure JWT in appsettings.json
- In your appsettings.json, configure the JWT settings.
Create a helper class that will be responsible for generating the JWT token.
Configure JWT Authentication in Startup.cs or Program.cs
In Program.cs, you need to configure JWT authentication in the builder. Services and middleware pipeline. Here's the step-by-step process.
Ensure you have Swashbuckle.AspNetCore is installed in your project.
You can then create a Login endpoint inside a controller to issue JWT tokens.
Protecting Routes
Finally, you can protect specific routes by adding the [Authorize] attribute in your controllers.
Testing JWT in Postman
- Login: Send a POST request to /api/auth/login with a valid username and password.
- Token: Copy the token from the login response.
- Protected Resource: Access the /API/WeatherForecast endpoint and include the JWT in the Authorization header:
Step 1. Obtain a JWT Token in Swagger.
- Create a Login Request
- Open Postman and create a new request.
- Set the request type to POST.
- Enter the URL for your login endpoint (e.g., http://localhost:5000/api/auth/login).
- Set the Request Body
- In the Body tab, select raw and set the format to JSON.
- Enter the login credentials. For example
- Send the Request
- Click the Send button.
- If the credentials are valid, you should receive a response containing the JWT token. The response might look like this.
- Copy the token from the login response.
- Create a GET request for a protected route.
- Set Authorization to Bearer Token and paste the JWT.
Example
Send the request and check the response.
We have implemented JWT (JSON Web Token) authentication to enhance security and streamline user authentication in our application.
ASP.NET Core 9.0 Hosting Recommendation
At HostForLIFE.eu, customers can also experience fast ASP.NET Core hosting. The company invested a lot of money to ensure the best and fastest performance of the datacenters, servers, network and other facilities. Its datacenters are equipped with the top equipments like cooling system, fire detection, high speed Internet connection, and so on. That is why HostForLIFEASP.NET guarantees 99.9% uptime for ASP.NET Core. And the engineers do regular maintenance and monitoring works to assure its Orchard hosting are security and always up.
0 comments:
Post a Comment