跳到主要内容

Fiber 与 JWT

Github StackBlitz

本示例演示了如何在 Fiber 应用中使用 JSON Web Tokens (JWT) 进行认证。

先决条件

  • Go 1.16 或更高版本
  • Go Modules

设置

  1. 克隆仓库

    git clone https://github.com/gofiber/recipes.git
    cd recipes/jwt
  2. 安装依赖

    go mod tidy

运行应用

  1. 运行应用

    go run main.go
  2. 服务器将在 http://localhost:3000 上启动。

端点

方法URL描述
POST/login认证用户并返回 JWT
GET/restricted使用 JWT 访问受限路由

示例请求

登录

curl -X POST http://localhost:3000/login -d '{"username": "user", "password": "pass"}' -H "Content-Type: application/json"

访问受限路由

curl -X GET http://localhost:3000/restricted -H "Authorization: Bearer <your_jwt_token>"

Postman 集合

您可以在此处找到 Postman 示例。