Authentication, OAuth2, PKCE, JWT & Authorization (RBAC/ABAC)
Designing enterprise authentication and authorization architecture requires understanding JWT (JSON Web Tokens) validation mechanics, OAuth 2.0 with PKCE (Proof Key for Code Exchange) for public and single-page apps, and authorization models (RBAC vs ABAC).
This chapter details JWT header/payload/signature structure, RS256 asymmetric token verification, OAuth2 PKCE authorization flows, and fine-grained ABAC policy enforcement.
1. JWT Structure & Asymmetric Verification (RS256 vs. HS256)
A JSON Web Token (JWT) consists of three Base64URL-encoded components separated by dots (.): Header.Payload.Signature.
JWT Cryptographic Signing:
1. HS256 (Symmetric):
Uses a SINGLE shared secret key to both SIGN and VERIFY the JWT.
- Danger: All microservices must know the secret key; leaking it allows ANY service to forge valid JWTs!
2. RS256 (Asymmetric - Enterprise Standard):
Uses a PRIVATE KEY to sign JWTs (Auth Server), and a PUBLIC KEY to verify signatures (Resource Services).
- Advantage: Resource microservices verify tokens using the Public Key without being able to forge tokens!import jwt # PyJWT library
PUBLIC_KEY = """-----BEGIN PUBLIC KEY----- ... -----END PUBLIC KEY-----"""
def verify_jwt_token(token: str) -> dict:
try:
# RS256 Asymmetric Verification: Verifies signature, expiration ('exp'), and issuer ('iss')
payload = jwt.decode(
token,
PUBLIC_KEY,
algorithms=["RS256"],
options={"verify_exp": True, "verify_iss": True},
issuer="https://auth.company.com/"
)
return payload
except jwt.ExpiredSignatureError:
raise Exception("Token expired")
except jwt.InvalidTokenError:
raise Exception("Invalid authentication token")2. OAuth 2.0 Authorization Code Flow with PKCE
For SPA and Mobile applications, standard Authorization Code Flow risks secret leakage. PKCE (Proof Key for Code Exchange) solves this using a dynamic code challenge:
OAuth 2.0 PKCE Flow Sequence:
[ Client App ] ββ> (1. Generates secret 'code_verifier' & SHA256 'code_challenge')
|
βββ (2. Redirects to Auth Server with 'code_challenge') ββ> [ Auth Server ]
| |
|<ββ (3. Returns Authorization Code) ββββββββββββββββββββββββββββββ
|
βββ (4. Exchanges Authorization Code + raw 'code_verifier') ββ> [ Auth Server ]
| (Verifies SHA256(verifier) == challenge)
v
[ Issues Access Token ]3. Authorization Architecture: RBAC vs. ABAC
Authorization Models Comparison:
1. ROLE-BASED ACCESS CONTROL (RBAC):
Assigns permissions to coarse roles: @requires_role("admin").
- Limitation: Cannot express context-aware permissions (e.g. "Can edit post ONLY if owner AND before 5 PM").
2. ATTRIBUTE-BASED ACCESS CONTROL (ABAC):
Evaluates boolean policy rules against Subject, Resource, Action, and Environment attributes:
- Policy: user.id == resource.owner_id AND environment.time < 17:00