How to set up JWT-based authentication in ASP.NET Core

5/8/2023
Back to List

ASP.NET Core provides several options for authentication, including cookie-based authentication, token-based authentication (using JWT), and external authentication providers such as Google, Facebook, and Twitter. Here's a brief overview of how to set up JWT-based authentication in ASP.NET Core:


  1. Add authentication middleware to the application's Startup.cs file. This middleware can be added by calling the AddAuthentication() method and specifying the authentication scheme you want to use (in this case, JWT-based authentication).

    public void ConfigureServices(IServiceCollection services)
    {
    // Add authentication services
    services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options =>
    {
    options.TokenValidationParameters = new TokenValidationParameters
    {
    ValidateIssuer = true,
    ValidateAudience = true,
    ValidateLifetime = true,
    ValidateIssuerSigningKey = true,
    ValidIssuer = Configuration["Jwt:Issuer"],
    ValidAudience = Configuration["Jwt:Audience"],
    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:Key"]))
    };
    });
    }
  2. Configure the authentication middleware to use the JWT-based authentication scheme. This is done in the Configure() method of Startup.cs.

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
    // Add authentication middleware
    app.UseAuthentication();
    }
  3. Protect the desired routes or controllers with the [Authorize] attribute. This attribute can be placed at the controller or action level to restrict access to authorized users only.

    [Authorize]
    public class HomeController : Controller
    {
    public IActionResult Index()
    {
    return View();
    }
    }
  4. Create a JWT token when the user successfully authenticates. This token will contain the user's claims, which can be used to authorize subsequent requests.

    [HttpPost("login")]
    public async Task<IActionResult> Login(LoginViewModel model)
    {
    // Validate user credentials
    var user = await _userManager.FindByEmailAsync(model.Email);
    if (user == null || !await _userManager.CheckPasswordAsync(user, model.Password))
    {
    return Unauthorized();
    }

    // Create token
    var tokenHandler = new JwtSecurityTokenHandler();
    var key = Encoding.ASCII.GetBytes(Configuration["Jwt:Key"]);
    var tokenDescriptor = new SecurityTokenDescriptor
    {
    Subject = new ClaimsIdentity(new Claim[]
    {
    new Claim(ClaimTypes.NameIdentifier, user.Id),
    new Claim(ClaimTypes.Email, user.Email)
    }),
    Expires = DateTime.UtcNow.AddDays(7),
    SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
    };
    var token = tokenHandler.CreateToken(tokenDescriptor);
    var tokenString = tokenHandler.WriteToken(token);

    return Ok(new { token = tokenString });
    }
  5. Add the JWT token to the Authorization header of subsequent requests. This can be done using a bearer token, like so:

    Authorization: Bearer <Token>

SuperChad
Gravatar About Sean Nelson
I like codes and stuff.

0 comments