Skip to content
AuthN vs AuthZ: 5 Selection Dimensions & Choosing Between Custom Redis Session, Sa-Token, Keycloak, and JWT

AuthN vs AuthZ: 5 Selection Dimensions & Choosing Between Custom Redis Session, Sa-Token, Keycloak, and JWT

A comprehensive 12-question guide covering authentication vs authorization fundamentals, stateful vs stateless session trade-offs, five architectural selection dimensions, cost modeling across team sizes, migration strategies from custom sessions to unified identity platforms, JWT token revocation patterns, Keycloak's scope limitations for fine-grained permissions, protocol mixing anti-patterns, and layered auth architecture principles.

CodeSmart Hoops
CodeSmart Hoops
CodeSmart Hoops

Q1: Authentication (AuthN) vs Authorization (AuthZ)

AuthN answers "Who are you?" — login, identity verification via passwords, SSO, OIDC. AuthZ answers "What can you do?" — permission checks, resource access control via RBAC, ABAC, ACL. Selection must distinguish these first because some solutions only handle AuthN (pure OIDC issuing id_token) while others handle both (Keycloak issuing tokens and managing scopes). If the core pain point is fine-grained permissions (button-level, data-level) but you choose an AuthN-only solution, you'll end up building a separate AuthZ system.

Q2: Stateful vs Stateless Sessions

Stateful : Session stored server-side (Redis). Token is an opaque random string used to look up session. Active revocation by deleting session key.

Stateless : No session storage. Token is a self-contained JWT with all claims. Active revocation requires a blocklist (reintroduces state).

Stateful pros: Easy active revocation, instant bans, session management (multi-device lists, renewal). Cons: Depends on shared storage (Redis), network I/O, storage failure affects sessions, horizontal scaling needs shared storage. Stateless pros: No shared storage, local signature verification, naturally suits cross-domain microservices. Cons: Cannot actively revoke without blocklist (which reintroduces state), tokens can be large, issued tokens remain valid until expiry — leaked tokens are hard to handle. Trade-off: Strong session management (finance, immediate ban) → stateful; stateless microservices, cross-domain, performance-sensitive → stateless. Hybrid is common: gateway uses stateful sessions, inter-service uses JWT.

Q3: Five Selection Dimensions

Team size & capability : How complex a solution can the team handle?

System count & relationships : Single system, multi-system, or external-facing?

External requirements : Need to integrate third parties, expose APIs?

