JSON Web Token (JWT) is a widely used method for securing APIs and transmitting information between parties. In this tutorial, we’ll discuss what JWT is, when to use it, and how to implement it in a .NET Core project.
JSON Web Token (JWT) is an open standard (RFC 7519) that defines a compact and self-contained way for securely transmitting information between parties as a JSON object. This information can be verified and trusted because it is digitally signed. JWTs can be signed using a secret (with the HMAC algorithm) or a public/private key pair using RSA or ECDSA.
Although JWTs can be encrypted to also provide secrecy between parties, we will focus on signed tokens. Signed tokens can verify the integrity of the claims contained within it, while encrypted tokens hide those claims from other parties. When tokens are signed using public/private key pairs, the signature also certifies that only the party holding the private key is the one that signed it.
Here are some scenarios where JSON Web Tokens are useful:
This is the most common scenario for using JWT. Once the user is logged in, each subsequent request will include the JWT, allowing the user to access routes, services, and resources that are permitted with that token. Single Sign On is a feature that widely uses JWT nowadays, because of its small overhead and its ability to be easily used across different domains.
JSON Web Tokens are a good way of securely transmitting information between parties. Because JWTs can be signed—for example, using public/private key pairs—you can be sure the senders are who they say they are. Additionally, as the signature is calculated using the header and the payload, you can also verify that the content hasn’t been tampered with.
To implement JWT in your .NET Core project, follow these steps:
Install the Microsoft.AspNetCore.Authentication.JwtBearer
package.
Update the configuration: Add the following configuration to your Startup.cs or Program.cs file:
JwtSettings jwtSettings = builder.Configuration.GetJwtSettings();string key = Encoding.ASCII.GetBytes(jwtSettings.SecretKey);builder.Services.AddAuthentication(config =>{config.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;config.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;config.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;}).AddJwtBearer(options =>{options.SaveToken = true;options.RequireHttpsMetadata = false;options.TokenValidationParameters = new TokenValidationParameters{ValidateIssuerSigningKey = true,IssuerSigningKey = new SymmetricSecurityKey(key),ValidateLifetime = true,ValidateIssuer = true,ValidateAudience = true,ValidAudience = jwtSettings.ValidAudience,ValidIssuer = jwtSettings.ValidIssuer};});// Other configurations...
Create a service to generate tokens: Create a new JwtTokenService.cs
file to generate tokens using the GetToken
function.
// JwtTokenService.csnamespace ShadyNagy.ApiTemplate.Infrastructure.Identity;public class JwtTokenService{private readonly JwtSettings _jwtSettings;public JwtTokenService(JwtSettings jwtSettings){_jwtSettings = jwtSettings;}public string GetToken(AuthenticationInfo authenticationInfo){// Token generation logic...}}
Create the IJwtTokenService interface: Create a new IJwtTokenService.cs
file with the following content:
// IJwtTokenService.csnamespace ShadyNagy.ApiTemplate.Core.Interfaces;public interface IJwtTokenService{string GetToken(AuthenticationInfo authenticationInfo);}
Register the service: Add the following line to your Startup.cs or Program.cs file to register the JwtTokenService:
builder.Services.AddScoped<IJwtTokenService, JwtTokenService>();
Secure your endpoints: Add the [Authorize]
attribute to any endpoint class you want to secure:
// Example of a secured endpoint classnamespace ShadyNagy.ApiTemplate.Api.Endpoints.BranchEndpoints;[Authorize]public class Add : BaseAsyncEndpoint.WithRequest<AddBranchRequest>.WithResponse<BranchDto>{// Endpoint logic...}
For a full example, visit the ShadyNagy.ApiTemplate GitHub repository. To use the ShadyNagy.ApiTemplate NuGet package, click here.
In this tutorial, we have explored how to implement JWT authentication in a .NET Core project. By following these steps, you can secure your APIs and ensure that only authorized users can access the resources they are allowed to.
If you want to learn more about JWT and authentication in .NET Core, consider checking out the following resources:
If you encounter any issues while implementing JWT authentication in your .NET Core project, consider the following troubleshooting tips:
Verify your package dependencies: Ensure that you have installed the necessary packages, such as Microsoft.AspNetCore.Authentication.JwtBearer
.
Check your configuration: Make sure you have correctly configured the JwtBearer settings in your Startup.cs or Program.cs file.
Inspect your tokens: Check the generated tokens to ensure that they contain the correct information and are signed properly.
Review your attribute usage: Double-check that you have added the [Authorize]
attribute to the appropriate endpoint classes.
Consult the official documentation: If you are still experiencing issues, refer to the official Microsoft documentation for more information on authentication and authorization in .NET Core.
We’d love to hear your feedback on this tutorial! If you have any questions or suggestions for improvement, please don’t hesitate to reach out. You can leave a comment below, or you can contact us through the following channels:
We’ll do our best to address any questions or concerns you may have. We look forward to hearing from you and helping you make the most of JWT authentication in your .NET Core projects!
Quick Links
Legal Stuff