A go implementation of JSON Web Tokens

jwt-go

build Go Reference

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

NEW VERSION COMING: There have been a lot of improvements suggested since the version 3.0.0 released in 2016. I'm working now on cutting two different releases: 3.2.0 will contain any non-breaking changes or enhancements. 4.0.0 will follow shortly which will include breaking changes. See the 4.0.0 milestone to get an idea of what's coming. If you have other ideas, or would like to participate in 4.0.0, now's the time. If you depend on this library and don't want to be interrupted, I recommend you use your dependency mangement tool to pin to version 3.

SECURITY NOTICE: Some older versions of Go have a security issue in the crypto/elliptic. Recommendation is to upgrade to at least 1.8.3. See issue #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 match the expected alg, but you should take the extra step to verify it in your usage. See the examples provided.

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.

Examples

See the project documentation for examples of usage:

Extensions

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

Here's an example of an extension that integrates with multiple Google Cloud Platform signing tools (AppEngine, IAM API, Cloud KMS): https://github.com/someone1/gcp-jwt-go

Compliance

This library was last reviewed to comply with RTF 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 backwards-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.

While we try to make it obvious when we make breaking changes, there isn't a great mechanism for pushing announcements out to users. You may want to use this alternative package include: gopkg.in/golang-jwt/jwt.v3. It will do the right thing WRT semantic versioning.

BREAKING CHANGES:*

  • Version 3.0.0 includes a lot of changes from the 2.x line, including a few that break the API. We've tried to break as few things as possible, so there should just be a few type signature changes. A full list of breaking changes is available in VERSION_HISTORY.md. See MIGRATION_GUIDE.md for more information on updating your code.

Usage Tips

Signing vs Encryption

A token is simply a JSON object that is signed by its author. this tells you exactly two things about the data:

  • The author of the token was in the possession of the signing secret
  • The data has not been modified since it was signed

It's important to know that JWT does not provide encryption, which means anyone who has access to the token can read its contents. If you need to protect (encrypt) the data, there is a companion spec, JWE, that provides this functionality. JWE is currently outside the scope of this library.

Choosing a Signing Method

There are several signing methods available, and you should probably take the time to learn about the various options before choosing one. The principal design decision is most likely going to be symmetric vs asymmetric.

Symmetric signing methods, such as HSA, use only a single secret. This is probably the simplest signing method to use since any []byte can be used as a valid secret. They are also slightly computationally faster to use, though this rarely is enough to matter. Symmetric signing methods work the best when both producers and consumers of tokens are trusted, or even the same system. Since the same secret is used to both sign and validate tokens, you can't easily distribute the key for validation.

Asymmetric signing methods, such as RSA, use different keys for signing and verifying tokens. This makes it possible to produce tokens with a private key, and allow any consumer to access the public key for verification.

Signing Methods and Key Types

Each signing method expects a different object type for its signing keys. See the package documentation for details. Here are the most common ones:

  • The HMAC signing method (HS256,HS384,HS512) expect []byte values for signing and validation
  • The RSA signing method (RS256,RS384,RS512) expect *rsa.PrivateKey for signing and *rsa.PublicKey for validation
  • The ECDSA signing method (ES256,ES384,ES512) expect *ecdsa.PrivateKey for signing and *ecdsa.PublicKey for validation

JWT and OAuth

It's worth mentioning that OAuth and JWT are not the same thing. A JWT token is simply a signed JSON object. It can be used anywhere such a thing is useful. There is some confusion, though, as JWT is the most common type of bearer token used in OAuth2 authentication.

Without going too far down the rabbit hole, here's a description of the interaction of these technologies:

  • OAuth is a protocol for allowing an identity provider to be separate from the service a user is logging in to. For example, whenever you use Facebook to log into a different service (Yelp, Spotify, etc), you are using OAuth.
  • OAuth defines several options for passing around authentication data. One popular method is called a "bearer token". A bearer token is simply a string that should only be held by an authenticated user. Thus, simply presenting this token proves your identity. You can probably derive from here why a JWT might make a good bearer token.
  • Because bearer tokens are used for authentication, it's important they're kept secret. This is why transactions that use bearer tokens typically happen over SSL.

