update jwt
This commit is contained in:
@@ -0,0 +1,26 @@
|
||||
/**
|
||||
* 解码 JWT payload(不验证签名,签名由服务端验证)。
|
||||
* 返回 payload 对象,解码失败返回 null。
|
||||
*/
|
||||
export function decodeJwtPayload(token: string): Record<string, unknown> | null {
|
||||
try {
|
||||
const parts = token.split('.')
|
||||
if (parts.length !== 3) return null
|
||||
const base64 = parts[1].replace(/-/g, '+').replace(/_/g, '/')
|
||||
const padded = base64 + '='.repeat((4 - base64.length % 4) % 4)
|
||||
const decoded = atob(padded)
|
||||
return JSON.parse(decoded)
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 从 JWT token 中提取用户角色。
|
||||
* 返回角色字符串(如 'administrator'),提取失败返回 null。
|
||||
*/
|
||||
export function extractRoleFromJwt(token: string): string | null {
|
||||
const payload = decodeJwtPayload(token)
|
||||
if (!payload || typeof payload.role !== 'string') return null
|
||||
return payload.role
|
||||
}
|
||||
Reference in New Issue
Block a user