Comments (6)
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.
@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.
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.
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.
Given that it's json, it makes more sense for me to change my code. Thanks for looking!
from jwt.
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)
- Panic when claim contains an array with null values HOT 4
- Request for ValidationError Support in Version 5 HOT 3
- proposal: add a CHANGELOG.md HOT 5
- Different types for RegisteredClaims before and after JSON marshaling
- ParseWithClaims fails from json.NewDecoder HOT 4
- `GetID` in the `Claims` interface ? HOT 2
- Development Roadmap
- Add a specific return type / type constraint to `Keyfunc` and `SignedString`
- Token.New example is for the wrong func HOT 2
- KeyFunc should be able to return a slice HOT 2
- ParseUnverified godoc update HOT 1
- Verifying multiple audiences HOT 2
- Restore .Valid() Functionality Somehow HOT 9
- Is it possible to parse JWT without verifying signature?
- I've mad a small library to help with JWT
- v5.0.0/request/request.go: with WithLeeway support? HOT 2
- SigningString produces a string without a signature HOT 2
- RSA-PSS (RSASSA-PSS) keys are unusable in Go language
- Let KeyFunc take Context as parameter HOT 3
- Customize the unit of timestamp/exp in payload HOT 1
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
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.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from jwt.