"use client"; import { useState } from "react"; import { KeySquare, Copy, Trash2, ShieldCheck, AlertCircle } from "lucide-react"; import { Button } from "@/components/ui/button"; import { Textarea } from "@/components/ui/textarea"; import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"; import { toast } from "sonner"; export default function JwtDecoderPage() { const [token, setToken] = useState(""); const [decoded, setDecoded] = useState<{ header: any; payload: any; error: string | null; }>({ header: null, payload: null, error: null, }); const base64UrlDecode = (str: string) => { try { // Replace non-url compatible chars with base64 standard chars str = str.replace(/-/g, '+').replace(/_/g, '/'); // Pad with = while (str.length % 4) { str += '='; } return decodeURIComponent(atob(str).split('').map(function(c) { return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2); }).join('')); } catch { throw new Error("Invalid base64 encoding"); } }; const decodeJwt = (input: string) => { setToken(input); if (!input.trim()) { setDecoded({ header: null, payload: null, error: null }); return; } const parts = input.split('.'); if (parts.length !== 3) { setDecoded({ header: null, payload: null, error: "无效的 JWT 格式(必须包含三个由点分隔的部分)" }); return; } try { const header = JSON.parse(base64UrlDecode(parts[0])); const payload = JSON.parse(base64UrlDecode(parts[1])); setDecoded({ header, payload, error: null }); } catch { setDecoded({ header: null, payload: null, error: "解码失败:请检查输入是否为有效的 JWT" }); } }; const copyToClipboard = async (data: any) => { if (!data) return; try { await navigator.clipboard.writeText(JSON.stringify(data, null, 2)); toast.success("已复制 JSON 内容"); } catch { toast.error("复制失败"); } }; const clearAll = () => { setToken(""); setDecoded({ header: null, payload: null, error: null }); }; return (
解析 JSON Web Token 的 Header 和 Payload 内容
{decoded.header ? JSON.stringify(decoded.header, null, 2) : "// 等待输入..."}
{decoded.payload ? JSON.stringify(decoded.payload, null, 2) : "// 等待输入..."}
安全提示
解码过程完全在您的浏览器本地进行,Token 不会被发送到任何服务器。请放心使用。