文档地址 https://github.com/gofiber/jwt
package main
import (
"time"
"github.com/dgrijalva/jwt-go"
"github.com/gofiber/fiber"
"github.com/gofiber/fiber/middleware"
jwtware "github.com/gofiber/jwt"
)
const jwtSecret = "asecret"
//token验证
func authRequired() func(ctx *fiber.Ctx) {
return jwtware.New(jwtware.Config{
SigningKey: []byte(jwtSecret),
ErrorHandler: func(ctx *fiber.Ctx, err error) {
ctx.Status(fiber.StatusUnauthorized).JSON(fiber.Map{
"err": "Unauthorized",
})
},
})
}
func main() {
app := fiber.New()
app.Use(middleware.Logger()) //查看访问的接口
app.Get("/", func(ctx *fiber.Ctx) {
ctx.Send("hello")
})
app.Post("/login", login)
app.Get("/hello", authRequired(), func(ctx *fiber.Ctx) {
ctx.Send("hello")
})
err := app.Listen(3000)
if err != nil {
panic(err)
}
}
//登录
func login(ctx *fiber.Ctx) {
type request struct {
Email string `json:"email"`
Password string `json:"password"`
}
var body request
err := ctx.BodyParser(&body)
if err != nil {
ctx.Status(fiber.StatusBadRequest).JSON(fiber.Map{
"error": "cannot parse json",
})
return
}
if body.Email != "bob@gmail.com" || body.Password != "password123" {
ctx.Status(fiber.StatusUnauthorized).JSON(fiber.Map{
"error": "Bad Credentials",
})
return
}
// Create token
token := jwt.New(jwt.SigningMethodHS256)
// Set claims
claims := token.Claims.(jwt.MapClaims)
claims["name"] = "wangmin"
claims["admin"] = true
claims["exp"] = time.Now().Add(time.Hour * 72).Unix()
// Generate encoded token and send it as response.
t, err := token.SignedString([]byte(jwtSecret))
if err != nil {
ctx.SendStatus(fiber.StatusInternalServerError)
return
}
ctx.Status(fiber.StatusOK).JSON(fiber.Map{
"token": t,
"user": struct {
Id int `json:"id"`
Email string `json:"email"`
}{
Id: 1,
Email: "bob@gmail.com",
},
})
}
fiber框架token校验
最新推荐文章于 2024-05-15 06:10:36 发布