Giter VIP home page Giter VIP logo

jwt's Introduction

jwt-go

build Go Reference Coverage Status

A go (or 'golang' for search engine friendliness) implementation of JSON Web Tokens.

Starting with v4.0.0 this project adds Go module support, but maintains backward compatibility with older v3.x.y tags and upstream github.com/dgrijalva/jwt-go. See the MIGRATION_GUIDE.md for more information. Version v5.0.0 introduces major improvements to the validation of tokens, but is not entirely backward compatible.

After the original author of the library suggested migrating the maintenance of jwt-go, a dedicated team of open source maintainers decided to clone the existing library into this repository. See dgrijalva/jwt-go#462 for a detailed discussion on this topic.

SECURITY NOTICE: Some older versions of Go have a security issue in the crypto/elliptic. The recommendation is to upgrade to at least 1.15 See issue dgrijalva/jwt-go#216 for more detail.

SECURITY NOTICE: It's important that you validate the alg presented is what you expect. This library attempts to make it easy to do the right thing by requiring key types to match the expected alg, but you should take the extra step to verify it in your usage. See the examples provided.

Supported Go versions

Our support of Go versions is aligned with Go's version release policy. So we will support a major version of Go until there are two newer major releases. We no longer support building jwt-go with unsupported Go versions, as these contain security vulnerabilities that will not be fixed.

What the heck is a JWT?

JWT.io has a great introduction to JSON Web Tokens.

In short, it's a signed JSON object that does something useful (for example, authentication). It's commonly used for Bearer tokens in Oauth 2. A token is made of three parts, separated by .'s. The first two parts are JSON objects, that have been base64url encoded. The last part is the signature, encoded the same way.

The first part is called the header. It contains the necessary information for verifying the last part, the signature. For example, which encryption method was used for signing and what key was used.

The part in the middle is the interesting bit. It's called the Claims and contains the actual stuff you care about. Refer to RFC 7519 for information about reserved keys and the proper way to add your own.

What's in the box?

This library supports the parsing and verification as well as the generation and signing of JWTs. Current supported signing algorithms are HMAC SHA, RSA, RSA-PSS, and ECDSA, though hooks are present for adding your own.

Installation Guidelines

  1. To install the jwt package, you first need to have Go installed, then you can use the command below to add jwt-go as a dependency in your Go program.
go get -u github.com/golang-jwt/jwt/v5
  1. Import it in your code:
import "github.com/golang-jwt/jwt/v5"

Usage

A detailed usage guide, including how to sign and verify tokens can be found on our documentation website.

Examples

See the project documentation for examples of usage:

Compliance

This library was last reviewed to comply with RFC 7519 dated May 2015 with a few notable differences:

  • In order to protect against accidental use of Unsecured JWTs, tokens using alg=none will only be accepted if the constant jwt.UnsafeAllowNoneSignatureType is provided as the key.

Project Status & Versioning

This library is considered production ready. Feedback and feature requests are appreciated. The API should be considered stable. There should be very few backward-incompatible changes outside of major version updates (and only with good reason).

This project uses Semantic Versioning 2.0.0. Accepted pull requests will land on main. Periodically, versions will be tagged from main. You can find all the releases on the project releases page.

BREAKING CHANGES: A full list of breaking changes is available in VERSION_HISTORY.md. See MIGRATION_GUIDE.md for more information on updating your code.

Extensions

This library publishes all the necessary components for adding your own signing methods or key functions. Simply implement the SigningMethod interface and register a factory method using RegisterSigningMethod or provide a jwt.Keyfunc.

A common use case would be integrating with different 3rd party signature providers, like key management services from various cloud providers or Hardware Security Modules (HSMs) or to implement additional standards.

Extension Purpose Repo
GCP Integrates with multiple Google Cloud Platform signing tools (AppEngine, IAM API, Cloud KMS) https://github.com/someone1/gcp-jwt-go
AWS Integrates with AWS Key Management Service, KMS https://github.com/matelang/jwt-go-aws-kms
JWKS Provides support for JWKS (RFC 7517) as a jwt.Keyfunc https://github.com/MicahParks/keyfunc

