我用 Golang 的Gin 框架和JWT 中間件為其構建了一個后端。這是自述文件中的官方示例,我使用了它:主程序package mainimport (? ? "log"? ? "net/http"? ? "os"? ? "time"? ? "github.com/appleboy/gin-jwt/v2"? ? "github.com/gin-gonic/gin")type login struct {? ? Username string `form:"username" json:"username" binding:"required"`? ? Password string `form:"password" json:"password" binding:"required"`}var identityKey = "id"func helloHandler(c *gin.Context) {? ? claims := jwt.ExtractClaims(c)? ? user, _ := c.Get(identityKey)? ? c.JSON(200, gin.H{? ? ? ? "userID":? ?claims[identityKey],? ? ? ? "userName": user.(*User).UserName,? ? ? ? "text":? ? ?"Hello World.",? ? })}// User demotype User struct {? ? UserName? string? ? FirstName string? ? LastName? string}func main() {? ? port := os.Getenv("PORT")? ? r := gin.New()? ? r.Use(gin.Logger())? ? r.Use(gin.Recovery())? ? if port == "" {? ? ? ? port = "8000"? ? }? ? // the jwt middleware? ? authMiddleware, err := jwt.New(&jwt.GinJWTMiddleware{? ? ? ? Realm:? ? ? ?"test zone",? ? ? ? Key:? ? ? ? ?[]byte("secret key"),? ? ? ? Timeout:? ? ?time.Hour,? ? ? ? MaxRefresh:? time.Hour,? ? ? ? IdentityKey: identityKey,? ? ? ? PayloadFunc: func(data interface{}) jwt.MapClaims {? ? ? ? ? ? if v, ok := data.(*User); ok {? ? ? ? ? ? ? ? return jwt.MapClaims{? ? ? ? ? ? ? ? ? ? identityKey: v.UserName,? ? ? ? ? ? ? ? }? ? ? ? ? ? }? ? ? ? ? ? return jwt.MapClaims{}? ? ? ? },? ? ? ? IdentityHandler: func(c *gin.Context) interface{} {? ? ? ? ? ? claims := jwt.ExtractClaims(c)? ? ? ? ? ? return &User{? ? ? ? ? ? ? ? UserName: claims[identityKey].(string),? ? ? ? ? ? }? ? ? ? },
- 1 回答
- 0 關注
- 140 瀏覽
添加回答
舉報
0/150
提交
取消