authentication-patterns
Patterns for implementing authentication and authorization in backend applications
What this skill does
# Authentication Patterns Skill
Patterns for implementing secure authentication and authorization.
## Authentication Methods
### JWT (JSON Web Tokens)
```typescript
import jwt from 'jsonwebtoken';
const JWT_SECRET = process.env.JWT_SECRET!;
const JWT_EXPIRES_IN = '15m';
const REFRESH_TOKEN_EXPIRES_IN = '7d';
// Generate tokens
function generateTokens(userId: string) {
const accessToken = jwt.sign(
{ userId, type: 'access' },
JWT_SECRET,
{ expiresIn: JWT_EXPIRES_IN }
);
const refreshToken = jwt.sign(
{ userId, type: 'refresh' },
JWT_SECRET,
{ expiresIn: REFRESH_TOKEN_EXPIRES_IN }
);
return { accessToken, refreshToken };
}
// Verify token
function verifyToken(token: string): JwtPayload {
return jwt.verify(token, JWT_SECRET) as JwtPayload;
}
// Refresh token endpoint
app.post('/auth/refresh', async (req, res) => {
const { refreshToken } = req.body;
try {
const payload = verifyToken(refreshToken);
if (payload.type !== 'refresh') {
throw new Error('Invalid token type');
}
// Check if refresh token is still valid in database
const storedToken = await getStoredRefreshToken(refreshToken);
if (!storedToken || storedToken.revoked) {
throw new Error('Token revoked');
}
// Generate new tokens
const tokens = generateTokens(payload.userId);
// Revoke old refresh token
await revokeRefreshToken(refreshToken);
// Store new refresh token
await storeRefreshToken(tokens.refreshToken, payload.userId);
res.json(tokens);
} catch (error) {
res.status(401).json({ error: 'Invalid refresh token' });
}
});
```
### API Keys
```typescript
// Generate API key
function generateApiKey(): string {
return `sk_${crypto.randomBytes(32).toString('hex')}`;
}
// Hash API key for storage
function hashApiKey(key: string): string {
return crypto.createHash('sha256').update(key).digest('hex');
}
// Validate API key
async function validateApiKey(key: string) {
const hash = hashApiKey(key);
const apiKey = await prisma.apiKey.findUnique({
where: { hash },
include: { user: true },
});
if (!apiKey || apiKey.revoked || apiKey.expiresAt < new Date()) {
return null;
}
// Update last used
await prisma.apiKey.update({
where: { id: apiKey.id },
data: { lastUsedAt: new Date() },
});
return apiKey;
}
// API key middleware
async function authenticateApiKey(req: Request, res: Response, next: NextFunction) {
const key = req.headers['x-api-key'] as string;
if (!key) {
return res.status(401).json({ error: 'API key required' });
}
const apiKey = await validateApiKey(key);
if (!apiKey) {
return res.status(401).json({ error: 'Invalid API key' });
}
req.user = apiKey.user;
req.apiKey = apiKey;
next();
}
```
### OAuth2
```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) => {
try {
// Find or create user
let user = await prisma.user.findUnique({
where: { googleId: profile.id },
});
if (!user) {
user = await prisma.user.create({
data: {
googleId: profile.id,
email: profile.emails?.[0].value,
name: profile.displayName,
},
});
}
done(null, user);
} catch (error) {
done(error);
}
}));
// Routes
app.get('/auth/google',
passport.authenticate('google', { scope: ['profile', 'email'] })
);
app.get('/auth/google/callback',
passport.authenticate('google', { session: false }),
(req, res) => {
const tokens = generateTokens(req.user.id);
res.redirect(`/auth/callback?token=${tokens.accessToken}`);
}
);
```
## Authorization Patterns
### Role-Based Access Control (RBAC)
```typescript
// Define roles and permissions
const PERMISSIONS = {
admin: ['read', 'write', 'delete', 'manage-users'],
editor: ['read', 'write'],
viewer: ['read'],
} as const;
type Role = keyof typeof PERMISSIONS;
type Permission = (typeof PERMISSIONS)[Role][number];
// Check permission middleware
function requirePermission(permission: Permission) {
return (req: Request, res: Response, next: NextFunction) => {
const userRole = req.user?.role as Role;
if (!userRole || !PERMISSIONS[userRole]?.includes(permission)) {
return res.status(403).json({ error: 'Insufficient permissions' });
}
next();
};
}
// Usage
app.delete('/users/:id',
authenticate,
requirePermission('delete'),
userController.delete
);
```
### Attribute-Based Access Control (ABAC)
```typescript
// Policy definition
interface Policy {
action: string;
resource: string;
condition: (user: User, resource: any) => boolean;
}
const policies: Policy[] = [
{
action: 'update',
resource: 'post',
condition: (user, post) => post.authorId === user.id || user.role === 'admin',
},
{
action: 'delete',
resource: 'post',
condition: (user, post) => post.authorId === user.id || user.role === 'admin',
},
];
// Check policy
function can(user: User, action: string, resource: string, resourceData?: any): boolean {
const policy = policies.find(p => p.action === action && p.resource === resource);
if (!policy) {
return false;
}
return policy.condition(user, resourceData);
}
// Middleware
function authorize(action: string, resource: string, getResource: (req: Request) => Promise<any>) {
return async (req: Request, res: Response, next: NextFunction) => {
const resourceData = await getResource(req);
if (!can(req.user, action, resource, resourceData)) {
return res.status(403).json({ error: 'Access denied' });
}
req.resource = resourceData;
next();
};
}
// Usage
app.put('/posts/:id',
authenticate,
authorize('update', 'post', (req) => prisma.post.findUnique({ where: { id: req.params.id } })),
postController.update
);
```
### Resource Ownership
```typescript
// Check ownership middleware
async function checkOwnership(req: Request, res: Response, next: NextFunction) {
const resource = await prisma.post.findUnique({
where: { id: req.params.id },
});
if (!resource) {
return res.status(404).json({ error: 'Resource not found' });
}
// Allow if owner or admin
if (resource.userId !== req.user.id && req.user.role !== 'admin') {
return res.status(403).json({ error: 'Access denied' });
}
req.resource = resource;
next();
}
```
## Security Best Practices
### Password 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);
}
```
### Secure Headers
```typescript
import helmet from 'helmet';
app.use(helmet());
app.use(helmet.contentSecurityPolicy({
directives: {
defaultSrc: ["'self'"],
styleSrc: ["'self'", "'unsafe-inline'"],
scriptSrc: ["'self'"],
imgSrc: ["'self'", 'data:', 'https:'],
},
}));
```
### CORS Configuration
```typescript
import cors from 'cors';
app.use(cors({
origin: process.env.ALLOWED_ORIGINS?.split(',') || 'http://localhost:3000',
credentials: true,
methods: ['GET', 'POST', 'PUT', 'DELETE', 'PATCH'],
allowedHeaders: ['Content-Type', 'Authorization', 'X-API-Key'],
}));
```
### Rate Limiting by User
```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' },
keyGenerator: (req) => req.body.email || req.ip,
});
app.post('/auth/login', authLimiter, authController.login);
```
## Session Management
```typescript
// SecureRelated 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.