Courses/C#/JWT Authentication
    Back to Course

    Lesson 36: Authentication & Authorization with JWT

    Secure your ASP.NET Core APIs with JSON Web Tokens — issue, validate, and refresh tokens for stateless authentication.

    What You'll Learn

    • • JWT structure: Header, Payload, Signature
    • • Generate and validate tokens with claims
    • • Configure JWT Bearer authentication in ASP.NET Core
    • • Refresh token rotation for secure session extension

    🧠 Real-World Analogy

    A JWT is like a concert wristband. It contains your identity (name, ticket type) and is signed by the venue. Security guards check the wristband (validate the signature) without calling the box office (no database lookup). But wristbands expire — you need a refresh token to get a new one without re-purchasing.

    Generating & Validating JWTs

    A JWT has three parts: Header (algorithm), Payload (claims — user ID, email, roles, expiry), and Signature (proves the token wasn't tampered with). The server signs tokens with a secret key and validates incoming tokens against the same key.

    Generate, Decode & Validate JWTs

    Create JWT tokens with claims, inspect their contents, and validate signatures.

    Try it Yourself »
    C#
    using System;
    using System.IdentityModel.Tokens.Jwt;
    using System.Security.Claims;
    using System.Text;
    using Microsoft.IdentityModel.Tokens;
    
    class JwtService
    {
        private const string SecretKey = "YourSuperSecretKeyThatIsAtLeast32BytesLong!";
        private const string Issuer = "LearnCodingFast";
        private const string Audience = "LearnCodingFastAPI";
        
        // Generate a JWT token
        public static string GenerateToken(string userId, string email, string role)
        {
            var key = new Sym
    ...

    ASP.NET Core JWT Setup

    ASP.NET Core has built-in JWT Bearer authentication. Configure it in Program.cs, and protect endpoints with [Authorize]. The middleware automatically extracts the token from the Authorization: Bearer ... header.

    ASP.NET Core JWT Configuration

    Set up JWT Bearer authentication with validation and custom events.

    Try it Yourself »
    C#
    // Program.cs — Configure JWT Authentication in ASP.NET Core
    using Microsoft.AspNetCore.Authentication.JwtBearer;
    using Microsoft.IdentityModel.Tokens;
    using System.Text;
    
    var builder = WebApplication.CreateBuilder(args);
    
    // Add JWT Authentication
    builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
        .AddJwtBearer(options =>
        {
            options.TokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuer = true,
                ValidIssue
    ...

    Refresh Token Rotation

    Access tokens should be short-lived (15 min–1 hour). Refresh tokens let users get new access tokens without re-logging in. Token rotation means each refresh invalidates the old refresh token — if an attacker steals one, it's already expired.

    Refresh Token Rotation

    Implement secure token refresh with automatic rotation to prevent reuse.

    Try it Yourself »
    C#
    using System;
    using System.Security.Cryptography;
    
    // Refresh Token flow — extend sessions securely
    public class TokenPair
    {
        public string AccessToken { get; set; } = "";   // Short-lived (15 min)
        public string RefreshToken { get; set; } = "";   // Long-lived (7 days)
        public DateTime AccessExpiry { get; set; }
        public DateTime RefreshExpiry { get; set; }
    }
    
    public class AuthService
    {
        // In production, store refresh tokens in database
        private static readonly Dictionary<stri
    ...
    TokenLifetimeStoragePurpose
    Access15 min – 1 hourMemory onlyAPI authorization
    Refresh7 – 30 daysHttpOnly cookie / DBGet new access tokens

    Pro Tip

    Store your JWT secret in configuration (appsettings.json or environment variables), never in code. In production, use Azure Key Vault or AWS Secrets Manager. Consider asymmetric keys (RSA) for microservices where multiple services validate tokens.

    Common Mistakes

    • • Storing JWTs in localStorage — vulnerable to XSS; use HttpOnly cookies
    • • Long-lived access tokens — if stolen, attackers have extended access
    • • Not validating issuer/audience — any JWT would be accepted

    Lesson Complete!

    You've mastered JWT authentication with refresh token rotation. Next, implement role-based, policy-based, and claims-based security models.

    Sign up for free to track which lessons you've completed and get learning reminders.

    Previous

    Cookie & Privacy Settings

    We use cookies to improve your experience, analyze traffic, and show personalized ads. You can manage your preferences below.

    By clicking "Accept All", you consent to our use of cookies for analytics and personalized advertising. You can customize your preferences or reject non-essential cookies.

    Privacy PolicyTerms of Service