一键导入
authentication-implementation
Guide for implementing secure authentication with JWT and session management. Use when adding authentication to an application.
用 Codex 或 Claude 帮你安装 复制这段 Prompt,粘贴到 Codex、Claude 或其他助手里,让它检查 Skill 页面并帮你完成安装。
菜单
Guide for implementing secure authentication with JWT and session management. Use when adding authentication to an application.
用 Codex 或 Claude 帮你安装 复制这段 Prompt,粘贴到 Codex、Claude 或其他助手里,让它检查 Skill 页面并帮你完成安装。
基于 SOC 职业分类
Checklist for auditing and fixing accessibility issues (WCAG 2.1 AA compliance). Use when reviewing components or pages for accessibility.
Guide for creating RESTful API endpoints with validation and error handling. Use when implementing backend API routes.
Guide for creating responsive layouts with CSS. Use when implementing responsive design or fixing layout issues.
Guide for designing database schemas with Prisma ORM. Use when creating or modifying database models.
Guide for consistent error handling across frontend and backend. Use when implementing error handling logic.
Guide for implementing form handling with React Hook Form and Zod validation. Use when creating forms with validation.
| name | authentication-implementation |
| description | Guide for implementing secure authentication with JWT and session management. Use when adding authentication to an application. |
Follow this process to implement secure authentication:
Use bcrypt for password hashing:
import bcrypt from 'bcrypt';
// Register
const hashedPassword = await bcrypt.hash(password, 10);
await db.user.create({
data: { email, password: hashedPassword },
});
// Login
const user = await db.user.findUnique({ where: { email } });
const isValid = await bcrypt.compare(password, user.password);
import jwt from 'jsonwebtoken';
function generateTokens(userId: string) {
const accessToken = jwt.sign(
{ userId },
process.env.JWT_SECRET!,
{ expiresIn: '15m' }
);
const refreshToken = jwt.sign(
{ userId },
process.env.JWT_REFRESH_SECRET!,
{ expiresIn: '7d' }
);
return { accessToken, refreshToken };
}
import { Request, Response, NextFunction } from 'express';
interface AuthRequest extends Request {
userId?: string;
}
export async function authenticate(
req: AuthRequest,
res: Response,
next: NextFunction
) {
try {
const token = req.headers.authorization?.split(' ')[1];
if (!token) {
return res.status(401).json({ error: 'Authentication required' });
}
const payload = jwt.verify(token, process.env.JWT_SECRET!) as { userId: string };
req.userId = payload.userId;
next();
} catch (error) {
res.status(401).json({ error: 'Invalid or expired token' });
}
}
router.post('/api/auth/login', async (req, res) => {
const { email, password } = req.body;
// 1. Find user
const user = await db.user.findUnique({ where: { email } });
if (!user) {
return res.status(401).json({ error: 'Invalid credentials' });
}
// 2. Verify password
const isValid = await bcrypt.compare(password, user.password);
if (!isValid) {
return res.status(401).json({ error: 'Invalid credentials' });
}
// 3. Generate tokens
const { accessToken, refreshToken } = generateTokens(user.id);
// 4. Set HTTP-only cookie
res.cookie('refreshToken', refreshToken, {
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
sameSite: 'strict',
maxAge: 7 * 24 * 60 * 60 * 1000, // 7 days
});
// 5. Return access token
res.json({ accessToken, user: { id: user.id, email: user.email } });
});
router.post('/api/auth/logout', (req, res) => {
res.clearCookie('refreshToken');
res.json({ message: 'Logged out successfully' });
});
router.post('/api/auth/refresh', async (req, res) => {
const refreshToken = req.cookies.refreshToken;
if (!refreshToken) {
return res.status(401).json({ error: 'Refresh token required' });
}
try {
const payload = jwt.verify(
refreshToken,
process.env.JWT_REFRESH_SECRET!
) as { userId: string };
const { accessToken } = generateTokens(payload.userId);
res.json({ accessToken });
} catch (error) {
res.status(401).json({ error: 'Invalid refresh token' });
}
});
// Auth context
const AuthContext = createContext<AuthContextType | null>(null);
export function AuthProvider({ children }: { children: ReactNode }) {
const [user, setUser] = useState<User | null>(null);
const [token, setToken] = useState<string | null>(null);
const login = async (email: string, password: string) => {
const response = await fetch('/api/auth/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ email, password }),
});
const data = await response.json();
setToken(data.accessToken);
setUser(data.user);
};
return (
<AuthContext.Provider value={{ user, token, login }}>
{children}
</AuthContext.Provider>
);
}