JWT Authentication in ASP.NET Core

>

πŸ’‘ Concept Name

JWT Authentication Integration

πŸ“˜ Quick Intro

JWT (JSON Web Token) is a token-based authentication mechanism used to securely transmit user identity. It's compact, self-contained, and signed β€” ideal for APIs in ASP.NET Core. Clients receive a token upon login and send it on each subsequent request for authorization.

🧠 Analogy / Short Story

Imagine a movie ticket with your name, seat, and validity printed. Once verified at entry, you don’t need to prove your identity again β€” just flash the ticket. JWT works similarly. It contains your identity and permissions, and once issued, servers only need to validate the token without storing session data.

πŸ”§ Technical Explanation

JWT tokens are issued after successful authentication and signed using HMAC or RSA algorithms. The token includes a payload (claims), issuer, expiration, and is sent via HTTP header using `Authorization: Bearer {token}`.

ASP.NET Core uses `JwtBearerDefaults.AuthenticationScheme` middleware, and you can validate tokens using `TokenValidationParameters` configured in `Program.cs`.

🎯 Purpose & Use Case

  • βœ… Secure API endpoints using stateless authentication
  • βœ… Avoid session storage or server-side state management
  • βœ… Support mobile and single-page apps (SPA)
  • βœ… Integrate with OAuth/OpenID systems
  • βœ… Control user access with claims and roles

πŸ’» Real Code Example

// Program.cs configuration
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options =>
    {
        options.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuer = true,
            ValidIssuer = "your-app",
            ValidateAudience = true,
            ValidAudience = "your-client",
            ValidateLifetime = true,
            IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("your-secret-key")),
            ValidateIssuerSigningKey = true
        };
    });

app.UseAuthentication();
app.UseAuthorization();

❓ Interview Q&A

Q1: What is JWT?
A: A JSON-based token used to represent user claims securely.

Q2: Why is JWT stateless?
A: Because server doesn’t store token; validation is done on each request.

Q3: Which header carries the token?
A: `Authorization: Bearer {token}`

Q4: What is `TokenValidationParameters`?
A: It defines how tokens are validated in ASP.NET Core.

Q5: Can we customize claims in JWT?
A: Yes, you can add custom claims like `role`, `email`, etc.

Q6: Which algorithm is commonly used to sign JWT?
A: HMAC SHA256 (HS256) or RSA.

Q7: Can JWT expire?
A: Yes, using the `exp` claim.

Q8: How do we invalidate a JWT before expiry?
A: Either change the signing key or use a token blacklist mechanism.

Q9: What is the `aud` claim?
A: It identifies the intended recipient of the token.

Q10: Is JWT suitable for WebSockets?
A: Yes, by sending the token during connection handshake.

πŸ“ MCQs

Q1. What does JWT stand for?

  • Java Web Token
  • JSON Web Token
  • JWT Web Type
  • JavaScript Web Token

Q2. Which header carries the JWT in HTTP request?

  • Token
  • Header
  • Authorization
  • BearerToken

Q3. What does `ValidateLifetime` do?

  • Encrypt token
  • Checks signature
  • Checks token expiry
  • Verify issuer

Q4. Which key is used to validate JWT signature?

  • Issuer
  • ClientKey
  • SessionID
  • IssuerSigningKey

Q5. What is the correct authentication scheme for JWT?

  • JwtAuth
  • TokenAuth
  • BearerAuth
  • JwtBearerDefaults.AuthenticationScheme

Q6. What algorithm is commonly used to sign JWT?

  • SHA1
  • HS256
  • AES
  • RSA128

Q7. Which middleware enables JWT auth?

  • UseJwt()
  • EnableToken()
  • UseAuthentication()
  • UseSession()

Q8. What’s the purpose of the `exp` claim?

  • Username
  • Encrypted password
  • Expiration time
  • Request ID

Q9. Which tool is best to decode JWT online?

  • jwt.io
  • auth.net
  • tokencheck.com
  • jsonweb.com

Q10. How can you revoke a JWT?

  • It auto expires
  • Clear cookie
  • Change secret or use blacklist
  • Delete from DB

πŸ’‘ Bonus Insight

JWTs should be short-lived to reduce security risk. Always use HTTPS to prevent man-in-the-middle attacks. Avoid storing sensitive user data directly in token payload.

πŸ“„ PDF Download

Need a handy summary for your notes? Download this topic as a PDF!

πŸ’¬ Feedback
πŸš€ Start Learning
Share:

Tags: