What is Authentication?
Authentication is the process of verifying who the user is.
It ensures the user’s identity is valid, typically through:
- Username/Password
- Tokens (e.g., JWT)
- Cookies
- External providers (Google, Facebook, Azure AD)
Example: If you log in using your email and password, that’s authentication. If your credentials are correct, the server "knows" who you are.
2. What is Authorization?
Authorization is the process of determining what an authenticated user is allowed to do.
After you are authenticated:
- Are you allowed to access this endpoint?
- Do you have the required role?
- Do you have permission to perform a certain action?
What happens when the user logs in?
- User submits credentials via login form or API (e.g., /login)
- Backend validates the credentials (e.g., against a database)
- If valid, the server issues an authentication token (JWT or sets a cookie).
- On the next request, the client sends the token or cookie back
- The middleware validates it and sets the User. Identity
- Controllers/actions protected by [Authorize] now recognize the user
Example: JWT Authentication (API-Based)
dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer
builder.Services.AddAuthentication("Bearer") .AddJwtBearer("Bearer", options => { options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true, ValidIssuer = "your-app", ValidateAudience = true, ValidAudience = "your-client", ValidateIssuerSigningKey = true, IssuerSigningKey = new SymmetricSecurityKey( Encoding.UTF8.GetBytes("your-secret-key")), ValidateLifetime = true }; }); builder.Services.AddAuthorization();
var app = builder.Build(); app.UseAuthentication(); // Must be before UseAuthorization app.UseAuthorization(); app.MapControllers();
[HttpPost("login")] public IActionResult Login(LoginModel model) { if (model.Username == "admin" && model.Password == "password") // DB check in real case { var claims = new[] { new Claim(ClaimTypes.Name, model.Username), new Claim(ClaimTypes.Role, "Admin") }; var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("your-secret-key")); var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); var token = new JwtSecurityToken( issuer: "your-app", audience: "your-client", claims: claims, expires: DateTime.Now.AddHours(1), signingCredentials: creds); return Ok(new { token = new JwtSecurityTokenHandler().WriteToken(token) }); } return Unauthorized("Invalid credentials"); }
GET /api/secure-data Authorization: Bearer eyJhbGciOiJIUzI1NiIs...
[Authorize] [HttpGet("secure-data")] public IActionResult GetSecureData() { var username = User.Identity?.Name; return Ok($"This data is only visible to {username}"); }
- It decodes the token
- Sets HttpContext.User with claims and identity
JWT Token Structure.
- HEADER
- PAYLOAD
- SIGNATURE
{ "alg": "HS256", // Algorithm used (HMAC SHA-256) "typ": "JWT" // Token type }
- iss Issuer – who created the token
- aud Audience – who the token is for
- exp Expiration time (Unix timestamp)
- nbf Not before – token valid after this time
- iat Issued at time
- sub Subject – usually the user ID
- jti Token ID – unique identifier
{ "iss": "JwtAuthDemo", "aud": "JwtAuthClient", "exp": 1720542515, "sub": "123456" }
{ "name": "admin", "email": "admin@example.com", "role": "Admin", "department": "HR" }
HMACSHA256( base64UrlEncode(header) + "." + base64UrlEncode(payload), secret-key )