Skill站外收录 @skilllib/skill-2014279387821060098
clerk-core-workflow-b
实现用户会话管理与路由保护,支持多会话切换及令牌刷新机制,通过中间件控制 API 和管理页面的访问权限,并可在服务端验证会话有效性,适用于需要精细化权限控制的应用场景。
测试与安全 AI 技能
Skills.MD
# Clerk Core Workflow B: Session & Middleware
## Overview
Manage user sessions, protect routes with middleware, and handle JWT tokens.
## Prerequisites
- Clerk SDK installed and configured
- Authentication flows implemented
- Understanding of Next.js middleware
## Instructions
### Step 1: Advanced Middleware Configuration
```typescript
// middleware.ts
import { clerkMiddleware, createRouteMatcher } from '@clerk/nextjs/server'
import { NextResponse } from 'next/server'
const isPublicRoute = createRouteMatcher([
'/',
'/sign-in(.*)',
'/sign-up(.*)',
'/api/webhooks(.*)',
'/api/public(.*)'
])
const isAdminRoute = createRouteMatcher(['/admin(.*)'])
const isAPIRoute = createRouteMatcher(['/api/(.*)'])
export default clerkMiddleware(async (auth, request) => {
const { userId, orgRole, sessionClaims } = await auth()
// Allow public routes
if (isPublicRoute(request)) {
return NextResponse.next()
}
// Require authentication for all other routes
if (!userId) {
const signInUrl = new URL('/sign-in', request.url)
signInUrl.searchParams.set('redirect_url', request.url)
return NextResponse.redirect(signInUrl)
}
// Admin route protection
if (isAdminRoute(request)) {
if (orgRole !== 'org:admin') {
return NextResponse.redirect(new URL('/unauthorized', request.url))
}
}
// Add custom headers for API routes
if (isAPIRoute(request)) {
const response = NextResponse.next()
response.headers.set('x-user-id', userId)
return response
}
return NextResponse.next()
})
export const config = {
matcher: ['/((?!_next|[^?]*\\.(?:html?|css|js|jpe?g|webp|png|gif|svg|ttf|woff2?|ico)).*)', '/']
}
```
### Step 2: Session Management
```typescript
'use client'
import { useSession, useAuth } from '@clerk/nextjs'
export function SessionManager() {
const { session, isLoaded } = useSession()
const { signOut } = useAuth()
if (!isLoaded) return <div>Loading session...</div>
if (!session) return <div>No active session</div>
const handleSignOutAll = async () => {
// Sign out from all devices
await signOut({ sessionId: 'all' })
}
const handleSignOutCurrent = async () => {
// Sign out from current session only
await signOut()
}
return (
<div>
<h2>Session Info</h2>
<p>Session ID: {session.id}</p>
<p>Created: {new Date(session.createdAt).toLocaleString()}</p>
<p>Last Active: {new Date(session.lastActiveAt).toLocaleString()}</p>
<p>Expires: {new Date(session.expireAt).toLocaleString()}</p>
<div className="space-x-2">
<button onClick={handleSignOutCurrent}>Sign Out</button>
<button onClick={handleSignOutAll}>Sign Out All Devices</button>
</div>
</div>
)
}
```
### Step 3: Token Management
```typescript
'use client'
import { useAuth } from '@clerk/nextjs'
export function useClerkToken() {
const { getToken, isLoaded, isSignedIn } = useAuth()
const fetchWithAuth = async (url: string, options: RequestInit = {}) => {
if (!isLoaded || !isSignedIn) {
throw new Error('Not authenticated')
}
const token = await getToken()
return fetch(url, {
...options,
headers: {
...options.headers,
Authorization: `Bearer ${token}`,
'Content-Type': 'application/json'
}
})
}
const fetchWithCustomTemplate = async (url: string, template: string) => {
const token = await getToken({ template })
return fetch(url, {
headers: {
Authorization: `Bearer ${token}`
}
})
}
return { fetchWithAuth, fetchWithCustomTemplate, getToken }
}
```
### Step 4: Server-Side Session Validation
```typescript
// app/api/protected/route.ts
import { auth } from '@clerk/nextjs/server'
import { headers } from 'next/headers'
export async function GET() {
const { userId, sessionId, sessionClaims } = await auth()
if (!userId) {
return Response.json({ error: 'Unauthorized' }, { status: 401 })
}
// Access session claims
const email = sessionClaims?.email as string
const role = sessionClaims?.metadata?.role as string
// Validate session freshness
const sessionAge = Date.now() - (sessionClaims?.iat ?? 0) * 1000
const maxAge = 60 * 60 * 1000 // 1 hour
if (sessionAge > maxAge) {
return Response.json({ error: 'Session expired' }, { status: 401 })
}
return Response.json({
userId,
sessionId,
email,
role
})
}
```
### Step 5: Multi-Session Support
```typescript
'use client'
import { useSessionList, useSession } from '@clerk/nextjs'
export function SessionList() {
const { sessions, isLoaded, setActive } = useSessionList()
const { session: currentSession } = useSession()
if (!isLoaded) return <div>Loading sessions...</div>
return (
<div>
<h2>Active Sessions</h2>
<ul>
{sessions?.map((session) => (
<li key={session.id}>
<span>{session.id}</span>
<span>{session.id === currentSession?.id ? ' (current)' : ''}</span>
<button onClick={() => setActive({ session: session.id })}>
Switch
</button>
<button onClick={() => session.remove()}>
Revoke
</button>
</li>
))}
</ul>
</div>
)
}
```
## Output
- Protected routes with middleware
- Session management UI
- Token refresh handling
- Multi-session support
## Error Handling
| Error | Cause | Solution |
|-------|-------|----------|
| Session not found | Expired or revoked | Redirect to sign-in |
| Token expired | JWT lifetime exceeded | Call getToken() for fresh token |
| Middleware loop | Incorrect matcher | Check matcher regex excludes static files |
| Headers already sent | Response already started | Check middleware order |
## Examples
### Rate-Limited Middleware
```typescript
import { clerkMiddleware } from '@clerk/nextjs/server'
import { Ratelimit } from '@upstash/ratelimit'
import { Redis } from '@upstash/redis'
const ratelimit = new Ratelimit({
redis: Redis.fromEnv(),
limiter: Ratelimit.slidingWindow(10, '10 s')
})
export default clerkMiddleware(async (auth, request) => {
const { userId } = await auth()
if (userId) {
const { success } = await ratelimit.limit(userId)
if (!success) {
return Response.json({ error: 'Rate limited' }, { status: 429 })
}
}
})
```
## Resources
- [Middleware Guide](https://clerk.com/docs/references/nextjs/clerk-middleware)
- [Session Management](https://clerk.com/docs/authentication/configuration/session-options)
- [JWT Templates](https://clerk.com/docs/backend-requests/making/jwt-templates)
## Next Steps
Proceed to `clerk-common-errors` for troubleshooting common issues.
评论 0
还没有评论,来抢沙发。
相关内容
同类或同场景的收录内容
building-with-kafka-strimzi
在 Kubernetes 上构建基于 Apache Kafka 的事件驱动系统,支持高可靠的消息传递、事务性处理与精确一次语义,结合 Strimzi 运营商实现集群自动化管理,利用 Schema Registry 保障事件模式演进,适用于微服务间解耦通信与实时数据流处理场景。
站外数据与分析
609 0.0
personal-tool-builder
专注于从个人真实痛点出发快速构建实用工具,涵盖命令行程序、本地优先应用和自动化脚本的开发与演进,强调先满足自身需求再逐步扩展,通过持续自用打磨功能,避免过度设计,确保工具简洁有效且长期可维护。
站外商业与营销
196 0.0
threejs-lighting
实现三维场景中的光照与阴影控制,支持多种光源类型及环境光照明,提供从基础布光到高级阴影优化的完整方案,适用于需要真实感渲染或性能平衡的可视化项目。
站外效率工具
442 0.0
aggregation-helper
提供数据聚合场景的自动化辅助能力,涵盖 SQL 查询编写、统计分析建模、可视化方案设计及商业智能配置,支持从需求理解到生产级代码生成的全流程指导。
站外效率工具数据与分析
217 0.0
举报「clerk-core-workflow-b」
举报信息仅审核团队可见,同一资产 24 小时内仅可举报一次