</>
Skip to content
ASP lessons (36/40)

ASP — ASP.NET Authentication

JWT Authentication

builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options =>
    {
        options.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuer = true,
            ValidateAudience = true,
            ValidateLifetime = true,
            ValidateIssuerSigningKey = true,
            ValidIssuer = builder.Configuration["Jwt:Issuer"],
            ValidAudience = builder.Configuration["Jwt:Audience"],
            IssuerSigningKey = new SymmetricSecurityKey(
                Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"]))
        };
    });

Generate Token

public string GenerateToken(User user)
{
    var claims = new[]
    {
        new Claim(ClaimTypes.Name, user.Username),
        new Claim(ClaimTypes.Email, user.Email)
    };
    
    var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt:Key"]));
    var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
    
    var token = new JwtSecurityToken(
        issuer: _config["Jwt:Issuer"],
        audience: _config["Jwt:Audience"],
        claims: claims,
        expires: DateTime.Now.AddHours(1),
        signingCredentials: creds
    );
    
    return new JwtSecurityTokenHandler().WriteToken(token);
}

Protect Endpoints

[Authorize]
[ApiController]
[Route("api/[controller]")]
public class ProtectedController : ControllerBase
{
    [HttpGet]
    public IActionResult Get()
    {
        return Ok("Authorized content");
    }
}

Mini Practice

  1. Configure JWT authentication
  2. Generate tokens
  3. Protect endpoints
  4. Handle unauthorized requests

Up Next

Continue with ASP.NET Entity Framework — Entity Framework.

Related Topics

Frequently Asked Questions about ASP.NET Authentication

What is ASP.NET Authentication in ASP?

ASP.NET Authentication is a fundamental concept in ASP. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn ASP.NET Authentication?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn ASP.NET Authentication.

Why is ASP.NET Authentication important in ASP?

ASP.NET Authentication is essential for ASP development. Understanding this concept will help you write better code and solve real-world problems more effectively.