auth-system
Implement secure authentication and authorization systems with JWT, OAuth2, Session-based auth, and RBAC. Use when: (1) implementing user login/signup, (2) setting up JWT tokens, (3) OAuth2 integration (Google, GitHub, etc.), (4) role-based access control (RBAC), (5) password hashing and validation, (6) session management, (7) API authentication middleware, (8) 2FA/MFA setup. Triggers: "authentication", "login", "JWT", "OAuth", "session", "password hash", "RBAC", "permissions", "2FA".
Best use case
auth-system is best used when you need a repeatable AI agent workflow instead of a one-off prompt.
Implement secure authentication and authorization systems with JWT, OAuth2, Session-based auth, and RBAC. Use when: (1) implementing user login/signup, (2) setting up JWT tokens, (3) OAuth2 integration (Google, GitHub, etc.), (4) role-based access control (RBAC), (5) password hashing and validation, (6) session management, (7) API authentication middleware, (8) 2FA/MFA setup. Triggers: "authentication", "login", "JWT", "OAuth", "session", "password hash", "RBAC", "permissions", "2FA".
Teams using auth-system should expect a more consistent output, faster repeated execution, less prompt rewriting.
When to use this skill
- You want a reusable workflow that can be run more than once with consistent structure.
When not to use this skill
- You only need a quick one-off answer and do not need a reusable workflow.
- You cannot install or maintain the underlying files, dependencies, or repository context.
Installation
Claude Code / Cursor / Codex
Manual Installation
- Download SKILL.md from GitHub
- Place it in
.claude/skills/auth-system/SKILL.mdinside your project - Restart your AI agent — it will auto-discover the skill
How auth-system Compares
| Feature / Agent | auth-system | Standard Approach |
|---|---|---|
| Platform Support | Not specified | Limited / Varies |
| Context Awareness | High | Baseline |
| Installation Complexity | Unknown | N/A |
Frequently Asked Questions
What does this skill do?
Implement secure authentication and authorization systems with JWT, OAuth2, Session-based auth, and RBAC. Use when: (1) implementing user login/signup, (2) setting up JWT tokens, (3) OAuth2 integration (Google, GitHub, etc.), (4) role-based access control (RBAC), (5) password hashing and validation, (6) session management, (7) API authentication middleware, (8) 2FA/MFA setup. Triggers: "authentication", "login", "JWT", "OAuth", "session", "password hash", "RBAC", "permissions", "2FA".
Where can I find the source code?
You can find the source code on GitHub using the link provided at the top of the page.
SKILL.md Source
# Authentication System
Production-grade authentication and authorization implementation.
## Authentication Strategies
### 1. JWT (Stateless)
```javascript
const jwt = require('jsonwebtoken');
const bcrypt = require('bcrypt');
// Signup
async function signup(email, password) {
const hashedPassword = await bcrypt.hash(password, 12);
const user = await User.create({ email, password: hashedPassword });
return generateTokens(user);
}
// Login
async function login(email, password) {
const user = await User.findByEmail(email);
if (!user || !await bcrypt.compare(password, user.password)) {
throw new Error('Invalid credentials');
}
return generateTokens(user);
}
// Token generation
function generateTokens(user) {
const accessToken = jwt.sign(
{ userId: user.id, role: user.role },
process.env.JWT_SECRET,
{ expiresIn: '15m' }
);
const refreshToken = jwt.sign(
{ userId: user.id, tokenVersion: user.tokenVersion },
process.env.REFRESH_SECRET,
{ expiresIn: '7d' }
);
return { accessToken, refreshToken };
}
// Middleware
function authMiddleware(req, res, next) {
const token = req.headers.authorization?.split(' ')[1];
if (!token) return res.status(401).json({ error: 'Unauthorized' });
try {
req.user = jwt.verify(token, process.env.JWT_SECRET);
next();
} catch (err) {
res.status(401).json({ error: 'Invalid token' });
}
}
```
### 2. Session-Based (Stateful)
```javascript
const session = require('express-session');
const RedisStore = require('connect-redis')(session);
app.use(session({
store: new RedisStore({ client: redisClient }),
secret: process.env.SESSION_SECRET,
resave: false,
saveUninitialized: false,
cookie: {
secure: true, // HTTPS only
httpOnly: true, // No JS access
maxAge: 24 * 60 * 60 * 1000, // 24 hours
sameSite: 'strict'
}
}));
// Login
app.post('/login', async (req, res) => {
const user = await validateCredentials(req.body);
req.session.userId = user.id;
req.session.role = user.role;
res.json({ success: true });
});
// Logout
app.post('/logout', (req, res) => {
req.session.destroy();
res.json({ success: true });
});
```
### 3. OAuth2 (Social Login)
```javascript
const passport = require('passport');
const GoogleStrategy = require('passport-google-oauth20').Strategy;
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) => {
let user = await User.findByGoogleId(profile.id);
if (!user) {
user = await User.createFromGoogle(profile);
}
done(null, user);
}));
// Routes
app.get('/auth/google', passport.authenticate('google', { scope: ['email', 'profile'] }));
app.get('/auth/google/callback',
passport.authenticate('google', { session: false }),
(req, res) => {
const tokens = generateTokens(req.user);
res.redirect(`/callback?token=${tokens.accessToken}`);
}
);
```
## Authorization (RBAC)
```javascript
// Role definitions
const ROLES = {
ADMIN: 'admin',
USER: 'user',
MODERATOR: 'moderator'
};
// Permission definitions
const PERMISSIONS = {
[ROLES.ADMIN]: ['read', 'write', 'delete', 'manage_users'],
[ROLES.MODERATOR]: ['read', 'write', 'delete'],
[ROLES.USER]: ['read', 'write']
};
// Middleware
function requirePermission(permission) {
return (req, res, next) => {
const userPermissions = PERMISSIONS[req.user.role] || [];
if (!userPermissions.includes(permission)) {
return res.status(403).json({ error: 'Forbidden' });
}
next();
};
}
// Usage
app.delete('/posts/:id',
authMiddleware,
requirePermission('delete'),
deletePost
);
```
## Password Security
```javascript
const bcrypt = require('bcrypt');
const crypto = require('crypto');
// Hash password
async function hashPassword(password) {
const salt = await bcrypt.genSalt(12);
return bcrypt.hash(password, salt);
}
// Validate password
async function validatePassword(password, hash) {
return bcrypt.compare(password, hash);
}
// Generate secure token (for password reset)
function generateResetToken() {
return crypto.randomBytes(32).toString('hex');
}
```
## 2FA (TOTP)
```javascript
const speakeasy = require('speakeasy');
const QRCode = require('qrcode');
// Setup 2FA
async function setup2FA(userId) {
const secret = speakeasy.generateSecret({
name: 'MyApp',
length: 20
});
await User.update(userId, {
twoFactorSecret: secret.base32,
twoFactorEnabled: false
});
const qrUrl = await QRCode.toDataURL(secret.otpauth_url);
return { secret: secret.base32, qrUrl };
}
// Verify 2FA
function verify2FA(secret, token) {
return speakeasy.totp.verify({
secret,
encoding: 'base32',
token,
window: 1 // Allow 1 step before/after
});
}
```
## Security Best Practices
```
✅ Always use HTTPS in production
✅ Store passwords with bcrypt (cost factor >= 12)
✅ Use short-lived access tokens (15-30 min)
✅ Implement refresh token rotation
✅ Set secure cookie flags (httpOnly, secure, sameSite)
✅ Rate limit login attempts
✅ Log failed authentication attempts
✅ Implement account lockout after N failures
✅ Never store tokens in localStorage (XSS risk)
✅ Use CSRF protection for session-based auth
```
## Scripts
- `scripts/generate_jwt_secret.js` - Generate secure JWT secret
- `scripts/hash_password.js` - CLI tool to hash passwords
- `scripts/verify_token.js` - Decode and verify JWT tokens
## References
- `references/oauth_providers.md` - OAuth2 provider setup guides
- `references/security_checklist.md` - Auth security audit checklist
- `references/token_refresh_flow.md` - Refresh token rotation patternsRelated Skills
Systematic Debugging
Use when encountering any bug, test failure, or unexpected behavior, before proposing fixes
sandler-system
Apply Sandler Selling System principles for consultative sales with pain discovery, budget qualification, and mutual decision frameworks
google-auth
Google OAuth setup, refresh tokens
doc-coauthoring
Guide users through a structured workflow for co-authoring documentation. Use when user wants to write documentation, proposals, technical specs, decision docs, or similar structured content. This workflow helps users efficiently transfer context, refine content through iteration, and verify the doc works for readers. Trigger when user mentions writing docs, creating proposals, drafting specs, or similar documentation tasks.
auth-manager
网页登录态管理。使用 OpenClaw 内置 browser (profile=openclaw) 统一管理各平台登录状态,定期检查可用性。
wemp-operator
> 微信公众号全功能运营——草稿/发布/评论/用户/素材/群发/统计/菜单/二维码 API 封装
zsxq-smart-publish
Publish and manage content on 知识星球 (zsxq.com). Supports talk posts, Q&A, long articles, file sharing, digest/bookmark, homework tasks, and tag management. Use when publishing content to 知识星球, creating/editing posts, uploading files/images/audio, managing digests, batch publishing, or formatting content for 知识星球.
zoom-automation
Automate Zoom meeting creation, management, recordings, webinars, and participant tracking via Rube MCP (Composio). Always search tools first for current schemas.
zoho-crm-automation
Automate Zoho CRM tasks via Rube MCP (Composio): create/update records, search contacts, manage leads, and convert leads. Always search tools first for current schemas.
ziliu-publisher
字流(Ziliu) - AI驱动的多平台内容分发工具。用于一次创作、智能适配排版、一键分发到16+平台(公众号/知乎/小红书/B站/抖音/微博/X等)。当用户需要多平台发布、内容排版、格式适配时使用。触发词:字流、ziliu、多平台发布、一键分发、内容分发、排版发布。
zhihu-post-skill
> 知乎文章发布——知乎平台内容创作与发布自动化
zendesk-automation
Automate Zendesk tasks via Rube MCP (Composio): tickets, users, organizations, replies. Always search tools first for current schemas.