auth-patterns
Use when implementing authentication (JWT, sessions, OAuth), authorization (RBAC, ABAC), password hashing, MFA, or security best practices for backend services.
What this skill does
# Authentication Patterns
## Overview
Authentication and authorization patterns for securing backend applications.
## Authentication Methods
### JWT (JSON Web Tokens)
```
┌─────────────────────────────────────────────────────────┐
│ Header.Payload.Signature │
│ │
│ Header: { "alg": "HS256", "typ": "JWT" } │
│ Payload: { "sub": "user123", "exp": 1609459200, ... } │
│ Signature: HMACSHA256(base64(header) + "." + │
│ base64(payload), secret) │
└─────────────────────────────────────────────────────────┘
```
**Token Structure:**
```typescript
interface JWTPayload {
sub: string; // Subject (user ID)
iat: number; // Issued at
exp: number; // Expiration
iss?: string; // Issuer
aud?: string; // Audience
roles?: string[]; // Custom claims
}
```
**Implementation:**
```typescript
import jwt from 'jsonwebtoken';
const ACCESS_TOKEN_EXPIRY = '15m';
const REFRESH_TOKEN_EXPIRY = '7d';
function generateTokens(user: User) {
const accessToken = jwt.sign(
{ sub: user.id, roles: user.roles },
process.env.JWT_SECRET,
{ expiresIn: ACCESS_TOKEN_EXPIRY }
);
const refreshToken = jwt.sign(
{ sub: user.id, type: 'refresh' },
process.env.JWT_REFRESH_SECRET,
{ expiresIn: REFRESH_TOKEN_EXPIRY }
);
return { accessToken, refreshToken };
}
function verifyAccessToken(token: string): JWTPayload {
return jwt.verify(token, process.env.JWT_SECRET) as JWTPayload;
}
```
### Session-Based Authentication
```typescript
// Session storage (Redis recommended for production)
interface Session {
userId: string;
createdAt: Date;
expiresAt: Date;
userAgent?: string;
ipAddress?: string;
}
// Login
async function login(email: string, password: string, req: Request) {
const user = await findUserByEmail(email);
if (!user || !await verifyPassword(password, user.passwordHash)) {
throw new AuthError('Invalid credentials');
}
const sessionId = generateSecureId();
await redis.set(`session:${sessionId}`, JSON.stringify({
userId: user.id,
createdAt: new Date(),
expiresAt: addDays(new Date(), 7),
userAgent: req.headers['user-agent'],
}), 'EX', 7 * 24 * 60 * 60);
return sessionId;
}
// Middleware
async function authenticate(req: Request, res: Response, next: NextFunction) {
const sessionId = req.cookies.session;
if (!sessionId) return res.status(401).json({ error: 'Unauthorized' });
const session = await redis.get(`session:${sessionId}`);
if (!session) return res.status(401).json({ error: 'Session expired' });
req.user = JSON.parse(session);
next();
}
```
### OAuth 2.0 / OpenID Connect
```
┌──────────┐ ┌──────────────┐
│ Client │──────1. Auth Request──────▶│ Auth │
│ (App) │◀─────2. Auth Code──────────│ Provider │
│ │──────3. Exchange Code──────▶│ (Google, │
│ │◀─────4. Access Token───────│ GitHub) │
│ │──────5. API Requests───────▶│ │
└──────────┘ └──────────────┘
```
**Implementation with Passport.js:**
```typescript
import passport from 'passport';
import { Strategy as GoogleStrategy } from 'passport-google-oauth20';
passport.use(new GoogleStrategy({
clientID: process.env.GOOGLE_CLIENT_ID,
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
callbackURL: '/auth/google/callback',
},
async (accessToken, refreshToken, profile, done) => {
const user = await findOrCreateUser({
provider: 'google',
providerId: profile.id,
email: profile.emails[0].value,
name: profile.displayName,
});
done(null, user);
}
));
// Routes
app.get('/auth/google', passport.authenticate('google', {
scope: ['profile', 'email']
}));
app.get('/auth/google/callback',
passport.authenticate('google', { failureRedirect: '/login' }),
(req, res) => res.redirect('/dashboard')
);
```
## Password Security
### Hashing
```typescript
import bcrypt from 'bcrypt';
const SALT_ROUNDS = 12;
async function hashPassword(password: string): Promise<string> {
return bcrypt.hash(password, SALT_ROUNDS);
}
async function verifyPassword(password: string, hash: string): Promise<boolean> {
return bcrypt.compare(password, hash);
}
```
### Password Requirements
```typescript
const PASSWORD_RULES = {
minLength: 8,
maxLength: 128,
requireUppercase: true,
requireLowercase: true,
requireNumber: true,
requireSpecial: true,
};
function validatePassword(password: string): string[] {
const errors: string[] = [];
if (password.length < PASSWORD_RULES.minLength) {
errors.push(`Password must be at least ${PASSWORD_RULES.minLength} characters`);
}
if (PASSWORD_RULES.requireUppercase && !/[A-Z]/.test(password)) {
errors.push('Password must contain an uppercase letter');
}
if (PASSWORD_RULES.requireLowercase && !/[a-z]/.test(password)) {
errors.push('Password must contain a lowercase letter');
}
if (PASSWORD_RULES.requireNumber && !/\d/.test(password)) {
errors.push('Password must contain a number');
}
if (PASSWORD_RULES.requireSpecial && !/[!@#$%^&*]/.test(password)) {
errors.push('Password must contain a special character');
}
return errors;
}
```
## Authorization Patterns
### Role-Based Access Control (RBAC)
```typescript
type Role = 'admin' | 'editor' | 'viewer';
const PERMISSIONS: Record<Role, string[]> = {
admin: ['read', 'write', 'delete', 'manage_users'],
editor: ['read', 'write'],
viewer: ['read'],
};
function hasPermission(user: User, permission: string): boolean {
return user.roles.some(role =>
PERMISSIONS[role]?.includes(permission)
);
}
// Middleware
function requirePermission(permission: string) {
return (req: Request, res: Response, next: NextFunction) => {
if (!hasPermission(req.user, permission)) {
return res.status(403).json({ error: 'Forbidden' });
}
next();
};
}
// Usage
app.delete('/users/:id', requirePermission('manage_users'), deleteUser);
```
### Attribute-Based Access Control (ABAC)
```typescript
interface Policy {
resource: string;
action: string;
condition: (user: User, resource: any) => boolean;
}
const policies: Policy[] = [
{
resource: 'document',
action: 'edit',
condition: (user, doc) =>
doc.ownerId === user.id || user.roles.includes('admin'),
},
{
resource: 'document',
action: 'delete',
condition: (user, doc) =>
doc.ownerId === user.id,
},
];
function canPerform(user: User, action: string, resource: string, resourceData: any): boolean {
const policy = policies.find(p =>
p.resource === resource && p.action === action
);
if (!policy) return false;
return policy.condition(user, resourceData);
}
```
## Security Best Practices
### Token Storage
| Storage | Access Token | Refresh Token |
|---------|--------------|---------------|
| Memory | Yes | No |
| HttpOnly Cookie | Yes (CSRF protection needed) | Yes |
| localStorage | Avoid | Never |
| sessionStorage | Last resort | Never |
### Rate Limiting
```typescript
import rateLimit from 'express-rate-limit';
const authLimiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 5, // 5 attempts
message: { error: 'Too many login attempts, try again later' },
standardHeaders: true,
});
app.post('/auth/login', authLimiter, loginHandler);
```
### Account Lockout
```typescript
const MAX_FAILED_ATTEMPTS = 5;
const LOCKOUT_DURATION = 15 * 60 * 1000; // 15 minutes
async function handleLogin(email: string, password: string) {
const user = await findUserByEmail(email);
if (user.lockedUntil && user.lockedUntil > new Date()) {
throw new AuthError('Account locked. Try again later.');
}
if (!await verifyPassword(password, user.passwordHash)) {
await incrementFailedAttempts(user.id);
if (user.failedAttempts + 1 >= MAX_FAILED_ATTEMPTS) {Related in Backend & APIs
jfrog
IncludedInteract with the JFrog Platform via the JFrog CLI and REST/GraphQL APIs. Use this skill when the user wants to manage Artifactory repositories, upload or download artifacts, manage builds, configure permissions, manage users and groups, work with access tokens, configure JFrog CLI servers, search artifacts, manage properties, set up replication, manage JFrog Projects, run security audits or scans, look up CVE details, query exposures scan results from JFrog Advanced Security, manage release bundles and lifecycle operations, aggregate or export platform data, or perform any JFrog Platform administration task. Also use when the user mentions jf, jfrog, artifactory, xray, distribution, evidence, apptrust, onemodel, graphql, workers, mission control, curation, advanced security, exposures, or any JFrog product name.
cupynumeric-migration-readiness
IncludedPre-migration readiness assessor for porting NumPy to cuPyNumeric. Use BEFORE substantial porting work begins when the user asks whether code will scale on GPU, whether they should migrate to cuPyNumeric, which NumPy patterns transfer cleanly, what must be refactored before porting, or mentions pre-port assessment, scaling analysis, or refactor planning. Inspect the user's source code, look up NumPy usage, cross-reference the cuPyNumeric API support manifest, and distinguish distributed-scaling-friendly patterns from blockers such as unsupported APIs, scalar synchronization, host round-trips, Python/object-heavy control flow, shape/data-dependent branching, and in-place mutation hazards. Produce a verdict of READY, LIGHT REFACTOR, SIGNIFICANT REFACTOR, or NOT RECOMMENDED, with concrete refactor pointers.
alibabacloud-data-agent-skill
IncludedInvoke Alibaba Cloud Apsara Data Agent for Analytics via CLI to perform natural language-driven data analysis on enterprise databases. Data Agent for Analytics is an intelligent data analysis agent developed by Alibaba Cloud Database team for enterprise users. It automatically completes requirement analysis, data understanding, analysis insights, and report generation based on natural language descriptions. This tool supports: discovering data resources (instances/databases/tables) managed in DMS, initiating query or deep analysis sessions, real-time progress tracking, and retrieving analysis conclusions and generated reports. Use this Skill when users need to query databases, analyze data trends, generate data reports, ask questions in natural language, or mention "Data Agent", "data analysis", "database query", "SQL analysis", "data insights".
token-optimizer
IncludedReduce OpenClaw token usage and API costs through smart model routing, heartbeat optimization, budget tracking, and native 2026.2.15 features (session pruning, bootstrap size limits, cache TTL alignment). Use when token costs are high, API rate limits are being hit, or hosting multiple agents at scale. The 4 executable scripts (context_optimizer, model_router, heartbeat_optimizer, token_tracker) are local-only — no network requests, no subprocess calls, no system modifications. Reference files (PROVIDERS.md, config-patches.json) document optional multi-provider strategies that require external API keys and network access if you choose to use them. See SECURITY.md for full breakdown.
resend-cli
IncludedUse this skill when the task is specifically about operating Resend from an AI agent, terminal session, or CI job via the official resend CLI: installing/authenticating the CLI, sending/listing/updating/cancelling emails, batch sends, domains and DNS, webhooks and local listeners, inbound receiving, contacts, topics, segments, broadcasts, templates, API keys, profiles, or debugging Resend CLI/API failures. Trigger on mentions of Resend CLI, `resend`, `resend doctor`, `resend emails send`, `resend domains`, `resend webhooks listen`, `resend emails receiving`, or agent-friendly terminal automation.
alibabacloud-odps-maxframe-coding
IncludedUse this skill for MaxFrame SDK development and documentation navigation on Alibaba Cloud MaxCompute (ODPS). Helps answer MaxFrame API, concept, official example, and supported pandas API questions; create data processing programs; read/write MaxCompute tables; debug jobs (remote or local); and build custom DPE runtime images. Trigger when users mention MaxFrame, MaxCompute with MaxFrame, ODPS table processing, DPE runtime, MaxFrame docs/examples, DataFrame/Tensor operations, or GPU runtime setup. Works for both English and Chinese queries about Alibaba Cloud data processing with MaxFrame.