Disclaimer: Unless otherwise specified, these integrations are maintained by third parties and should not be considered as a primary offer by any of the mentioned cloud providers

More

Go package documentation can be found on pkg.go.dev. Additional documentation can be found on our project page.

The command line utility included in this project (cmd/jwt) provides a straightforward example of token creation and parsing as well as a useful tool for debugging your own integration. You'll also find several implementation examples in the documentation.

golang-jwt incorporates a modified version of the JWT logo, which is distributed under the terms of the MIT License.

jwt's People

Contributors

abdollar avatar aboodman avatar abourget avatar albrow avatar alexandear avatar alexanderyastrebov avatar alias-dev avatar amnonbc avatar appleboy avatar ashikpaul avatar aussiegeek avatar bbigras avatar bruston avatar cenkalti avatar cryptix avatar dakom avatar dependabot[bot] avatar dgrijalva avatar estensen avatar itsjamie avatar johnlockwood-wf avatar lggomez avatar mfridman avatar oxisto avatar sebastien-rosset avatar simonjefford avatar vongohren avatar waterdrips avatar xyproto avatar zimbatm avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

jwt's Issues

Community: Looking for a logo

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?

v3.2.2+incompatible build have error

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)

Placeholder repo migrating maintenance

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:

  1. patch any outstanding security issues
  2. add module support
  3. maintain the existing jwt-go API in its current form
  4. setup GitHub Actions as CI for existing tests
  5. have a few independent maintainers to spread the load and trust of maintenance with the ultimate goal of the Go community having access to a stable JWT package.

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.

dgrijalva/jwt-go#428
dgrijalva/jwt-go#463

cc @ripienaar @Waterdrips @lggomez

jwt.io - Update package feature set

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/

Create a contribution guide

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

Compliance with published RFC7519

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):

  • The fields ExpiresAt, IssuedAt, NotBefore in jwt.StandardClaims are int64 instead of a (to be defined) NumericDate type. Probably solvable with a new struct
  • The functions VerifyIssuedAt, VerifyNotBefore, VerifyIssuedAt of jwt.StandardClaims only compare against an int64 instead of the NumericDate. Also probably solvable with a new struct
  • The functions VerifyIssuedAt, 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 struct

Anything 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)

Remove deprecated functions

We have several deprecated functions and structs, mainly introduced due to #15 and #44. We should remove them in a future release, such as v5. This issues keeps track of that.

Handling and migration of original project issues

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:

  • Perform a triage there and only migrate the actionables manually (we're talking about 90 issues as of today)
  • Use some automated tool (TBD) and perform triage here

Replace encoding/json with jsoniter

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.

Does this support the x5c/x5u fields in JWS? (RFC-7515)

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)

HelpWanted: handling clock skew for nbf, exp and iat

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

How handle tokens issued by previous libarary.

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?

Please add err.types

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.

Support for EdDSA

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.

jwt.Parse got "invalid character 'x' looking for beginning of value"

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 1

I 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....

Proper go.mod support

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

Bring over ValidationHelper functionality from v4 branch

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).

Incorporate string array in `aud` field from the original v4 branch

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 as aud 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 in aud validation behavior now expects []string instead of string. This was a common request.

It would be nice to see that picked up and moved forward, as well.

Security disclosure information

We need to create a process for individuals to be able to disclose security vulnerabilities responsibly.

I suggest:

  • We create a "SECURITY.md" file with contact information of one/some people here who will be designated security contact.
  • Add information to our README/Contributing guide as to how to disclose security issues (not open issues/PRs without contacting security etc)
  • Discuses/publish our security patch processes and any backporting we intecnd to do (set the library users expectations)

Keyfunc usage and token Parsing examples

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)

Address cached references to old versions in the Go module proxy

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

Used for two different module paths error in go mod tidy

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?

v4 preview 1, "functional options" for constructors don't work as intended outside the package

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.

Add to awesome-go & misc

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

VerifyIssuedAt in mapclaims broken

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

Add GitHub Actions for CI

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

RS256 message too long for RSA public key size

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?

Add go module support

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.

Add GitHub Discussions

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.

Example code is memory insecure

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)

Remove support for obsolete Go versions

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).

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.