Token based authentication in asp net core

Introduction

Token based authentication is a popular method used in ASP.NET Core to secure web applications. It involves generating a token that is sent to the client and then included in subsequent requests to authenticate the user.

Generating a Token

To generate a token in ASP.NET Core, you can use the built-in authentication . This middleware provides options for configuring token generation, such as the token issuer, audience, expiration time, and signing key.


services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options =>
    {
        options.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuer = true,
            ValidateAudience = true,
            ValidateLifetime = true,
            ValidateIssuerSigningKey = true,
            ValidIssuer = "your-issuer",
            ValidAudience = "your-audience",
            IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("your-signing-key"))
        };
    });

In the above example, we configure the authentication middleware to use JWT bearer authentication scheme. We also specify the token validation parameters, including the issuer, audience, , and signing key. These parameters are used to validate the token received from the client.

Securing Endpoints

Once the token generation is configured, you can secure your endpoints by the [Authorize] attribute to the respective controllers or actions. This attribute ensures that only authenticated requests with a valid token can access the protected resources.


[ApiController]
[Route("api/[controller]")]
[Authorize]
  UserController : ControllerBase
{
    // Controller actions
}

In the above example, the [Authorize] attribute is applied to the UserController class, which means that all actions within this controller require authentication. If a request is made without a valid token, the server will with a 401 Unauthorized status code.

Handling Token in Client

On the client side, you need to include the token in the request headers for subsequent authenticated requests. This can be done by adding an Authorization with the value .


HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "your-token");

In the above example, we create an instance of HttpClient and set the Authorization header to include the token. This ensures that the subsequent requests made by the client are authenticated.

Conclusion

Token based authentication is a powerful mechanism for securing ASP.NET Core applications. By generating and validating tokens, you can ensure that only users can access protected resources. With the examples provided above, you should now have a good of how to implement token based authentication in ASP.NET Core.

Rate this post

Leave a Reply

Your email address will not be published. Required fields are marked *

Table of Contents