kmaruthi2002/universal-llm-skills/authentication-and-authorization
Claude Code and agent skill by kmaruthi2002/universal-llm-skills
- community
Checking that the SKILL.md file is still in the repository.
Design and implement who-are-you and what-may-you-do correctly: choosing between managed identity providers, auth libraries, and custom code; sessions vs. tokens (JWT, opaque, refresh); OAuth 2.0 and OpenID Connect flows (auth code + PKCE, client credentials, device flow); password storage, reset, and account recovery; MFA and passkeys/WebAuthn; API keys and service-to-service auth; RBAC, ABAC, and relationship-based access control; multi-tenant isolation; and the common auth bugs. Use when adding login, signup, SSO, social login, MFA, API authentication, roles and permissions, tenant isolation, or when debugging or reviewing auth code.
Install
npx vskill@latest install kmaruthi2002/universal-llm-skills/authentication-and-authorizationSKILL.md
The same SKILL.md was published earlier as kmaruthi2002/universal-llm-skills/authentication-and-authorization.
Authentication and Authorization
Authentication (authn) establishes who is making a request. Authorization (authz) decides whether that identity may perform this action on this resource. Both are deceptively simple to sketch and notoriously easy to get subtly wrong, and mistakes are directly exploitable. The central rule of this skill: reuse proven systems for the hard parts, and put your own effort into the parts only you can get right — your permission model and enforcing it everywhere.
Scope
Covers end-user and machine authentication, session and token handling, federated login, credentials and recovery, MFA, permission models, multi-tenancy, and the implementation hazards around all of these.
Related skills:
- General input handling, crypto hygiene, CSRF/XSS, secrets —
secure-coding. - Auditing an existing system —
security-audit. - API surface design (how auth appears in the API) —
api-design. - Schema for users, roles, and tenants —
database-design.
Core principles
1. Don't build what you can adopt
Use a managed identity provider (e.g. Auth0/Okta, Cognito, Entra ID, Firebase Auth, Clerk, Supabase Auth, WorkOS, Keycloak self-hosted) or a mature framework auth library (e.g. Django's auth, Devise, ASP.NET Identity, Spring Security, Auth.js/NextAuth, Passport, Lucia-style libraries) before writing authentication from scratch. Why: password hashing, timing-safe comparisons, session fixation, token validation, account enumeration, MFA enrolment, recovery flows, and federation protocols each contain well-known traps. A proven system has already been attacked and fixed. Your custom code has not.
Choosing among them:
| Option | Choose when | Trade-offs | |
|---|---|---|---|
| Managed IdP | You want SSO/social/enterprise federation, MFA, passkeys quickly; small team; compliance pressure | Cost per user, vendor lock-in, less control over UX and data residency | |
| Self-hosted IdP (e.g. Keycloak, Ory, Authentik, Zitadel) | Need control, on-prem, data residency, many apps | You operate and patch it | |
| Framework auth library | Single app, conventional login, framework already has strong defaults | Federation and MFA may need extra work | |
| Custom | Truly unusual requirements, and you have security expertise and review capacity | Highest risk; justify explicitly |
Follow whatever the project already uses. If it uses a provider, integrate with it properly rather than adding a second mechanism.
2. Authorization is enforced on the server, on every request, for every object
The UI can hide what a user may not do; only the server can prevent it. Every endpoint, job, and query that touches a resource must check that the authenticated principal may perform that action on that specific resource. Why: broken access control — especially insecure direct object references (changing an ID in a URL) — is the most common serious vulnerability in real applications, and it comes from checks that exist in most places but not all.
3. Centralize policy, decentralize nothing
Express permission rules in one place (a policy module, a policy engine, or middleware with a clear API), and make the safe path the easy path: e.g. data-access functions that require a principal and scope their queries, so forgetting the check is hard. Why: scattered if user.role == "admin" checks drift, contradict each other, and are impossible to audit.
4. Default deny
No access unless a rule grants it. New endpoints are protected by default; making something public is an explicit, reviewable act. Why: the failure mode of a forgotten rule should be "someone gets an error", not "everyone gets the data".
5. Credentials are toxic; minimize, protect, and expire them
Store as few credentials as possible, hash what you must store, scope and time-limit what you issue, and make revocation possible. Why: every credential will eventually leak somewhere (logs, browser storage, a laptop, a breach); limited scope and lifetime bound the damage.
Discovering context
Before changing auth:
- Identify the existing identity source (provider, library, custom tables), session or token mechanism, and where authorization checks live. Trace one authenticated request end to end: where is the credential read, validated, turned into a principal, and checked?
- Find the user, role, permission, and tenant models in the schema.
- Determine clients: server-rendered web, single-page app, mobile, CLI, third-party API consumers, other services. Each affects the right flow.
- Check requirements: enterprise SSO (SAML/OIDC), social login, MFA mandates, compliance (e.g. SOC 2, HIPAA, PCI DSS, regional privacy laws), password policy, session timeouts, audit logging.
- Look for existing tests of authorization; their absence is itself a finding.
- If the project already has a pattern for checking permissions, use it consistently. If it lacks one, raise that rather than adding another ad hoc check.
Sessions vs. tokens
Server-side sessions (session ID in a cookie)
The server stores session state; the browser holds an opaque random ID in a cookie.
- Pros: instant revocation (delete the session), small cookie, no sensitive data on the client, mature framework support.
- Cons: requires a session store shared across instances (database, Redis), cookies need CSRF protection.
- Best default for browser-based apps served from your own domain, including most SPAs on the same site (use a backend-for-frontend if the SPA talks to APIs).
Self-contained tokens (e.g. JWT access tokens)
Signed tokens carrying claims, validated without a lookup.
- Pros: stateless validation across services; suits APIs and distributed systems.
- Cons: hard to revoke before expiry; claims go stale (role changed, user disabled); size; many implementation pitfalls.
- Mitigations: short lifetimes (minutes), refresh tokens for renewal, a revocation or denylist check for high-risk actions, and re-reading critical attributes from the source of truth.
Opaque tokens
Random strings validated by lookup or introspection. Revocable like sessions, usable in headers like JWTs. A good choice for API keys and refresh tokens.
Decision table
| Client | Recommended default | |
|---|---|---|
| Server-rendered web app | Server-side session in a Secure; HttpOnly; SameSite cookie | |
| SPA on same site as its API | Cookie session (often via a backend-for-frontend), not tokens in JavaScript-accessible storage | |
| SPA calling third-party APIs | OAuth auth code + PKCE; prefer a backend-for-frontend holding tokens server-side | |
| Native mobile/desktop app | OAuth auth code + PKCE via the system browser; tokens in the platform secure store (Keychain, Keystore) | |
| CLI | Device authorization flow or loopback-redirect auth code + PKCE; tokens in the OS credential store | |
| Service-to-service | Client credentials, workload identity (cloud IAM, SPIFFE), or mTLS | |
| Third-party developers | API keys or OAuth client credentials, scoped and revocable |
Token and session handling rules
- Session IDs and tokens: generated by a CSPRNG, ≥128 bits of entropy.
- Regenerate the session ID on login and on privilege change (prevents session fixation).
- Cookies:
Secure,HttpOnly,SameSite=LaxorStrict, narrow scope; consider the__Host-prefix. - Avoid storing long-lived tokens in
localStorage/sessionStorage— any XSS can read them. If a browser must hold tokens, keep access tokens short-lived and in memory. - Expire sessions: an idle timeout and an absolute lifetime, set according to risk (banking minutes; consumer apps days to weeks with re-authentication for sensitive actions).
- Logout must invalidate server-side state (session, refresh token), not just delete the cookie.
- Refresh tokens: rotate on each use and detect reuse (a reused refresh token means theft — revoke the whole family). Bind to the client where the platform allows.
- Never put tokens in URLs (they end up in logs, history, and referrer headers), except where a protocol requires short-lived single-use codes.
JWT pitfalls
Use a maintained library and configure it strictly:
- Pin the accepted algorithm(s); reject
alg: noneand algorithm switching (e.g. an RS256 public key used as an HS256 secret). - Validate signature,
exp,nbf,iss, andaudevery time. Missing audience checks let a token for one service be used at another. - Fetch signing keys from the issuer's JWKS endpoint with caching and key rotation support; do not hardcode keys that will rotate.
- Do not put sensitive data in JWT payloads — they are encoded, not encrypted.
- Do not use an ID token as an API access token; they have different audiences and purposes.
OAuth 2.0 and OpenID Connect
OAuth 2.0 is for delegated authorization (an app obtaining access to an API on a user's behalf). OpenID Connect (OIDC) adds authentication on top (an ID token saying who the user is). "Log in with X" is OIDC.
Current best practice (reflected in the OAuth 2.0 Security Best Current Practice and OAuth 2.1 drafts):
| Flow | Use for | Notes | |
|---|---|---|---|
| Authorization code + PKCE | All user-facing clients: web, SPA, mobile, desktop, CLI with browser | PKCE for every client, including confidential ones | |
| Client credentials | Machine-to-machine, no user | Keep client secrets server-side; prefer private-key JWT or mTLS client auth where supported | |
| Device authorization | Input-constrained devices, CLIs without a browser | User approves on another device | |
| Refresh token | Renewing access | Rotation and reuse detection | |
| Implicit flow | Do not use | Tokens in URL fragments; superseded by code + PKCE | |
| Resource owner password credentials | Do not use | App sees the user's password; defeats the point of federation and MFA |
Implementation checks:
- Use a certified or widely used client library; do not hand-roll the protocol.
- Use and verify the
stateparameter (CSRF protection for the redirect) and thenoncefor OIDC. - Register exact redirect URIs; no wildcards, no open redirects on the callback path.
- Validate ID tokens fully (signature, issuer, audience, expiry, nonce).
- Request minimal scopes.
- Identify users by the stable subject identifier (
sub, scoped to the issuer), never by email alone. Emails change, can be unverified, and can be reused; linking accounts by unverified email enables account takeover. - For enterprise customers, SAML is still common; use a library or provider that handles it, as XML signature validation is a notorious source of bypasses.
Passwords
If you store passwords at all (prefer delegating to a provider):
This is the start of the file. Read the full SKILL.md on GitHub.
Security
- Security scanPassed, 90 of 100Pattern checks on the skill's files.
- Model reviewPassed
Quality evaluation
- Task evaluationNot runNo evaluation yet. Run one in Skill Studio.
Source
- SKILL.md in the repositoryCheckingskills/authentication-and-authorization/SKILL.md
Popularity
- 7-day trend score
- 0
Not refreshed yet.
Works with
Any agent vskill installs to: 56 targets in all. These 39 have a page on this site.
- Claude Code
- Cursor
- GitHub Copilot
- Windsurf
- Codex
- Gemini CLI
- Cline
- Amp
- Roo Code
- Goose
- Continue
- Kilo Code
- Junie
- Trae
- OpenHands
- Qwen Code
- AI Agent
- Tabnine Chat
- Sourcegraph Cody
- Amazon Q
- Firebase Genkit
- Sweep
- Devin
- Phind
- Mentat
- Claude Desktop
- Aider
- GPT Pilot
- Plandex
- bolt.new
- v0
- Replit Agent
- Anse
- TypingMind
- BetterChatGPT
- LibreChat
- Warp AI
- Pieces
- Fig AI
Embed badge
[](https://verified-skill.com/skills/kmaruthi2002/universal-llm-skills/authentication-and-authorization)