Monday 25 March 2024

JWT -GO add claims and decode claims

 https://github.com/golang-jwt/jwt


https://pkg.go.dev/github.com/golang-jwt/jwt/v5


// add fileName to claim , sign

token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{

"exp": time.Now().Add(10 * time.Hour).Unix(),

"fileName": os.Getenv(<my_file>),

})

// sign token with private key

tokenString, err := token.SignedString(<my_public_key>)

----------------------------------------------------------------------

// middleware validation

tokenString := c.Query("token")

// fileName := c.Query("file")

if tokenString == "" {

c.JSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized: No token found"})

c.Abort()

return

}

// if fileName == "" {

// c.JSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized: No file found"})

// c.Abort()

// return

// }

// Parse validate token

token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {

// Validate the signing method

if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {

return nil, jwt.ErrSignatureInvalid

}

return jwtSignKey, nil

})

if err != nil {

c.JSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized: " + err.Error()})

c.Abort()

return

}

// token valid

if !token.Valid {

c.JSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized: Invalid token"})

c.Abort()

return

}

// token expired

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

// _, ok := token.Claims.(jwt.MapClaims)

if !ok {

c.JSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized: Invalid token claims"})

c.Abort()

return

}

expirationTime := time.Unix(int64(claims["exp"].(float64)), 0)

if time.Now().After(expirationTime) {

c.JSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized: Token expired"})

c.Abort()

return

}

fileName, ok := claims["fileName"].(string)

fileLocation = fileName

if !ok {

c.JSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized: File not found in request"})

c.Abort()

return

}


No comments:

Post a Comment