A go implementation of JSON Web Tokens

Related tags

go golang jwt auth
Overview

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.

Issues
  • 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

    opened by mfridman 17
  • Add go module support

    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.

    opened by mfridman 10
  • Add GitHub Actions for CI

    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 |
    +--------+---------+-----------------------------------------+---------+
    
    opened by mfridman 9
  • Enable go module support for the project

    Enable go module support for the project

    through this series of commits i have enabled go module support by following official docs. All README files are subjected to further changes

    opened by sadmansakib 6
  • Fix security vulnerability (CVE-2020-26160)

    Fix security vulnerability (CVE-2020-26160)

    More detailed explanation here: https://github.com/dgrijalva/jwt-go/issues/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.

    security 
    opened by mfridman 6
  • Fix issue with MapClaims VerifyAudience []string

    Fix issue with MapClaims VerifyAudience []string

    There was an issue in MapClaims's VerifyAudiance where a []string (which is valid in the spec) would return true (claim is found, or nil) when required was not set. It now checks interface types correctly and has tests written

    Fixes: #6 Signed-off-by: Alistair Hey [email protected]

    security 
    opened by Waterdrips 4
  • update MIGRATION_GUIDE and VERSION_HISTORY

    update MIGRATION_GUIDE and VERSION_HISTORY

    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

    opened by Waterdrips 3
  • Providing (almost) full test matrix in GitHub actions

    Providing (almost) full test matrix in GitHub actions

    Starting with Go 1.7, since this is the lowest version still working, once we merge in #12. We can then gradually move upwards with new PRs.

    opened by oxisto 2
  • Migrate default branch to Main

    Migrate default branch to Main

    Does anyone object to the default branch being migrated to main

    https://github.com/github/renaming

    opened by Waterdrips 2
  • chore: code cleanup

    chore: code cleanup

    This PR slightly improves the code quality.

    opened by dunglas 1
  • Security disclosure information

    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)
    opened by Waterdrips 1
  • Create a contribution guide

    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

    opened by Waterdrips 0
  • WIP: Add golanci/golint to github actions

    WIP: Add golanci/golint to github actions

    Add golangci linting to ensure consistent code standards.

    Signed-off-by: Alistair Hey [email protected]

    opened by Waterdrips 1
  • Bring over ValidationHelper functionality from v4 branch

    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 https://github.com/form3tech-oss/jwt-go/pull/12).

    opened by oxisto 0
  • 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.

    aud was also converted to []string.

    Closes #11

    opened by oxisto 7
  • Compliance with published RFC7519

    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 https://github.com/golang-jwt/jwt/pull/9#discussion_r641039944

    opened by oxisto 0
  • fix!: NumericDate parsing conformance

    fix!: NumericDate parsing conformance

    The current implementation of the standard claims parser is invalid. It doesn't allow NumericDate value to be floats, while it's explicitly allowed by the RFC:

    NumericDate A JSON numeric value representing the number of seconds from 1970-01-01T00:00:00Z UTC until the specified UTC date/time, ignoring leap seconds. This is equivalent to the IEEE Std 1003.1, 2013 Edition [POSIX.1] definition "Seconds Since the Epoch", in which each day is accounted for by exactly 86400 seconds, other than that non-integer values can be represented. See RFC 3339 [RFC3339] for details regarding date/times in general and UTC in particular.

    (Emphasis mine).

    This is annoying because popular libraries generate tokens containing floats in the exp, iat and nbf fields. For instance, it's the case of lcobucci/jwt, one of the most popular JWT library written in PHP.

    This PR fixes this, and also allows comparing fractions of seconds.

    This is a BC break, so it should be merged in the 4.0 version.

    Also, as this library is a core dependency of my Mercure project, if you need help for the maintenance of this library, I'll be glad to participate!

    Closes https://github.com/dunglas/mercure/issues/404 and https://github.com/form3tech-oss/jwt-go/pull/11.

    opened by dunglas 5
  • Handling and migration of original project issues

    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
    opened by lggomez 4
  • Handling and migration of original project PRs

    Handling and migration of original project PRs

    We have to define how to deal with the original project's PRs

    We can either:

    • Triage and port then manulally (we're talking about 42 as of today)
    • Use some automated (albeit complicated) solution like https://github.com/NicholasBoll/github-migration
    opened by lggomez 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

    opened by mfridman 13
Releases(v3.2.1)
  • v3.2.1(Jun 8, 2021)

    • Import Path Change: See MIGRATION_GUIDE.md for tips on updating your code
      • Changed the import path from github.com/dgrijalva/jwt-go to github.com/golang-jwt/jwt
    • Fixed type confusion issue between string and []string in VerifyAudience (#12). This fixes CVE-2020-26160
    Source code(tar.gz)
    Source code(zip)
A fast and simple JWT implementation for Go

JWT Fast and simple JWT implementation written in Go. This package was designed with security, performance and simplicity in mind, it protects your to

Gerasimos (Makis) Maropoulos 93 Jun 12, 2021
Golang implementation of JSON Web Tokens (JWT)

jwt-go A go (or 'golang' for search engine friendliness) implementation of JSON Web Tokens NEW VERSION COMING: There have been a lot of improvements s

Dave Grijalva 9.7k Jun 14, 2021
The boss of http auth.

Authboss Authboss is a modular authentication system for the web. It has several modules that represent authentication and authorization features that

Volatile Technologies Inc. 2.7k Jun 13, 2021
A go implementation of JSON Web Tokens

jwt-go A go (or 'golang' for search engine friendliness) implementation of JSON Web Tokens NEW VERSION COMING: There have been a lot of improvements s

null 27 Jun 17, 2021
A standalone, specification-compliant, OAuth2 server written in Golang.

Go OAuth2 Server This service implements OAuth 2.0 specification. Excerpts from the specification are included in this README file to describe differe

Richard Knop 1.8k Jun 9, 2021
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

Oleg Lobanov 516 Jun 11, 2021
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

Pascal S. de Kloe 255 Jun 16, 2021
⛩️ Go library for protecting HTTP handlers with authorization bearer token.

G8, pronounced Gate, is a simple Go library for protecting HTTP handlers with tokens. Tired of constantly re-implementing a security layer for each

Chris C. 28 Jun 17, 2021
JWT login microservice with plugable backends such as OAuth2, Google, Github, htpasswd, osiam, ..

loginsrv loginsrv is a standalone minimalistic login server providing a JWT login for multiple login backends. ** Attention: Update to v1.3.0 for Goog

tarent 1.8k Jun 12, 2021
Small Lambda function which performs a Aws:Sts:AssumeRole based on the presented JWT-Token

About This implements a AWS Lambda handler which takes a JWT-Token, validates it and then performs a Aws:Sts:AssumeRole based on preconfigured rules.

AOE 3 May 13, 2021
An implementation of JOSE standards (JWE, JWS, JWT) in Go

Go JOSE Package jose aims to provide an implementation of the Javascript Object Signing and Encryption set of standards. This includes support for JSO

Square 1.8k Jun 12, 2021
Certificate authority and access plane for SSH, Kubernetes, web applications, and databases

Teleport is an identity-aware, multi-protocol access proxy which understands SSH, HTTPS, Kubernetes API, MySQL and PostgreSQL wire protocols.

Teleport 9.6k Jun 14, 2021
Go + Vue开发的管理系统脚手架, 前后端分离, 仅包含项目开发的必需部分, 基于角色的访问控制(RBAC), 分包合理, 精简易于扩展。 后端Go包含了gin、 gorm、 jwt和casbin等的使用, 前端Vue基于vue-element-admin开发

go-web-mini Go + Vue开发的管理系统脚手架, 前后端分离, 仅包含项目开发的必需部分, 基于角色的访问控制(RBAC), 分包合理, 精简易于扩展。 后端Go包含了gin、 gorm、 jwt和casbin等的使用, 前端Vue基于vue-element-admin开发: http

gnimli 14 Apr 22, 2021
Time-Based One-Time Password (TOTP) and HMAC-Based One-Time Password (HOTP) library for Go.

otpgo HMAC-Based and Time-Based One-Time Password (HOTP and TOTP) library for Go. Implements RFC 4226 and RFC 6238. Contents Supported Operations Read

Jose Torres 19 May 23, 2021