浏览器与自动化
auth-patterns
JWT access/refresh tokens, Passport.js strategies, session management, OAuth. Use when implementing authentication, authorization, or setting up OAuth providers in a NestJS + Next.js app.
sabahattink · 已有 AI 审核记录
安装与使用
运行命令前先阅读来源与依赖说明。复制命令不会自动安装或执行。
npx skills add sabahattink/antigravity-fullstack-hq --skill auth-patterns技能说明
name: auth-patterns description: JWT access/refresh tokens, Passport.js strategies, session management, OAuth. Use when implementing authentication, authorization, or setting up OAuth providers in a NestJS + Next.js app.
Auth Patterns
JWT Access + Refresh Token Flow
Login
→ API issues access_token (15min) + refresh_token (7d)
→ Frontend stores access_token in memory, refresh_token in httpOnly cookie
Request
→ Attach Authorization: Bearer <access_token>
→ If 401 → POST /auth/refresh with httpOnly cookie
→ If refresh valid → new access_token
→ If refresh expired → redirect to login
NestJS Auth Module
// auth/auth.module.ts
@Module({
imports: [
PassportModule,
JwtModule.registerAsync({
inject: [ConfigService],
useFactory: (config: ConfigService) => ({
secret: config.get('JWT_SECRET'),
signOptions: { expiresIn: '15m' },
}),
}),
UsersModule,
],
controllers: [AuthController],
providers: [
AuthService,
JwtStrategy,
LocalStrategy,
JwtRefreshStrategy,
],
exports: [AuthService],
})
export class AuthModule {}
Strategies
// auth/strategies/local.strategy.ts
import { Strategy } from 'passport-local'
import { PassportStrategy } from '@nestjs/passport'
@Injectable()
export class LocalStrategy extends PassportStrategy(Strategy) {
constructor(private auth: AuthService) {
super({ usernameField: 'email' })
}
async validate(email: string, password: string): Promise<AuthUser> {
const user = await this.auth.validateCredentials(email, password)
if (!user) throw new UnauthorizedException('Invalid email or password')
return user
}
}
// auth/strategies/jwt.strategy.ts
import { ExtractJwt, Strategy } from 'passport-jwt'
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy, 'jwt') {
constructor(config: ConfigService) {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
ignoreExpiration: false,
secretOrKey: config.get<string>('JWT_SECRET'),
})
}
async validate(payload: JwtPayload): Promise<AuthUser> {
return { id: payload.sub, email: payload.email, role: payload.role }
}
}
// auth/strategies/jwt-refresh.strategy.ts
@Injectable()
export class JwtRefreshStrategy extends PassportStrategy(Strategy, 'jwt-refresh') {
constructor(config: ConfigService, private auth: AuthService) {
super({
jwtFromRequest: ExtractJwt.fromExtractors([
(req: Request) => req?.cookies?.['refresh_token'],
]),
ignoreExpiration: false,
secretOrKey: config.get<string>('JWT_REFRESH_SECRET'),
passReqToCallback: true,
})
}
async validate(req: Request, payload: JwtPayload): Promise<AuthUser> {
const refreshToken = req.cookies['refresh_token']
return this.auth.validateRefreshToken(payload.sub, refreshToken)
}
}
Auth Service
// auth/auth.service.ts
@Injectable()
export class AuthService {
constructor(
private usersService: UsersService,
private jwtService: JwtService,
private config: ConfigService,
) {}
async validateCredentials(email: string, password: string): Promise<AuthUser | null> {
const user = await this.usersService.findByEmail(email)
if (!user) return null
const valid = await compare(password, user.passwordHash)
return valid ? { id: user.id, email: user.email, role: user.role } : null
}
async login(user: AuthUser): Promise<TokenPair> {
const payload: JwtPayload = { sub: user.id, email: user.email, role: user.role }
const [accessToken, refreshToken] = await Promise.all([
this.jwtService.signAsync(payload, { expiresIn: '15m' }),
this.jwtService.signAsync(payload, {
secret: this.config.get('JWT_REFRESH_SECRET'),
expiresIn: '7d',
}),
])
// Store hashed refresh token
const hash = await bcrypt.hash(refreshToken, 10)
await this.usersService.saveRefreshToken(user.id, hash)
return { accessToken, refreshToken }
}
async validateRefreshToken(userId: string, token: string): Promise<AuthUser> {
const user = await this.usersService.findById(userId)
if (!user?.refreshTokenHash) throw new UnauthorizedException()
const valid = await compare(token, user.refreshTokenHash)
if (!valid) throw new UnauthorizedException()
return { id: user.id, email: user.email, role: user.role }
}
async logout(userId: string): Promise<void> {
await this.usersService.clearRefreshToken(userId)
}
}
Auth Controller
// auth/auth.controller.ts
@Controller('auth')
export class AuthController {
constructor(private auth: AuthService) {}
@Post('login')
@UseGuards(LocalAuthGuard)
@HttpCode(HttpStatus.OK)
async login(
@CurrentUser() user: AuthUser,
@Res({ passthrough: true }) res: Response,
) {
const { accessToken, refreshToken } = await this.auth.login(user)
// Set refresh token as httpOnly cookie
res.cookie('refresh_token', refreshToken, {
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
sameSite: 'strict',
maxAge: 7 * 24 * 60 * 60 * 1000, // 7 days in ms
path: '/api/auth', // restrict cookie scope
})
return { accessToken, expiresIn: 900 }
}
@Post('refresh')
@UseGuards(JwtRefreshGuard)
@HttpCode(HttpStatus.OK)
async refresh(
@CurrentUser() user: AuthUser,
@Res({ passthrough: true }) res: Response,
) {
const { accessToken, refreshToken } = await this.auth.login(user)
res.cookie('refresh_token', refreshToken, {
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
sameSite: 'strict',
maxAge: 7 * 24 * 60 * 60 * 1000,
path: '/api/auth',
})
return { accessToken, expiresIn: 900 }
}
@Post('logout')
@UseGuards(JwtAuthGuard)
@HttpCode(HttpStatus.NO_CONTENT)
a
阅读完整来源 ↗