Troubleshooting

This library uses descriptive error messages whenever possible. If you are not getting the expected result, have a look at the errors. The most common place people get stuck is providing the correct type of key to the parser. See the above section on signing methods and key types.

More

Documentation can be found on pkg.go.dev.

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.

Comments
  • Backwards-compatible implementation of RFC7519's registered claim's structure

    Backwards-compatible implementation of RFC7519's registered claim's structure

    This PR aims at implementing compliance to RFC7519, as documented in #11 without breaking the public API. It creates a new struct RegisteredClaims and deprecates (but not removes) the StandardClaims. It introduces a new type NumericDate, which represents a JSON numeric date value as specified in the RFC. This allows us to handle float as well as int-based time fields in aud, exp and nbf. Additionally, it introduces the type StringArray, which is basically a wrapper around []string to deal with the oddities of the JWT aud field.

    Closes #11

  • Address cached references to old versions in the Go module proxy

    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

  • Placeholder repo migrating maintenance

    Placeholder repo migrating maintenance

    See https://github.com/dgrijalva/jwt-go/issues/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.

    https://github.com/dgrijalva/jwt-go/issues/428 https://github.com/dgrijalva/jwt-go/issues/463

    cc @ripienaar @Waterdrips @lggomez

  • New validation API

    New validation API

    Some guidelines in designing the new validation API

    • Previously, the Valid method was placed on the claim, which was always not entirely semantically correct, since the validity is concerning the token, not the claims. Although the validity of the token is based on the processing of the claims (such as exp). Therefore, the function Valid was removed from the Claims interface and the single canonical way to retrieve the validity of the token is to retrieve the Valid property of the Token struct.
    • The previous fact was enhanced by the fact that most claims implementations had additional exported VerifyXXX functions, which are now removed
    • All validation errors should be comparable with errors.Is to determine, why a particular validation has failed
    • Developers want to adjust validation options. Popular options include:
      • Leeway when processing exp, nbf, iat (#98, #237)
      • Setting the time manually, especially for testing (#188)
      • Not verifying iat, since this is actually just an informational claim. When purely looking at the standard, this should probably the default (#175)
      • Verifying aud by default, which actually the standard sort of demands. We need to see how strong we want to enforce this
    • Developers want to create their own claim types, mostly by embedding one of the existing types such as RegisteredClaims.
      • Sometimes there is the need to further tweak the validation of a token by checking the value of a custom claim. Previously, this was possibly by overriding Valid. However, this was error-prone, e.g., if the original Valid was not called. Therefore, we should provide an easy way for additional checks, without by-passing the necessary validations

    This leads to the following two major changes:

    • The Claims interface now represents a set of functions that return the mandatory claims represented in a token, such as exp, and so on, rather than just a Valid function. This is also more semantically correct and makes our codebase smaller and way more maintainable.
    • All validation tasks are offloaded to a new (optional) Validator, which can also be configured with appropriate options. If no custom validator was supplied, a default one is used.

    Some smaller goodies:

    • This introduces a new convenience feature for map claims: ParseXXX (naming to change) functions, that make it easy to parse a key as a certain JWT special type such as numeric date.

    Remaining tasks

    • [x] Provide a way for custom claims for additional verification
    • [x] Update examples with validator goodness
    • [x] Add option to skip iat
    • [x] Moving the TimeFunc to the validator instead of a global function
    • [x] Make aud verification default-ish, at least if a new validator is provided
  • key is of invalid type for

    key is of invalid type for "typ": "JWS"

    My JWT has a header like this:

    {
      "typ": "JWS",
      "alg": "RS256",
      "kid": "9167337"
    }
    

    Note this is is JWS not JWT.

    When I call jwt.Parse() on it like this, I get token.Valid is false:

    token, err := jwt.Parse(authToken, func(token *jwt.Token) (interface{}, error) {
            return []byte("AllYourBase"), nil
    })
    

    The error is "key is of invalid type". Am I doing something wrong here, or is JWS unsupported?

  • Due to the use of fillBytes golang-jwt now requires go1.15

    Due to the use of fillBytes golang-jwt now requires go1.15

    https://github.com/golang-jwt/jwt/blob/4bbdd8ac624fc7a9ef7aec841c43d99b5fe65a29/ecdsa.go#L135-L136

    from #33, means that golang-jwt/jwt now requires go1.15.

    Is this intentional?

  • Adds go module support /v4

    Adds go module support /v4

    Introduces modules support with with/v4 SIV

    • [x] Update migration guide
    • [x] Update README to ensure import paths are correct referenced

    fixes #5 #3 #30

  • JWE Support

    JWE Support

    Issue #67

    Add support of JWE with one key (Compact)

    Add AES GCM cipher to encrypt content Add RSA-OAEP to encrypt key

    Add test from RFC7516 Section 3.3

    cc @mfridman

  • v4.4.0 breaks backwards compatibilty

    v4.4.0 breaks backwards compatibilty

    After upgrading from 4.3.0 to 4.4.0, my custom implementation of the Claims interface is broken:

    	*Claims does not implement jwt.Claims (wrong type for Valid method)
    		have Valid() error
    		want Valid(opts ...jwt.validationOption) error
    
  • Revert Encoding/Decoding changes for better compatibility

    Revert Encoding/Decoding changes for better compatibility

    This is a small revert to the optimizations made to the encoding/decoding in https://github.com/golang-jwt/jwt/pull/33.

    While technically JWTs should not have padded characters in Base64 URL encoding, it seems like not every provider may follow this construct, specifically AWS Cognito as seen in https://github.com/golang-jwt/jwt/issues/92.

    While the change initially was made to have better optimization, it has left compatibility issues, forcing dependencies to stay on v3.2.1 until an update occurs. Thus the proposal is to simply undo the changes made in that section of code, and create a new ticket to better optimize this section.

  • upstream fix for security vulnerability from form3tech-oss/jwt-go fork

    upstream fix for security vulnerability from form3tech-oss/jwt-go fork

    This forwards the changes of https://github.com/form3tech-oss/jwt-go/pull/14 to the upstream repository.

    I am not the author of the original PR (nor do I know much about JWT), but thought I'd give this an attempt, following the discussion in https://github.com/Azure/go-autorest/issues/642 (and issues linked from there).

    Fixes a security vulnerability where a jwt token could potentially be validated having invalid string characters.

    (cherry picked from commit a211650c6ae1cff6d7347d3e24070d65dcfb1122) https://github.com/form3tech-oss/jwt-go/pull/14

  • Support pkcs8 from Apple APNs

    Support pkcs8 from Apple APNs

    Hi, After spending a few hours on trying to import Apple Mapkit p8 file, which is pkcs8, i have stumbled on someones post here: https://github.com/dgrijalva/jwt-go/issues/179

    It includes a working function to import the private key, i've tested it and it works. While i am not the author of the post in the link, i feel it would be beneficial to many people to have this function be included in your repo. Would you be interested in a pull request with the above mentioned change ? I will make sure to include the original author.

  • PRISMA-2022-0270 security vulnerability in version v4.4.2

    PRISMA-2022-0270 security vulnerability in version v4.4.2

    Found the vulnerability with CVE code PRISMA-2022-0270 in version v4.4.2. Can we get this fixed?

    Vulnerability description: github.com/golang-jwt/jwt/v4 module from all versions is vulnerable to Denial of Service (DoS) due to token without ExpiresAt can cause panic.

  • Improve precision on NumericDate.UnmarshalJSON

    Improve precision on NumericDate.UnmarshalJSON

    I faced an precision issue when calling UnmarshalJSON for NumericDate.
    For example, when original unix time was 9223371974719179007,
    NumericDate.Unix() shows 9223371974719178752 after json.Unmarshal.

    	var t jwt.NumericDate
    	json.Unmarshal([]byte("9223371974719179007"), &t)
    	fmt.Println(t.Unix()) // 9223371974719178752
    

    I think that this issue is caused because code uses float64.

    https://github.com/golang-jwt/jwt/blob/0c4e3879854669acd15ea435f2c8aada6c73810a/types.go#L88-L93

    This patch use rational type of math/big standard package when parcing JSON to improve precision.

    This patch includes test by 10bc0152ec873c8c510a6c6db7c14a0470a6c43e .
    We can check that added test is going to be failed by checkout 10bc0152ec873c8c510a6c6db7c14a0470a6c43e .

Gets Firebase auth tokens (for development purposes only)Gets Firebase auth tokens

Firebase Token Gets Firebase auth tokens (for development purposes only) Getting started Create Firebase project Setup Firebase authentication Setup G

Nov 17, 2021
Safe, simple and fast JSON Web Tokens for Go

jwt JSON Web Token for Go RFC 7519, also see jwt.io for more. The latest version is v3. Rationale There are many JWT libraries, but many of them are h

Jan 4, 2023
A simple and lightweight library for creating, formatting, manipulating, signing, and validating JSON Web Tokens in Go.

GoJWT - JSON Web Tokens in Go GoJWT is a simple and lightweight library for creating, formatting, manipulating, signing and validating Json Web Tokens

Nov 15, 2022
Microservice generates pair of access and refresh JSON web tokens signed by user identifier.

go-jwt-issuer Microservice generates pair access and refresh JSON web tokens signed by user identifier. ?? Deployed on Heroku Run tests: export SECRET

Nov 21, 2022
Platform-Agnostic Security Tokens implementation in GO (Golang)

Golang implementation of PASETO: Platform-Agnostic Security Tokens This is a 100% compatible pure Go (Golang) implementation of PASETO tokens. PASETO

Jan 2, 2023
:key: Secure alternative to JWT. Authenticated Encrypted API Tokens for Go.

branca branca is a secure alternative to JWT, This implementation is written in pure Go (no cgo dependencies) and implements the branca token specific

Dec 29, 2022
Oct 8, 2022
an stateless OpenID Connect authorization server that mints ID Tokens from Webauthn challenges

Webauthn-oidc Webauthn-oidc is a very minimal OIDC authorization server that only supports webauthn for authentication. This can be used to bootstrap

Nov 6, 2022
Minting OIDC tokens from GitHub Actions for use with OpenFaaS

minty Experiment for minting OIDC tokens from GitHub Actions for use with OpenFaaS Why would you want this? Enable third-parties to deploy to your ope

Oct 31, 2021
Golang jwt tokens without any external dependency

Yet another jwt lib This is a simple lib made for small footprint and easy usage It allows creating, signing, reading and verifying jwt tokens easily

Oct 11, 2021
Utility to generate tokens to interact with GitHub API via GitHub App integration

GitHub App Authentication for integration with GitHub Introduction GitHub Apps are the officially recommended way to integrate with GitHub because of

Mar 16, 2022
Generate and verify JWT tokens with Trusted Platform Module (TPM)

golang-jwt for Trusted Platform Module (TPM) This is just an extension for go-jwt i wrote over thanksgiving that allows creating and verifying JWT tok

Oct 7, 2022
Go module with token package to request Azure Resource Manager and Azure Graph tokens.

azAUTH Go module with token package to request Azure Resource Manager and Azure Graph tokens. prerequisites Install azure cli: https://docs.microsoft.

Dec 1, 2021
Generate and verify JWT tokens with PKCS-11

golang-jwt for PKCS11 Another extension for go-jwt that allows creating and verifying JWT tokens where the private key is embedded inside Hardware lik

Dec 5, 2022
OauthMicroservice-cassandraCluster - Implement microservice of oauth using golang and cassandra to store user tokens

implement microservice of oauth using golang and cassandra to store user tokens

Jan 24, 2022
Generate a generic library of 2FA tokens compatible with Google Authenticator

towfa Generate a generic library of 2FA tokens compatible with Google Authenticator go get -u github.com/golandscape/twofa $twofa "you secret" result:

Mar 23, 2022
Authenticated and encrypted API tokens using modern crypto

Branca Token Authenticated and encrypted API tokens using modern crypto. What? Branca is a secure, easy to use token format which makes it hard to sho

Dec 25, 2022
Authenticated encrypted API tokens (IETF XChaCha20-Poly1305 AEAD) for Golang

branca.go is branca token specification implementation for Golang 1.15+.

Dec 26, 2022
JSON Web Token library

About … a JSON Web Token (JWT) library for the Go programming language. Feature complete Full test coverage Dependency free Key management The API enf

Dec 19, 2022