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
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
}