golang-jwt / jwt Goto Github PK
View Code? Open in Web Editor NEWCommunity maintained clone of https://github.com/dgrijalva/jwt-go
Home Page: https://golang-jwt.github.io/jwt/
License: MIT License
Community maintained clone of https://github.com/dgrijalva/jwt-go
Home Page: https://golang-jwt.github.io/jwt/
License: MIT License
How do i skip token verification? nil as keyfunc returns error
dgrijalva/jwt-go was one of the main recommended packages on the site until it was removed due to being EOL. Once we feel comfortable enough with the state of this fork we should reach out the folks at Auth0 to add it on the libraries section of https://jwt.io/
https://github.com/golang-jwt/jwt/blob/master/MIGRATION_GUIDE.md
Is currently talking about migrating from v2 ro v3, this doesnt make much sense in this reop's context.
We could update this doc to discuss how to migrate from dgrijalva/jwt-go/
to golang-jwt/jwt
as a drop-in replacment, and then we can add sections in the future for new versions published from here
Migrated from dgrijalva/jwt-go#249:
dgrijalva commented on Mar 8, 2018
How far down the rabbit hole should we go with this?
See the issue thread for more details
Migrated from dgrijalva/jwt-go#318:
greenpau commented on Mar 20, 2019
There are no instructions how to build jwt tool. Perhaps, it is worth adding something like this.
cd cmd/jwt
go build -o $GOPATH/bin/jwt
See dgrijalva/jwt-go#462 for a lengthier discussion and background.
For brevity, there is/was an attempt to migrate to the gors organization, issues here, but unfortunately there was no response on GitHub issue or Slack #gofrs channel.
Hopefully other can chip in, but afaics the goal of this org/repo:
The intention is to support the package in its current form without any major re-write or refactor.
I still hope one day the Go standard library or /x will add JWT support and backing from the Go team.
If there is agreement we can setup independent GitHub issues to tackle the above and address these in particular.
What are your thoughts on adding GitHub Discussions?
I noticed with the upstream repository dgrijalva/jwt-go a good chunk of the Issues were questions.
Alternatively (or in parallel), we can setup a GitHub Pages with a basic FAQ to address a lot of the recurring questions.
Migrated from dgrijalva/jwt-go#227
asambeka commented on Aug 28, 2017
I am looking to compress the JWT generated, I have custom claims and that bloats the JWT.
How compression can be achieved using jwt-go? Looking at https://www.iana.org/assignments/jose/jose.xhtml "zip" header is reserved for compression algorithm, any ideas on how to implement it?
The original repo has a pretty complete v4 release that I'm using (docs).
As I recall, I needed v4 because of this change:
Added new type,
ClaimStrings
, which will correctly handle properties such asaud
that can be either an array of strings or a single string.ClaimStrings
is an alias to[]string
, but with custom decoding behavior. This means all the built inaud
validation behavior now expects[]string
instead ofstring
. This was a common request.
It would be nice to see that picked up and moved forward, as well.
Migrated from dgrijalva/jwt-go#360:
nathan-fiscaletti commented on Sep 28, 2019
The VerifyExpiresAt function for Claims has incorrect or unclear documentation. It states that it will compare the exp claim to cmp, which is indicative of a == comparison, when in reality it does a cmp <= exp comparison.
I am trying to follow the steps in the migration guide however, I am getting the following error with go mod tidy
:
go mod tidy
go: finding module for package github.com/golang-jwt/jwt/test
go: finding module for package github.com/golang-jwt/jwt/request
go: finding module for package github.com/golang-jwt/jwt
go: found github.com/golang-jwt/jwt in github.com/golang-jwt/jwt v3.2.1+incompatible
go: found github.com/golang-jwt/jwt/request in github.com/golang-jwt/jwt v3.2.1+incompatible
go: found github.com/golang-jwt/jwt/test in github.com/golang-jwt/jwt v3.2.1+incompatible
go: github.com/golang-jwt/[email protected]+incompatible used for two different module paths (github.com/dgrijalva/jwt-go and github.com/golang-jwt/jwt)
Here is the PR: upbound/universal-crossplane#167
Any ideas how to fix that?
Migrated from dgrijalva/jwt-go#410:
trygvis commented on Jun 17, 2020
I'm building a CLI to create tokens, and it would be nice if there was a way to find all registered signing methods.
Something like
func GetSigningMethods() ([]SigningMethod)
Migrated from dgrijalva/jwt-go#325:
itstehkman commented on May 4, 2019
This would be an awesome feature. I took a very quick look and it seems like this project does not support it, but maybe I am wrong.
See https://tools.ietf.org/html/rfc7515#section-4.1.6 for more details on this field - it is essentially providing the certificate and its chain in some JWT headers so that both the signature and the cert can be verified.
FWIW, I am trying to add support to the main ruby JWT library, I can post back here with what the PR looks like there. jwt/ruby-jwt#59 (jwt/ruby-jwt#59)
Migrated from dgrijalva/jwt-go#441:
Comments
@gardc
gardc commented on Nov 21, 2020 โขReferring to this example (https://godoc.org/github.com/dgrijalva/jwt-go#example-Parse--Hmac) pointed to by the readme, feeding it an invalid JWT will create a memory panic.
Go playground example. (https://play.golang.org/p/wyOgm21FYE8)
Checking for err and token.Valid before assuming it's all good in the hood fixes the issue, Go playground example. (https://play.golang.org/p/0sX-54gXfE2)
We need to create a process for individuals to be able to disclose security vulnerabilities responsibly.
I suggest:
Since this repo and organization are getting some traction it would be nice to have a little logo for the GitHub organization. Ideally something licensed as CC-0. Do we have any talented artists among our ranks?
Migrated from dgrijalva/jwt-go#375:
Filet-de-S commented on Jan 18, 2020 โข
It's inconvenient to check it with strcmp instead of switch err.(type)
*jwt.ValidationError is the same for "invalid signature" as for any other like from custom Valid() method. It would be great if we could set it manually. Thanks.
Unfortunately the Go module proxy (i.e., mirror) cached 2 versions:
https://pkg.go.dev/github.com/golang-jwt/jwt?tab=versions
When a user does a go get github.com/golang-jwt/jwt
it will download the following version:
github.com/golang-jwt/jwt v3.2.0+incompatible // indirect
Whereas it should import the correct one (based on latest commit on main
)
github.com/golang-jwt/jwt v0.0.0-20210529012641-6a07921e6808 // indirect
If we cannot get those 2 versions removed from the proxy, we'll have to go with plan B... add a /v3 and tag a v3.2.1
We have to define how to deal with the original project's PRs
We can either:
Migrated from dgrijalva/jwt-go#459
Yiming1997 commented on Mar 24
If a token string is expired๏ผHow to refresh it๏ผ
Migrated from dgrijalva/jwt-go#261
v3n commented on May 2, 2018
I don't think this behavior is documented anywhere (unless I missed it!) and hidden in private helpers in the package so took me a bit to find.
Would appreciate this being documented somewhere as its instinctual to use exp: 0 for an easy test case for service properly handling expiration.
Cheers!
Migrated from dgrijalva/jwt-go#458
smcallis commented on Mar 17
jwt-go/parser.go
Line 131 in dc14462
err = dec.Decode(&claims)Since this function takes claims as Claims, if you pass anything other than MapClaims{}, you'll get an unmarshalling error:
Error verifying token: json: cannot unmarshal object into Go value of type jwt.Claims
EdDSA, which is based on ed25519 has gained some traction, and is also supported by some other JWT libraries. I will prepare an initial branch supporting this over the next week or so.
Go 1.17 also features a significantly faster implementation then before, according to the Go 1.17 beta docs.
github.com/golang-jwt/jwt
../pkg/mod/github.com/golang-jwt/[email protected]+incompatible/ecdsa.go:135:4: r.FillBytes undefined (type *big.Int has no field or method FillBytes)
../pkg/mod/github.com/golang-jwt/[email protected]+incompatible/ecdsa.go:136:4: s.FillBytes undefined (type *big.Int has no field or method FillBytes)
Got public key from my keycloak test server and passing it , base64 decoded, as return value in keyfinc.
We should include a contribution guide to solidify and broadcast what is required of any contribution to this project
Does anybody have a good example we can adapt? Or know of some "sensible defaults" used out in the OSS community
StandardClaims has issuedAt as an int64. That means when it gets marshaled to json, it's an int64.
MapClaims VerifyIssuedAt checks for float64 and json.Number, but not int64.
Therefore, verifyIssuedAt fails.
Seems like a recent regression?
github.com/golang-jwt/jwt v3.2.2+incompatible
I tried to migrate from github.com/dgrijalva/jwt-go
to github.com/golang-jwt/jwt
Everything works fine when I use new tokens. But if I want to auth with old generated tokens I get:
invalid token: json: cannot unmarshal number 1615466156.259695 into Go struct field TokenClaims.iat of type int64
How am I suppose to handle that whithout generating all tokens again?
More detailed explanation here: dgrijalva/jwt-go#428
How should we approach a fix?
There is a v4.0.0-preview1
version in dgrijalva/jwt-go that apparently fixes this, and a bunch of PRs.
There was a fix in this fork, https://github.com/form3tech-oss/jwt-go by @Waterdrips and co. as well.
Closely related but now exactly the same as #7. We should triage and migrate the issues from the original repo to this one
We could either:
I opened avelino/awesome-go#3695 to add this package to the list. @mfridman I requested you org access to coveralls, since it's one of the requirements (and it doesn't hurt to have a code coverage badge I guess)
If there are other lists or sites in which we should make a contribution adding the package (like #65) it'd be worth to mention them here
Migrated from dgrijalva/jwt-go#346:
maxshifrin commented on Jul 30, 2019
It would be great if this library could also support payload encryption (https://tools.ietf.org/html/rfc7516)
It would greatly help in case sensitive information needs to be stored inside the JWT token, and offload the need to encrypt it in every application separately
Migrated from dgrijalva/jwt-go#447
stonedu1011 commented on Jan 20
I understand it's at very early stage, so just want to provide some feedback after my attempt to use it.
We uses similar API designed inspired by (this article)[https://dave.cheney.net/2014/10/17/functional-options-for-friendly-apis] in our team. This approach only works if the functional options takes exported type with exported fields. Otherwise, the constructor is completely not configurable.
Here is the patterns we ends up using, in case we want to keep the Type's field hidden:
type Options func(*Opt)
type Opt struct {
ConfigurableField1 type
ConfigurableField2 type
}
type SomeType struct {
field1 type
field2 type
}
func New(opts ...Options) *SomeType {
opt := Opt{
// defaults
}
for _, optFunc := range opts {
optFunc(&opt)
}
return &SomeType {
field1: opt.ConfigurableField1,
field2: opt.ConfigurableField2,
}
}
This is a great library and I hope the V4 reaches a stable state soon.
Migrated from dgrijalva/jwt-go#408:
shobhitsrivastava commented on Jun 11, 2020 โข
I'm using a 256-bit private PEM to build a JWT with signing method RSA 256, similar to the example code:
signBytes, _ := ioutil.ReadFile(privKeyPath)
signKey, err := jwt.ParseRSAPrivateKeyFromPEM(signBytes)
token := jwt.NewWithClaims(jwt.SigningMethodRS256, middleware.CognitoAccessTokenClaim{
CustomArray: []string{"testString"},
StandardClaims: jwt.StandardClaims{
ExpiresAt: 1500,
},
})
jwtString, err := token.SignedString(signKey)
When I try to sign the token, I'm getting the error crypto/rsa: message too long for RSA public key size. Does anyone know what could be causing this?
Migrated from dgrijalva/jwt-go#361:
alanywlee commented on Oct 8, 2019
I am trying to parse a RS256 encoded token (tokenString) from java, it could be successfully decoded by public key in java using the following java code
Jwts.parser().setSigningKey(publicKey).parseClaimsJws(jwt);
However, It could be verified by jwt.SigningMethodRS256.Verify() just as described in https://stackoverflow.com/questions/51834234/i-have-a-public-key-and-a-jwt-how-do-i-check-if-its-valid-in-go
But not able to be jwt.Parse, I tried to write more debug print messages inside the parse function, and verified not even run into it.
tokenString := "eyJhbGciOiJSUzI1NiIsInppcCI6IkRFRiJ9.eNqqVkqtKFCyMjQ1s7Q0sbA0MtFRyk3NTUot8kxRslIKLbZQggn4JeamAoUcfRz99HxcXRWeze172tr4bFq7Ui0AAAD__w.jBXD4LT4aq4oXTgDoPkiV6n4QdSZPZI1Z4J8MWQC42aHK0oXwcovEU06dVbtB81TF-2byuu0-qi8J0GUttODT67k6gCl6DV_iuCOV7gczwTcvKslotUvXzoJ2wa0QuujnjxLEE50r0p6k0tsv_9OIFSUZzDksJFYNPlJH2eFG55DROx4TsOz98az37SujZi9GGbTc9SLgzFHPrHMrovRZ5qLC_w4JrdtsLzBBI11OQJgRYwV8fQf4O8IsMkHtetjkN7dKgUkJtRarNWOk76rpTPppLypiLU4_J0-wrElLMh1TzUVZW6Fz2cDHDDBACJgMmKQ2pOFEDK_vYZN74dLCF5GiTZV6DbXhNxO7lqT7JUN4a3p2z96G7WNRjblf2qZeuYdQvkIsiK-rCbSIE836XeY5gaBgkOzuEvzl_tMrpRmb5Oox1ibOfVT2KBh9Lvqsb1XbQjCio2CLE2ViCLqoe0AaRqlUyrk3n8BIG-r0IW4dcw96CEryEMIjsjVp9mtPXamJzf391kt8Rf3iRBqwv3zP7Plg1ResXbmsFUgOflAUPcYmfLug4W3W52ntcUlTHAKXrNfaJL9QQiYAaDukG-ZHDytsOWTuuXw7lVxjt-XYi1VbRAIjh1aIYSELEmEpE4Ny74htQtywYXMQNfJpB0nNn8IiWakgcYYMJ0TmKM"
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
fmt.Println("token parse start...")
...
}
// ... error handling
if err != nil {
log.Fatal(err)
}
It got error message as following
2019/10/08 17:29:38 invalid character 'x' looking for beginning of value
exit status 1I am curious if I can verify token signature, how come not able to parse its header and claims body. Or I missed anything before doing jwt.Parse()
Any comment is highly appreciated....
When the library was initially started, RFC7519 did not exist - only its drafts. This has lead to some shortcomings over the years where the implementation, especially of the claims, diverged from the now published RFC.
For example, the draft at the time of the writing of the claims struct actually stated that iat
, exp
and so on must be an IntDate
, which did not include the possibility of non-integer date representations. It got then later changed to a NumericDate
format in draft version 26, which - as @dunglas correctly pointed out - included also float representations (also strings).
The aim would be to be as backwards compatible as possible, e.g. with the introduction of a new struct as suggested by @mfridman, which I will name for the lack of a better name jwt.RFC7159Claims
for now.
This also was the original problem behind the audience mixup in #6
Points to consider (and possibly replaced with a new struct or function):
ExpiresAt
, IssuedAt
, NotBefore
in jwt.StandardClaims
are int64 instead of a (to be defined) NumericDate
type. Probably solvable with a new structVerifyIssuedAt
, VerifyNotBefore
, VerifyIssuedAt
of jwt.StandardClaims
only compare against an int64 instead of the NumericDate
. Also probably solvable with a new structVerifyIssuedAt
, VerifyNotBefore
, VerifyIssuedAt
of jwt.MapClaims
only compare against an int64 instead of the NumericDate
. Trickier. I do not want to touch jwt.MapClaims
too much. Probably the introduction of a new set of functions can be made and the old ones set to deprecated.Audience
of jwt.StandardClaims
should be a []string
instead of string
. Could also be part of the new structAnything else that comes to mind?
At some point, it would also probably a good idea to check, whether RFC8725 is also properly reflected in the implementation.
Originally posted by @oxisto in #9 (comment)
Such that moving the API to github.com/golang-jwt/jwt/v3
for v3 releases. This helps downstream projects such as github.com/minio/minio - to pin to a correct release.
The problem with go.mod
's - v3.2.1+incompatible
would simply be unexpected
The original issue that was neverhttps://github.com/dgrijalva/jwt-go/issues/294
Anything else we are missing for 4.0?
I would say, you are good to Go, @mfridman
Any last minute objections from anyone else, @Waterdrips, @lggomez, @ripienaar?
We should remove/replace it, to be compatible with future Go versions.
Migrated from dgrijalva/jwt-go#456
moloch-- commented on Feb 28
The https://pkg.go.dev/github.com/dgrijalva/jwt-go#Keyfunc does not specify what should be returned, it simply says "supply the key for verification." Should the function return the JSON key structure? A byte array of the base64 encoded public key? A byte array of the raw key material? A PEM encoded key? A parsed RSA Key?
The documentation should specify what is returned when, assuming different values should be returned for different signing mechanism.
The function signature is also documented as func(token *jwt.Token) ([]byte, error), however in practice it seems the function must be implemented as func(token *jwt.Token) (interface{}, error)
I have a k8s application where issuer pod creates JWT token and the client pod parses it for validity. In some situations, the time on the worker nodes are skewed by few seconds (~20sec). So if the issuer pod and the client pod runs on separate worker nodes, the validity of the JWT token fails (ValidationErrorIssuedAt).
// Validates time based claims "exp, iat, nbf".
// There is no accounting for clock skew.
// As well, if any of the above claims are not in the token, it will still
// be considered a valid claim.
func (c StandardClaims) Valid() error {
vErr := new(ValidationError)
now := TimeFunc().Unix()
// The claims below are optional, by default, so if they are set to the
// default value in Go, let's not fail the verification for them.
if c.VerifyExpiresAt(now, false) == false {
delta := time.Unix(now, 0).Sub(time.Unix(c.ExpiresAt, 0))
vErr.Inner = fmt.Errorf("token is expired by %v", delta)
vErr.Errors |= ValidationErrorExpired
}
if c.VerifyIssuedAt(now, false) == false {
vErr.Inner = fmt.Errorf("Token used before issued")
vErr.Errors |= ValidationErrorIssuedAt
}
if c.VerifyNotBefore(now, false) == false {
vErr.Inner = fmt.Errorf("token is not valid yet")
vErr.Errors |= ValidationErrorNotValidYet
}
if vErr.valid() {
return nil
}
return vErr
}
Is there a override option to handle clock skew? The RFC specifies that the JWT implementation may handle clock skew for a few minutes https://datatracker.ietf.org/doc/html/rfc7519#page-10
Migrated from dgrijalva/jwt-go#358:
fredbi commented on Sep 3, 2019
github.com/json-iterator/go is currently one of the fastest libs available to process json.
Besides, it is a simple drop-in replacement for the standard lib, without much code change.I am proposing PR #357 to validate the concept and expose benchmarks on signing and parsing methods.
NOTE: due to some changes in the order of marshalled claims, testable examples verifying the value of the signed string have been adapted to check for decoded claims instead.
The existing project https://github.com/dgrijalva/jwt-go had no module support and was likely imported as:
github.com/dgrijalva/jwt-go v3.2.0+incompatible
There was also a v4 that never got fully released.
go get github.com/dgrijalva/[email protected]
go get: github.com/dgrijalva/[email protected]: invalid version: module contains a go.mod file, so major version must be compatible: should be v0 or v1, not v4
Since users would import a new module anyways, one solution could be drop all existing versions (14 total) and start with a fresh v1.0.0
(hopefully no breaking changes required).
For many of my projects I see this being a basic search/replace operation:
- github.com/dgrijalva/jwt-go v3.2.0+incompatible
+ github.com/golang-jwt/jwt v1.0.0
The version in this case is irrelevant afaics.
Lastly, I am not sure whether the original repo will get "transferred" or "archived" (see comment here), but if it gets transferred then this might change the outcome of how to proceed adding module support?
Thoughts, suggestions welcome.
GitHub Actions probably makes the most sense for OSS projects like this to avoid another dependency on external services.
Setup CI for existing tests on every push
+--------+---------+-------------------------------------+-------+------+------+------+
| STATUS | ELAPSED | PACKAGE | COVER | PASS | FAIL | SKIP |
+--------+---------+-------------------------------------+-------+------+------+------+
| PASS | 0.10s | github.com/dgrijalva/jwt-go/request | 78.4% | 4 | 0 | 0 |
| PASS | 0.21s | github.com/dgrijalva/jwt-go | 78.3% | 24 | 0 | 0 |
+--------+---------+-------------------------------------+-------+------+------+------+
+--------+---------+-----------------------------------------+---------+
| STATUS | ELAPSED | TEST | PACKAGE |
+--------+---------+-----------------------------------------+---------+
| PASS | 0.03 | TestECDSAVerify | jwt-go |
| PASS | 0.01 | TestParser_Parse | jwt-go |
| PASS | 0.01 | TestECDSASign | jwt-go |
| PASS | 0.01 | TestRSAPSSSaltLengthCompatibility | jwt-go |
| PASS | 0.01 | TestParser_ParseUnverified | jwt-go |
| PASS | 0.00 | TestRSASign | jwt-go |
| PASS | 0.00 | TestNoneSign | jwt-go |
| PASS | 0.00 | TestNoneVerify | jwt-go |
| PASS | 0.00 | TestRSAPSSVerify | jwt-go |
| PASS | 0.00 | TestRSAPSSSign | jwt-go |
| PASS | 0.00 | TestHMACSign | jwt-go |
| PASS | 0.00 | TestRSAVerify | jwt-go |
| PASS | 0.00 | TestHMACVerify | jwt-go |
| PASS | 0.00 | TestRSAVerifyWithPreParsedPrivateKey | jwt-go |
| PASS | 0.00 | TestRSAWithPreParsedPrivateKey | jwt-go |
| PASS | 0.00 | TestRSAKeyParsing | jwt-go |
| PASS | 0.00 | ExampleNewWithClaims_standardClaims | jwt-go |
| PASS | 0.00 | ExampleNewWithClaims_customClaimsType | jwt-go |
| PASS | 0.00 | ExampleParseWithClaims_customClaimsType | jwt-go |
| PASS | 0.00 | ExampleParse_errorChecking | jwt-go |
| PASS | 0.00 | ExampleNew_hmac | jwt-go |
| PASS | 0.00 | ExampleParse_hmac | jwt-go |
| PASS | 0.00 | Example_getTokenViaHTTP | jwt-go |
| PASS | 0.00 | Example_useTokenViaHTTP | jwt-go |
| | | | |
| PASS | 0.01 | TestParseRequest | request |
| PASS | 0.00 | TestExtractor | request |
| PASS | 0.00 | ExampleHeaderExtractor | request |
| PASS | 0.00 | ExampleArgumentExtractor | request |
+--------+---------+-----------------------------------------+---------+
See https://golang.org/doc/devel/release#policy
Each major Go release is supported until there are two newer major releases. For example, Go 1.5 was supported until the Go 1.7 release, and Go 1.6 was supported until the Go 1.8 release. We fix critical problems, including critical security problems, in supported releases as needed by issuing minor revisions (for example, Go 1.6.1, Go 1.6.2, and so on).
Unsupported versions of Go (more than two major versions old) do not receive fixes for critical security problems,
so should be considered insecure.
As security is important in this library, we should make sure we should not build it on insecure versions of the tool-chain and standard libraries. We should therefore remove support for obsolete versions of Go (currently 1.14 and below).
Does anyone object to the default branch being migrated to main
The v4 branch has a nice validation helper struct which combines a lot of the functionality of the Validate
functions. It might be nice to re-implement that and slowly move existing functionality to it.
This would include things that have been on the wishlist in other forks, such as having leeway when validating timestamps (see form3tech-oss/jwt-go#12).
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.