Quick Overview:
As we know, JWT authentication is gaining popularity in the market when it comes to web development. The core reason behind this popularity is that with the increasing utilization of APIs within the market, their security becomes crucial. This is where JWT comes into place. In this blog post, we will look at the steps to implement JWT authentication in .NET Core, ensuring the security of your application.
What is JWT Authentication?
JWT or JSON Web Token is an open standard to pass data between the client and the server. It allows you to transmit the data back and forth between the client, the server, and the consumer in a secure manner. In simple terms, JWT is a compact URL-safe representing the claims to be transferred between the two parties. The claims in a JWT are generally used for authentication and information exchange in web development. It is digitally signed, making it secure and verifiable.
Steps To Implement JWT Authentication in .NET Core
Implementing JWT (JSON Web Token) authentication in a .NET Core application is an ideal way to secure your APIs and web applications. Below is a step-by-step guide to implementing .NET JWT authentication in .NET Core.
Step 1: Create Your New .NET Core Web API Project
Initially, you must create a net .NET Core Web API project in Visual Studio or by using the ‘dotnet new webapi—n Positiwise’ command from the command line.
The command above will create a new .NET Core Web API project named “Positiwise” in the current directory. You can easily find this directory and start working on your project. Using Visual Studio, you can create a new project via its interface by selecting the ideal template.
Step 2: Install Required NuGet Packages
Install the necessary packages using the NuGet Package Manager or by using the command line when you are using the Visual Studio Code:
dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer
dotnet add package System.IdentityModel.Tokens.Jwt
These commands allow adding packages required for implementing the JWT authentication in an ASP.NET Core application. The Microsoft.AspNetCore.Authentication.JwtBearer package provides .NET JWT authentication middleware, while System.IdentityModel.Tokens.Jwt offers support for generating and validating JWTs.
Make sure that the .NET CLI is already installed on your system and that you run these commands in the root directory of your ASP.NET Core project. These commands fetch and install the specified packages and their dependencies into your project.
Step 3: Configure JWT Authentication in ‘Startup.cs’
Open the file ‘Startup.cs’ and then within the ‘ConfigureServices’ method, add the .NET JWT authentication services:
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = Configuration["Jwt:Issuer"],
ValidAudience = Configuration["Jwt:Issuer"],
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:Key"]))
};
});
This configuration sets up the application to authenticate incoming requests using the JWT tokens and validate them based on certain parameters.
Step 4: Add the JWT Middleware to the Pipeline
Add the authentication middleware inside the ‘Configure’ method of ‘Startup.cs’.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
// Other middleware configurations...
// Add .NET JWT authentication middleware
app.UseAuthentication();
// Other middleware configurations...
}
Ensure that you add this line after the middleware that manages the routing but before any middleware that may need authentication, such as authorization middleware.
By adding this line, you instruct ASP.NET Core to include the JWT authentication middleware in the request processing pipeline, allowing your app to authenticate incoming requests using JWT tokens.
Step 5: Generate the JWT Tokens
Create a method to generate the JWT tokens. Generally, this will be included in your authentication services.
public string GenerateJwtToken(string userId)
{
var tokenHandler = new JwtSecurityTokenHandler();
var key = Encoding.ASCII.GetBytes("yourSecretKey");
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(new[] { new Claim("id", userId) }),
Expires = DateTime.UtcNow.AddDays(7),
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
};
var token = tokenHandler.CreateToken(tokenDescriptor);
return tokenHandler.WriteToken(token);
}
Step 6: Authenticate Users And Issue The JWT Tokens
Implement the method to authenticate users, validate the credentials, and issue the JWT tokens.
[HttpPost("login")]
public IActionResult Login(LoginModel model)
{
// Authenticate user
var user = _userService.Authenticate(model.Username, model.Password);
if (user == null)
return Unauthorized();
// Generate JWT token
var token = _authenticationService.GenerateJwtToken(user.Id);
return Ok(new { token });
}
Step-7 Secure Your API Endpoints
Then, add the ‘[Authorize]’ attribute to the controller or the action methods needing authentication.
[Authorize]
[ApiController]
[Route("[controller]")]
public class YourController : ControllerBase
{
// Your authenticated endpoints
}
Step 8: Validate And Decode JWT Tokens
You can easily access the authenticated user’s information from the JWT token in your API controllers or middleware.
var userId = User.FindFirst("id").Value;
Step 9: Test Your .NET JWT Authentication
You can use tools like Postman or Fiddler to test your API endpoints. Authenticate them using the login endpoint to gain a JWT token, which you can include in the Authorization header of subsequent requests.
After receiving the JWT token from the login endpoint, store it securely; then, you will use it to authenticate the other requests to protected endpoints.
Then, for each subsequent request to a protected endpoint, include the JWT token in the Authorization header. Set the header value to “Bearer {your_token}” where “{your_token}” is replaced with the actual JWT token that you obtained earlier.
Send your request to the desired API endpoints with the JWT token in the Authorization header. The API server will then validate the token and, if it is valid, allow access to the protected resources.
Verify that you are receiving the expected responses from the API endpoints. If everything is set up correctly, you can access the protected resources without issues.
Make sure that the JWT tokens typically have an expiration time. If your token expires, you must get new ones by repeating the previous steps.
Also, it is a great idea to test how your API manages the invalid or expired tokens. Send requests with incorrect or expired tokens, and ensure your API returns the correct error messages.
Step 10: Handle Token Expiration and Refreshing (Optional)
You may like to implement the token expiration and refreshing logic to handle the expired tokens without requiring your user to log in again.
Following these steps, you can implement the JWT authentication within your .NET Core application, delivering a secure and efficient way to protect your APIs and web resources.
Conclusion
In the end, we can conclude that Authentication and Authorization in .NET Core are crucial to the security and safety of your application, and implementing JWT authentication in .NET Core allows a robust and secure solution for authenticating your users and protecting the resources in web applications. Leveraging the JSON Web Tokens, your development team can effectively manage the user sessions, authorize access to endpoints, and improve overall security measures. Through the integration of JWT authentication, .NET Core applications can achieve scalability, flexibility, and interoperability, ensuring a seamless user experience while prioritizing data integrity and confidentiality. As technology continues to evolve, embracing .NET JWT authentication in .NET Core remains a pivotal strategy for safeguarding sensitive information and fortifying the integrity of modern web applications.
Expert in Software & Web App Engineering
Parag Mehta, the CEO and Founder of Positiwise Software Pvt Ltd has extensive knowledge of the development niche. He is implementing custom strategies to craft highly-appealing and robust applications for its clients and supporting employees to grow and ace the tasks. He is a consistent learner and always provides the best-in-quality solutions, accelerating productivity.