HomeContact

Apply JWT on Endpoints (.NET Core)

By Shady Nagy
Published in dotnet
July 22, 2022
3 min read
Apply JWT on Endpoints (.NET Core)

Table Of Contents

01
Introduction
02
What is JSON Web Token?
03
When should you use JSON Web Tokens?
04
Implementing JWT on a .NET Core project
05
Conclusion

Introduction

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.

What is JSON Web Token?

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.

When should you use JSON Web Tokens?

Here are some scenarios where JSON Web Tokens are useful:

Authorization

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.

Information Exchange

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.

Implementing JWT on a .NET Core project

To implement JWT in your .NET Core project, follow these steps:

1. Install the JwtBearer package

Install the Microsoft.AspNetCore.Authentication.JwtBearer package.

  1. 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...
  2. Create a service to generate tokens: Create a new JwtTokenService.cs file to generate tokens using the GetToken function.

    // JwtTokenService.cs
    namespace 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...
    }
    }
  3. Create the IJwtTokenService interface: Create a new IJwtTokenService.cs file with the following content:

    // IJwtTokenService.cs
    namespace ShadyNagy.ApiTemplate.Core.Interfaces;
    public interface IJwtTokenService
    {
    string GetToken(AuthenticationInfo authenticationInfo);
    }
  4. Register the service: Add the following line to your Startup.cs or Program.cs file to register the JwtTokenService:

    builder.Services.AddScoped<IJwtTokenService, JwtTokenService>();
  5. Secure your endpoints: Add the [Authorize] attribute to any endpoint class you want to secure:

    // Example of a secured endpoint class
    namespace 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.

Conclusion

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.

Further Reading

If you want to learn more about JWT and authentication in .NET Core, consider checking out the following resources:

Troubleshooting

If you encounter any issues while implementing JWT authentication in your .NET Core project, consider the following troubleshooting tips:

  1. Verify your package dependencies: Ensure that you have installed the necessary packages, such as Microsoft.AspNetCore.Authentication.JwtBearer.

  2. Check your configuration: Make sure you have correctly configured the JwtBearer settings in your Startup.cs or Program.cs file.

  3. Inspect your tokens: Check the generated tokens to ensure that they contain the correct information and are signed properly.

  4. Review your attribute usage: Double-check that you have added the [Authorize] attribute to the appropriate endpoint classes.

  5. 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.

Feedback and Questions

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:

  1. Email: shady@shadynagy.com
  2. Twitter: @ShadyNagy_
  3. LinkedIn: Shady Nagy
  4. GitHub: ShadyNagy

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!


Tags

#JWT#microsoft#dotnet6#dotnet#dotnet core#ef core#ef#entity framework#entity framework core#C##csharp#api#api template#endpoints template#shady nagy api template#ShadyNagy.ApiTemplate#CleanArchitecture#Clean Architecture#Secure#Security

Share


Previous Article
Value converters in Entity Framework Code (EF Core)
Shady Nagy

Shady Nagy

Software Innovation Architect

Topics

AI
Angular
dotnet
GatsbyJS
Github
Linux
Oracle
MS SQL

Related Posts

Unraveling Performance Bottlenecks in .NET Applications A Deep Dive with Code Examples
Unraveling Performance Bottlenecks in .NET Applications A Deep Dive with Code Examples
December 31, 2023
1 min

Quick Links

Contact Us

Social Media