英文:
How to access below json values in go fiber?
问题
这是我写的代码。当我使用token.Claims
方法时,它返回以下结果。我需要访问电子邮件值,以便检查用户是谁。当我使用token.Claims.Email
时,它会抛出一个错误。
func User(c *fiber.Ctx) error {
cookie := c.Cookies("jwt")
claims := jwt.MapClaims{}
token, _ := jwt.ParseWithClaims(cookie, claims, func(token *jwt.Token) (interface{}, error) {
return []byte(SecretKey), nil
})
return c.JSON(token.Claims)
}
英文:
This is the code I wrote. When I used token.Claims
method it returns below result. And I need to access email value also for check whether who is the user. When I used token.Claims.Email
it throws an error.
func User(c *fiber.Ctx) error {
cookie := c.Cookies("jwt")
claims := jwt.MapClaims{}
token, _ := jwt.ParseWithClaims(cookie, claims, func(token *jwt.Token) (interface{}, error) {
return []byte(SecretKey), nil
})
return c.JSON(token.Claims)
}
This is the postman response. How to access below email address
答案1
得分: 2
根据你的代码,我猜测你正在使用golang-jwt包。
在调用jwt.ParseWithClaims
之后,你应该能够通过已创建的名为claims
的jwt.MapClaims
对象来访问你的声明。
以下是一个不使用Fiber,只使用golang-jwt的示例,但逻辑保持不变:
package main
import (
"fmt"
"github.com/golang-jwt/jwt/v4"
)
// 在 https://jwt.io/ 上生成的示例令牌
const tokenString = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6InRlc3RAbWFpbC5jaCJ9.Iv6oZWIX7Rrtag4d6h3-eJ3xdXLwoZ9PbotcvbjOvhI"
// 仅作为示例,请确保选择更强的密钥
const key = "1234567890"
func main() {
claims := jwt.MapClaims{}
token, err := jwt.ParseWithClaims(tokenString, claims, keyFunc)
if err != nil {
panic(err)
}
fmt.Println(token.Valid)
email, ok := claims["email"].(string)
if !ok {
panic("Couldn't parse email as string")
}
fmt.Println(email)
}
func keyFunc(*jwt.Token) (interface{}, error) {
return []byte(key), nil
}
英文:
Just by checking out your code I'm guessing that you are using this golang-jwt package.
After calling jwt.ParseWithClaims
you should be able to access your claims over the already created jwt.MapClaims
object named claims
in your code.
Example without Fiber, only with golang-jwt, but logic stays the same:
package main
import (
"fmt"
"github.com/golang-jwt/jwt/v4"
)
// Created on https://jwt.io/
const tokenString = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6InRlc3RAbWFpbC5jaCJ9.Iv6oZWIX7Rrtag4d6h3-eJ3xdXLwoZ9PbotcvbjOvhI"
// Just as an example, make sure to pick a stronger key
const key = "1234567890"
func main() {
claims := jwt.MapClaims{}
token, err := jwt.ParseWithClaims(tokenString, claims, keyFunc)
if err != nil {
panic(err)
}
fmt.Println(token.Valid)
email, ok := claims["email"].(string)
if !ok {
panic("Couldn't parse email as string")
}
fmt.Println(email)
}
func keyFunc(*jwt.Token) (interface{}, error) {
return []byte(key), nil
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论