亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

golang jwt.MapClaims 獲取用戶ID

golang jwt.MapClaims 獲取用戶ID

Go
一只甜甜圈 2022-12-26 10:27:37
設置后,一個簡單的有很多關聯,其中用戶 has_many posts 創建一個帶有用戶 ID 的帖子似乎有必要解析 jwt Claims 以獲取 userID 并將其放置在帖子創建中。那么,如何從 jwt Claims 獲取用戶 ID我嘗試解析令牌但只是出現map[email:[email protected] exp:1.655701949e+09 username:teste]tokenString := c.GetHeader("Authorization")    //claims := jwt.MapClaims{}token, err := jwt.ParseWithClaims(tokenString, claims, func(token *jwt.Token) (interface{}, error) {    return []byte("supersecretkey"), nil})if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {    fmt.Printf("%v", claims )} else {    fmt.Println(err)}
查看完整描述

1 回答

?
不負相思意

TA貢獻1777條經驗 獲得超10個贊

我從一開始就告訴過你,當你想生成 JWT 時,請執行以下操作:


token := jwt.New(jwt.SigningMethodHS256)

// Set claims

// This is the information which frontend can use

// The backend can also decode the token and get admin etc.

claims := token.Claims.(jwt.MapClaims)

claims["username"] = ID

accessTokenExpireTime := time.Now().Add(time.Hour * 48).Unix()

claims["exp"] = accessTokenExpireTime

// Generate encoded token and send it as response.

// The signing string should be secret (a generated UUID works too)

t, err := token.SignedString([]byte("AccessToken"))

然后當你想解碼用戶名時,請執行以下操作:


type MyCustomClaims struct {

        Username string `json:"username"`

        jwt.StandardClaims

    }


    auth := c.Request.Header.Get("Authorization")

    if auth == "" {

        c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"Message": "Authorization Header Not Found"})

        return

    }

    splitToken := strings.Split(auth, "Bearer ")

    auth = splitToken[1]


    token, err := jwt.ParseWithClaims(auth, &MyCustomClaims{}, func(token *jwt.Token) (interface{}, error) {

        return []byte("AccessToken"), nil

    })


    if err != nil {

        c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"Message": "Token is wrong or Expire"})

        return

    }



    if claims, ok := token.Claims.(*MyCustomClaims); ok && token.Valid {

        log.Printf("%v %v", claims.Username, claims.StandardClaims.ExpiresAt)

    }


查看完整回答
反對 回復 2022-12-26
  • 1 回答
  • 0 關注
  • 321 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號