Compliance needs : Regulatory (e.g., China's MLPS), audit, identity federation?

Ops capability : Can the team maintain extra middleware/services?

Why not just compare features: Keycloak has the most features, but a small team cannot maintain a standalone cluster — adopting it becomes a disaster. Sa-Token has fewer features but a small team can ship in a week. Selection isn't about the "strongest" solution; it's about what the team can operate, what suffices now, and what can evolve. Feature set is the theoretical ceiling; team capability is the practical floor — the floor determines whether you can land it.

Q4: Single Admin Backend, ~10 Users — What to Choose? Why Not Keycloak?

Recommended: Sa-Token / custom Redis Session / even raw Servlet Session. Why Keycloak is over-engineering:

Deployment : Must run Keycloak service + database

Configuration : Realm, Client, users, roles — days of setup

Integration : Business apps must integrate OIDC Client

Operations : Keycloak needs monitoring, backup, upgrades

Resource waste : For 10 users, Keycloak consumes more server resources than the business app

Root cause: Keycloak's value lies in "multi-system SSO + standard protocols + user federation." With a single system, no external needs, no SSO requirement, 90% of its capabilities go unused — using a cannon to kill a mosquito. Correct approach: Progressive selection by scale. Single-system phase: Sa-Token/custom. When users grow, systems multiply, external needs arise → evolve to Spring Security + AS / Keycloak. Reserve evolution paths (abstract interfaces) instead of jumping to heavy solutions.

Q5: External API Platform — Why Must You Use Standard Protocols (OIDC)?

Core reason: Standard protocols (OIDC/OAuth2) are the hard currency of external scenarios; proprietary protocols (Sa-Token/custom) hit walls everywhere.

Partner gateways reject proprietary tokens — Standard OIDC access_token is JWT; any JWT-capable gateway can verify. Proprietary tokens are random strings requiring callback to origin system; partners won't integrate that.

Enterprise AD/LDAP federation requires standards — SAML/OIDC federation is standard; proprietary means building your own.

Third-party API consumers expect standard Authorization Code flow — OAuth2 is industry standard; developers know it. Proprietary needs custom docs and SDKs.

Compliance audits demand standards — MLPS, identity federation recognize standard protocols.

Typical anti-pattern: External SaaS uses Sa-Token, ships login in a week. Six months later: need to integrate enterprise AD, expose APIs to partners. Sa-Token's proprietary protocol fails everywhere; full rewrite costs far exceed initial dev time saved — selection was too shallow. Correct pattern: External platform uses Keycloak or Spring Authorization Server with standard OIDC; internal systems can use Sa-Token. Internal proprietary, external standard — common combination.

Q6: Choosing Among Custom Redis Session, Sa-Token, Keycloak, JWT

Custom Redis : Stateful, Proprietary protocol, External ❌, SSO ❌, Ops: Redis, Best for: Strong customization

Sa-Token : Stateful, Proprietary protocol, External ⚠️, SSO ✅, Ops: Redis, Best for: Fast internal

Keycloak : Stateful, Standard protocol, External ✅, SSO ✅, Ops: Standalone cluster, Best for: Enterprise unified identity

JWT : Stateless, Standard protocol, External ✅, SSO ⚠️, Ops: None, Best for: Stateless microservices

Decision matrix:

Single backend, fast launch, internal → Sa-Token

Strong customization (risk control, multi-tenant session isolation) → Custom Redis

Enterprise multi-system, unified identity, external → Keycloak

Stateless microservices, cross-domain, performance-sensitive → JWT

Multi-system SSO + self-built auth center → Spring Security + Spring Authorization Server

Key insight: External must be standard (OIDC); internal can be proprietary (Sa-Token/custom). It's not "which is better" but "which scenario matches."

Q7: Four Cost Categories & How Scale Shifts Weight

Development cost : Custom Medium, Sa-Token Low, Spring Security+AS High, Keycloak Medium, JWT Low

Operations cost : Custom Redis, Sa-Token Redis, Spring Security+AS Redis+AS, Keycloak Standalone cluster, JWT None

Learning cost : Custom Low, Sa-Token Low, Spring Security+AS High, Keycloak Medium, JWT Medium

Migration cost (out) : Custom High, Sa-Token Medium, Spring Security+AS Medium, Keycloak Medium, JWT Low

Scale impact on cost weights:

Small scale: Development cost sensitive; ops and scaling costs acceptable → choose Sa-Token/custom, dev speed matters most.

Large scale: Ops and scaling costs dominate; dev cost amortized → choose Keycloak/standard solutions; standardization and out-of-the-box maturity actually save more.

Hidden costs to count: Security vulnerability cost (custom must patch yourself), extension cost (proprietary protocol requires rewrite for external), personnel turnover cost (niche solutions slower to onboard), compliance cost (MLPS/audit may need extra development).

Q8: Evolving from Custom Session to Unified Identity Platform — Migration Pitfalls & Why Abstraction Matters

Evolution path: Phase 0 raw login → Phase 1 custom/Sa-Token → Phase 2 multi-system SSO → Phase 3 unified identity platform → Phase 4 identity federation/external. Each phase picks the best-fit solution, reserving path to next phase.

Migration watchouts:

Progressive migration: New and old coexist, canary switch — no big-bang cutover (risk of full-site outage).

Dual-login session compatibility: During migration both systems run; ensure user logged in old system is recognized in new — dual-write (write to both on login), dual-read (check new then fallback to old), canary (gradual cutover by user/tenant %).

User identity alignment: Build old↔new user ID mapping; preserve historical data continuity; don't invalidate all sessions and kick everyone.

Protocol-first design: Even in Phase 1 with proprietary protocol, design token flow with OAuth2 mindset to reduce future migration cost.

Why abstraction isolation matters: Business code should depend on interfaces, not frameworks.

// Business depends on interface, not framework
public interface AuthService {
  SessionInfo login(String username, String password);
  SessionInfo verify(String token);
  void logout(String token);
}

// Sa-Token implementation (Phase 1)
@Service
public class SaTokenAuthServiceImpl implements AuthService { ... }

// Keycloak implementation (Phase 3 migration)
@Service
public class KeycloakAuthServiceImpl implements AuthService { ... }

Migration swaps only the implementation class; business code untouched. If business code directly calls StpUtil.hasPermission() everywhere, migrating to Keycloak means rewriting all call sites — the anti-pattern in section 5.3. Abstract interface is migration "insurance": tiny cost, huge payoff.

Q9: JWT Stateless "Token Revocation Blind Spot" & Solutions

Blind spot: JWT is self-contained; server stores no session. Once issued, it's valid until expiry. Cannot actively revoke — even if user changes password, gets banned, or token leaks, the JWT remains valid until expiry. This is the price of "stateless."

Short TTL + Refresh Token : access_token 15 min, refresh_token 7 days; on refresh, check user status. Cost: Refresh adds network I/O; need seamless refresh UX.

Blocklist : Store revoked jti in Redis; check on validation. Cost: Regresses to stateful (Redis lookup); loses stateless advantage.

Version number in token : Token includes hash version of user password; password change increments version, old tokens invalid. Cost: Adds extra fields to token.

Short TTL without renewal : Sensitive ops: 30 min expiry, no sliding renewal. Cost: Poor UX; frequent re-login.

Practical picks:

General business: Short TTL + Refresh Token; on refresh, verify user status (deny new token if banned).

Strong session management (finance, immediate ban): Use stateful (Sa-Token/custom), not JWT.

Sensitive operations: Short TTL without renewal (30 min expiry).

Key insight: JWT fits "no active revocation needed"; strong session management needs stateful. Don't force JWT for "stateless elegance" and lose revocation capability.

Q10: Keycloak Handles AuthN — Who Owns Button-Level Permissions? Why?

Answer: Business system implements button-level permissions via RBAC/ABAC; Keycloak does not.

AuthN + Scope AuthZ : Verify identity, coarse scopes (e.g., read:order) → Keycloak

Business Fine-Grained Permissions : Button-level (export button), data-level (own-department orders only) → Business system RBAC/ABAC

Reasons:

Keycloak scopes are coarse — It governs "can access order service," not "can click export button in order list."

Business permissions couple tightly to business — "Own-department orders" depends on business org structure and data model; Keycloak doesn't understand business.

Permissions change frequently — Business permissions evolve with business; putting them in Keycloak means frequent Realm config changes — impractical.

Correct architecture: Layered AuthN/AuthZ. Keycloak does L2 (AuthN) + L3 (Token issuance); business system does L4 (RBAC/ABAC). Keycloak token carries sub (user ID) + scope (coarse); business system uses sub to query its own permission tables for fine-grained decisions.

Misconception: "Keycloak installed → it owns button permissions too" — confusing IdP with permission center, conflating AuthN and AuthZ.

Q11: "Protocol Mixing" Anti-Pattern & Business-Framework Coupling

Protocol mixing anti-pattern: One system runs multiple incompatible auth schemes — e.g., login uses Sa-Token, external API uses OAuth2, internal APIs use custom token, external uses JWT. Result: maintain multiple auth logics, tokens don't interoperate, new hires confused.

How to avoid:

Unified auth entry: One system, one auth scheme; external uses standard OIDC, internal also unified where possible.

Gateway unified auth: Push auth validation to gateway; downstream microservices trust gateway-passed identity.

Protocol-first design: Even with proprietary protocol, design token flow with OAuth2 mindset to lower future migration cost.

Business-framework coupling problem (anti-pattern 5.3):

// Anti-pattern: Business code directly depends on Sa-Token
@GetMapping("/order")
public Order getOrder(Long id) {
  if (!StpUtil.hasPermission("order:view")) { // Framework API scattered in business code
    throw new ForbiddenException();
  }
  return orderService.get(id);
}

Migrating to Spring Security requires rewriting every StpUtil.hasPermission call — deep coupling, migration cost explodes.

Correct approach: Abstract AuthService interface; business depends on interface, framework implements it.

public interface AuthService {
  boolean hasPermission(String permission);
}

@GetMapping("/order")
public Order getOrder(Long id) {
  if (!authService.hasPermission("order:view")) { // Depends on interface, not framework
    throw new ForbiddenException();
  }
  return orderService.get(id);
}

Migration changes only AuthService implementation; business code untouched. This is the core value of "abstraction isolation" — decouple business from framework, make selection evolvable.

Q12: AuthN/AuthZ Layered Architecture & Why IdP Shouldn't Own Business Permissions

Layered architecture:

Identity Source : Store users, passwords, org structure → DB, LDAP, AD

Authentication : Verify identity → Custom, Sa-Token, Keycloak

Token : Issue/validate tokens → OAuth2/OIDC, JWT, Custom

Authorization : Permission decisions → RBAC/ABAC

Audit : Logging & traceability → Log systems, SIEM

Keycloak covers L1-L3 + L5, but not deep into L4 (business fine-grained permissions). Sa-Token covers L2-L4, but L1/L5 need custom work. Selection must clarify "which layers am I buying?"

Why IdP shouldn't own business permissions:

Single responsibility: IdP (Keycloak) owns "verify identity + issue token"; business permissions are "verify capability." Different concerns. IdP absorbing business permissions becomes bloated "permission mudball."

Business permissions couple to business: "Own-department orders," "edit only self-created" — these data-level permissions depend on business org structure and data model; IdP doesn't know business.

Frequent permission changes: Business permissions evolve with business; putting them in IdP means frequent Realm config changes — ops burden.

Multi-IdP future: If later integrating multiple IdPs (each enterprise customer's own AD), business permissions must be centralized in business system, not scattered across IdPs.

Correct pattern: IdP handles L2-L3 (AuthN + Token); token carries sub (user ID) + scope (coarse); business system handles L4 (RBAC/ABAC), using sub to query its own permission tables for fine-grained decisions. AuthN and AuthZ layered, each doing its job.

Key insight: During selection, decide per layer; don't expect one framework to cover all — Keycloak's "covers everything" illusion leads to stuffing business permissions into Realm, ending in ops nightmare.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

AuthenticationMigration StrategyLayered ArchitectureJWTauthorizationRBACProtocol DesignSession ManagementSa-TokenKeycloakOIDCToken RevocationArchitecture SelectionAuthNAuthZ
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.