JWT Authentication

JWT Authentication And Refresh Tokens In ASP.NET Core

Learn how to implement JWT Authentication and Refresh Tokens in ASP.NET Core APIs including token generation, validation, security best practices, role-based authorization, and production-ready authentication architecture.

23 Jun 2026 12 min read 9 Views
JWT Authentication And Refresh Tokens In ASP.NET Core

JWT Authentication And Refresh Tokens In ASP.NET Core

```

Authentication is one of the most important aspects of modern web applications and APIs. JWT (JSON Web Token) authentication has become the standard approach for securing ASP.NET Core APIs because it is lightweight, scalable, and works well in distributed systems and microservices architectures.

What Is JWT?

JWT stands for JSON Web Token. It is a compact and self-contained token used to securely transmit user information between parties.

A JWT contains three parts:

  • Header
  • Payload
  • Signature
xxxxx.yyyyy.zzzzz

Why Use JWT Authentication?

  • Stateless authentication
  • Scalable architecture
  • Works with APIs
  • Supports mobile applications
  • Supports microservices
  • Easy integration with cloud environments

JWT Authentication Flow

  1. User submits username and password
  2. Server validates credentials
  3. Server generates JWT token
  4. Token returned to client
  5. Client sends token in Authorization header
  6. API validates token
  7. Request is authorized

Installing JWT Package

Install-Package
Microsoft.AspNetCore.Authentication.JwtBearer

Configure JWT Authentication

builder.Services
.AddAuthentication(
    JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
    options.TokenValidationParameters =
        new TokenValidationParameters
        {
            ValidateIssuer = true,
            ValidateAudience = true,
            ValidateLifetime = true,
            ValidateIssuerSigningKey = true
        };
});

Configure Authentication Middleware

app.UseAuthentication();

app.UseAuthorization();

Authentication must be registered before authorization.

Creating JWT Tokens

var tokenHandler =
    new JwtSecurityTokenHandler();

var key =
    Encoding.UTF8.GetBytes(secretKey);

var tokenDescriptor =
    new SecurityTokenDescriptor
    {
        Subject = new ClaimsIdentity(
            new[]
            {
                new Claim(
                    ClaimTypes.Name,
                    username)
            }),

        Expires =
            DateTime.UtcNow.AddMinutes(30),

        SigningCredentials =
            new SigningCredentials(
                new SymmetricSecurityKey(key),
                SecurityAlgorithms.HmacSha256Signature)
    };

var token =
    tokenHandler.CreateToken(
        tokenDescriptor);

Adding Claims

Claims store user information inside the token.

new Claim(
    ClaimTypes.Name,
    user.UserName),

new Claim(
    ClaimTypes.Role,
    "Admin")

Role-Based Authorization

[Authorize(Roles = "Admin")]
public IActionResult Dashboard()
{
    return View();
}

What Is A Refresh Token?

Access tokens usually have a short lifetime. Refresh tokens allow users to obtain a new access token without logging in again.

This improves both security and user experience.

Refresh Token Flow

  1. User logs in
  2. Server generates Access Token
  3. Server generates Refresh Token
  4. Access Token expires
  5. Client sends Refresh Token
  6. Server issues new Access Token

Refresh Token Table Example

CREATE TABLE RefreshTokens
(
    Id INT IDENTITY(1,1),
    UserId INT,
    Token NVARCHAR(MAX),
    ExpiryDate DATETIME
)

Generating Refresh Tokens

var refreshToken =
    Guid.NewGuid().ToString();

Refresh tokens should be stored securely in the database.

Token Validation

When a request arrives, ASP.NET Core automatically validates:

  • Issuer
  • Audience
  • Expiration
  • Signature
  • Signing key

Security Best Practices

  • Use HTTPS only
  • Store secrets securely
  • Use short-lived access tokens
  • Rotate refresh tokens
  • Validate all claims
  • Store refresh tokens in database
  • Implement token revocation

JWT In Microservices

JWT is widely used in microservices because services can validate tokens without calling a centralized authentication server for every request.

Azure Integration

JWT authentication can be integrated with:

  • Azure Active Directory
  • Azure AD B2C
  • Microsoft Entra ID
  • Azure API Management

Production Support Scenario

A production application was randomly logging users out. Investigation showed that token expiration was configured for only five minutes. Increasing expiration time and implementing refresh tokens resolved the issue.

Common Interview Questions

  • What is JWT?
  • How does JWT authentication work?
  • What are Claims?
  • What is the difference between Authentication and Authorization?
  • Why use Refresh Tokens?
  • How do you secure JWT tokens?
  • How does token validation work?
  • How would you implement logout with JWT?

Common Mistakes

  • Storing secrets in source code
  • Using long-lived access tokens
  • Not validating token expiration
  • Not implementing refresh tokens
  • Ignoring token revocation

Best Practices

  • Use HTTPS everywhere
  • Store secrets in Key Vault
  • Use Refresh Tokens
  • Use role-based authorization
  • Log authentication events
  • Monitor failed login attempts

Conclusion

JWT Authentication is the preferred authentication mechanism for modern ASP.NET Core APIs. When combined with Refresh Tokens, it provides a secure, scalable, and user-friendly authentication system suitable for enterprise applications, cloud deployments, and microservices architectures.

NEED EXPERT HELP?

Need Real-Time ASP.NET Core, Azure & SQL Server Support?

Working on production issues, deployment failures, performance bottlenecks, authentication problems, Azure hosting, Docker containers, Microservices, Entity Framework Core, or SQL Server optimization? Our experienced enterprise support team can help you resolve critical issues quickly and confidently.


10+ Years
Industry Experience
ASP.NET Core
Production Support
Azure & DevOps
Cloud Expertise
SQL Server
Performance Tuning