Authentication ও Authorization — JWT, OAuth 2.0

লেসন ১৯ / ৫০

AuthN vs AuthZ

  • AuthN — তুমি কে? (login)
  • AuthZ — কী করতে পারো? (permission)

Session vs Token

SessionJWT
Server statefulStateless
Easy invalidationHard until expiry
Scaling issueScalable

JWT Structure

header.payload.signature

Header: {"alg":"HS256","typ":"JWT"}
Payload: {"sub":"123","exp":1700000000,"role":"admin"}
Signature: HMACSHA256(base64(h)+"."+base64(p), SECRET)

JWT Best Practices

  • Short expiry (15min) + refresh token
  • HTTPS, HttpOnly cookie
  • No sensitive data payload
  • RS256 prefer HS256 distributed-এ
  • Critical action-এ revocation list

Refresh Flow

Login → access (15m) + refresh (7d)
Access expired → POST /refresh
                → new access

OAuth 2.0 ⭐

3rd-party delegation framework। (Login with Google)

Authorization Code Flow

1. App → Google /authorize?client_id=...
2. User logs in, consents
3. Google → redirect with ?code=xyz
4. App POST /token with code+secret
5. Google → access_token + refresh_token

OAuth Flows

  • PKCE — mobile/SPA
  • Client Credentials — service-to-service
  • Device Code — TV, IoT
  • Implicit, Password — deprecated

OpenID Connect (OIDC)

OAuth 2.0 + identity layer। Returns ID token (JWT) with user info।

RBAC

Roles: admin, manager, user
Perms: order.create, order.read, order.delete

[Authorize(Roles = "admin,manager")]
[HttpDelete("{id}")]
public IActionResult Delete(int id) {}

ABAC ⭐

Context-aware (user, resource, action, env)। More flexible।

// "Manager edit own dept orders, business hours"
if (user.dept == order.dept && user.role == "manager"
    && isBusinessHours()) allow();

SSO

SAML, OIDC দিয়ে একবার login সব app-এ।