Giter VIP home page Giter VIP logo

Comments (6)

oxisto avatar oxisto commented on May 18, 2024

Hmm interesting point, I need to check this further. It may have always been broken, i.e. that it just takes the inverted value of req instead of properly checking, if it is an int64. A possible workaround is to use the parser option that enables JSON numbers, that should then properly unmarshal as json.Number.

I was never a big fan of those MapClaims, they are a bit annoying to handle because they fields can be "anything".

from jwt.

oxisto avatar oxisto commented on May 18, 2024

@ggilley Can you share an example? If I parse a regular JWT that contains the payload { "iat": 1000 } it will always create a float64 field. Afaik that is the way the json package works. How did you manage to create an int64 field?

from jwt.

ggilley avatar ggilley commented on May 18, 2024

Hmm... Good idea. It looks like I picked up an example for custom validation that "fixed" expiredAt and not issuedAt. This code has been running for a couple of years, so something in the path changed recently.

func (c CustomClaims) Valid() error {
        err := jwt.MapClaims{"exp": float64(c.ExpiresAt), "iat": c.IssuedAt, "iss": c.Issuer}.Valid()
        if err != nil {
                return err
        }
        if c.UserID == "" {
                return errors.New("missing userid")
        }
        if c.TenantID == "" {
                return errors.New("missing tenantid")
        }
        if c.PID == "" {
                return errors.New("missing pid")
        }
        return nil
}

from jwt.

ggilley avatar ggilley commented on May 18, 2024

Here's the whole example:

package main

import (
    "errors"
    "fmt"
    "time"

    "github.com/golang-jwt/jwt"
)

type CustomClaims struct {
	UserID      string   `json:"userid"`
	TenantID    string	`json:"tenantid"`
	PID         string         `json:"pid"`
	Roles       []string       `json:"roles"`
	Permissions []string       `json:"permissions"`
	Parameters  []string       `json:"parameters"`
	jwt.StandardClaims
}

type CustomClaimsWrapper struct {
	CustomClaims
	Partial bool `json:"-"`
}

var JWTSecret string = ""

func main() {

	claims := CustomClaims{
		"1",
		"1",
		"1",
		[]string{"User"},
		[]string{"rtdb"},
		[]string{},
		jwt.StandardClaims{
			Issuer:    "jwt.test.org",
			ExpiresAt: time.Now().Add(15 * time.Minute).Unix(),
			IssuedAt:  time.Now().Unix(),
			Audience:  "my-audience",
		},
	}
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)

	tokenString, err := token.SignedString([]byte(JWTSecret))
	if err != nil {
  	    fmt.Printf("Error signing token: %v\n", err)
	}


	var parsedClaims CustomClaimsWrapper

	_, error := jwt.ParseWithClaims(tokenString, &parsedClaims, func(token *jwt.Token) (interface{}, error) {
			if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
				return nil, fmt.Errorf("There was an error")
			}

			return []byte(JWTSecret), nil
	})

	if error != nil {
	    fmt.Printf("error: %v\n", error);
	}

}

func (c CustomClaims) Valid() error {
	err := jwt.MapClaims{"exp": float64(c.ExpiresAt), "iat": c.IssuedAt, "iss": c.Issuer}.Valid()
	if err != nil {
		return err
	}
	if c.UserID == "" {
		return errors.New("missing userid")
	}
	if c.TenantID == "" {
		return errors.New("missing tenantid")
	}
	if c.PID == "" {
		return errors.New("missing pid")
	}
	return nil
}

from jwt.

ggilley avatar ggilley commented on May 18, 2024

Given that it's json, it makes more sense for me to change my code. Thanks for looking!

from jwt.

oxisto avatar oxisto commented on May 18, 2024

Given that it's json, it makes more sense for me to change my code. Thanks for looking!

No problem. BTW, you can make your life a lot easier if you replace the line where you reconstruct your custom claims with map claims just to validate them with the following line: err := c.StandardClaims.Valid()

Since you are embedding StandardClaims, this will just forward the Valid() to it and then run your custom code on top of it.

from jwt.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.