├── .github ├── dependabot.yml └── workflows │ ├── build.yml │ ├── codeql-analysis.yml │ └── lint.yml ├── .gitignore ├── LICENSE ├── MIGRATION_GUIDE.md ├── README.md ├── SECURITY.md ├── VERSION_HISTORY.md ├── claims.go ├── cmd └── jwt │ ├── README.md │ └── main.go ├── doc.go ├── ecdsa.go ├── ecdsa_test.go ├── ecdsa_utils.go ├── ed25519.go ├── ed25519_test.go ├── ed25519_utils.go ├── errors.go ├── errors_go1_20.go ├── errors_go_other.go ├── errors_test.go ├── example_test.go ├── go.mod ├── go.sum ├── hmac.go ├── hmac_example_test.go ├── hmac_test.go ├── http_example_test.go ├── jwt_test.go ├── map_claims.go ├── map_claims_test.go ├── none.go ├── none_test.go ├── parser.go ├── parser_option.go ├── parser_test.go ├── registered_claims.go ├── request ├── doc.go ├── extractor.go ├── extractor_example_test.go ├── extractor_test.go ├── oauth2.go ├── request.go └── request_test.go ├── rsa.go ├── rsa_pss.go ├── rsa_pss_test.go ├── rsa_test.go ├── rsa_utils.go ├── signing_method.go ├── staticcheck.conf ├── test ├── ec256-private.pem ├── ec256-public.pem ├── ec384-private.pem ├── ec384-public.pem ├── ec512-private.pem ├── ec512-public.pem ├── ed25519-private.pem ├── ed25519-public.pem ├── examplePaddedKey-public.pem ├── helpers.go ├── hmacTestKey ├── privateSecure.pem ├── sample_key └── sample_key.pub ├── token.go ├── token_option.go ├── token_test.go ├── types.go ├── types_test.go ├── validator.go └── validator_test.go /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | # To get started with Dependabot version updates, you'll need to specify which 2 | # package ecosystems to update and where the package manifests are located. 3 | # Please see the documentation for all configuration options: 4 | # https://docs.github.com/github/administering-a-repository/configuration-options-for-dependency-updates 5 | 6 | version: 2 7 | updates: 8 | - package-ecosystem: "github-actions" 9 | directory: "/" 10 | schedule: 11 | interval: "weekly" 12 | -------------------------------------------------------------------------------- /.github/workflows/build.yml: -------------------------------------------------------------------------------- 1 | name: build 2 | 3 | on: 4 | push: 5 | branches: 6 | - main 7 | pull_request: 8 | types: [opened, synchronize, reopened] 9 | 10 | jobs: 11 | build: 12 | runs-on: ubuntu-latest 13 | strategy: 14 | fail-fast: false 15 | matrix: 16 | go: ["1.22", "1.23", "1.24"] 17 | steps: 18 | - name: Checkout 19 | uses: actions/checkout@v4 20 | - name: Setup Go 21 | uses: actions/setup-go@v5 22 | with: 23 | go-version: "${{ matrix.go }}" 24 | check-latest: true 25 | - name: Check Go code formatting 26 | run: | 27 | if [ "$(gofmt -s -l . | wc -l)" -gt 0 ]; then 28 | gofmt -s -l . 29 | echo "Please format Go code by running: go fmt ./..." 30 | exit 1 31 | fi 32 | - name: Build 33 | run: | 34 | go install github.com/mfridman/tparse@latest 35 | go vet ./... 36 | go test -v -race -count=1 -json -cover ./... | tee output.json | tparse -follow -notests || true 37 | tparse -format markdown -file output.json -all > $GITHUB_STEP_SUMMARY 38 | go build ./... 39 | coverage: 40 | runs-on: ubuntu-latest 41 | steps: 42 | - name: Checkout 43 | uses: actions/checkout@v4 44 | - name: Setup Go 45 | uses: actions/setup-go@v5 46 | - name: Coverage 47 | run: | 48 | go test -v -covermode=count -coverprofile=coverage.cov ./... 49 | - name: Coveralls 50 | uses: coverallsapp/github-action@v2 51 | with: 52 | file: coverage.cov 53 | format: golang 54 | -------------------------------------------------------------------------------- /.github/workflows/codeql-analysis.yml: -------------------------------------------------------------------------------- 1 | # For most projects, this workflow file will not need changing; you simply need 2 | # to commit it to your repository. 3 | # 4 | # You may wish to alter this file to override the set of languages analyzed, 5 | # or to provide custom queries or build logic. 6 | # 7 | # ******** NOTE ******** 8 | # We have attempted to detect the languages in your repository. Please check 9 | # the `language` matrix defined below to confirm you have the correct set of 10 | # supported CodeQL languages. 11 | # 12 | name: "CodeQL" 13 | 14 | on: 15 | push: 16 | branches: [main] 17 | pull_request: 18 | schedule: 19 | - cron: "31 10 * * 5" 20 | 21 | jobs: 22 | analyze: 23 | name: Analyze 24 | runs-on: ubuntu-latest 25 | permissions: 26 | actions: read 27 | contents: read 28 | security-events: write 29 | 30 | strategy: 31 | fail-fast: false 32 | matrix: 33 | language: ["go"] 34 | # CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python' ] 35 | # Learn more: 36 | # https://docs.github.com/en/free-pro-team@latest/github/finding-security-vulnerabilities-and-errors-in-your-code/configuring-code-scanning#changing-the-languages-that-are-analyzed 37 | 38 | steps: 39 | - name: Checkout repository 40 | uses: actions/checkout@v4 41 | 42 | # Initializes the CodeQL tools for scanning. 43 | - name: Initialize CodeQL 44 | uses: github/codeql-action/init@v3 45 | with: 46 | languages: ${{ matrix.language }} 47 | # If you wish to specify custom queries, you can do so here or in a config file. 48 | # By default, queries listed here will override any specified in a config file. 49 | # Prefix the list here with "+" to use these queries and those in the config file. 50 | # queries: ./path/to/local/query, your-org/your-repo/queries@main 51 | 52 | # Autobuild attempts to build any compiled languages (C/C++, C#, or Java). 53 | # If this step fails, then you should remove it and run the build manually (see below) 54 | - name: Autobuild 55 | uses: github/codeql-action/autobuild@v3 56 | 57 | # ℹ️ Command-line programs to run using the OS shell. 58 | # 📚 https://git.io/JvXDl 59 | 60 | # ✏️ If the Autobuild fails above, remove it and uncomment the following three lines 61 | # and modify them (or add more) to build your code if your project 62 | # uses a compiled language 63 | 64 | #- run: | 65 | # make bootstrap 66 | # make release 67 | 68 | - name: Perform CodeQL Analysis 69 | uses: github/codeql-action/analyze@v3 70 | -------------------------------------------------------------------------------- /.github/workflows/lint.yml: -------------------------------------------------------------------------------- 1 | name: golangci 2 | on: 3 | push: 4 | branches: 5 | - main 6 | pull_request: 7 | jobs: 8 | golangci: 9 | name: lint 10 | runs-on: ubuntu-latest 11 | steps: 12 | - name: Checkout code 13 | uses: actions/checkout@v4 14 | - name: Setup Go 15 | uses: actions/setup-go@v5 16 | with: 17 | go-version: "1.24" 18 | check-latest: true 19 | - name: golangci-lint 20 | uses: golangci/golangci-lint-action@v8 21 | with: 22 | # Optional: version of golangci-lint to use in form of v1.2 or v1.2.3 or `latest` to use the latest version 23 | version: latest 24 | 25 | # Optional: working directory, useful for monorepos 26 | # working-directory: somedir 27 | 28 | # Optional: golangci-lint command line arguments. 29 | # args: --issues-exit-code=0 30 | 31 | # Optional: show only new issues if it's a pull request. The default value is `false`. 32 | # only-new-issues: true 33 | 34 | # Optional: if set to true then the all caching functionality will be complete disabled, 35 | # takes precedence over all other caching options. 36 | # skip-cache: true 37 | 38 | # Optional: if set to true then the action don't cache or restore ~/go/pkg. 39 | # skip-pkg-cache: true 40 | 41 | # Optional: if set to true then the action don't cache or restore ~/.cache/go-build. 42 | # skip-build-cache: true 43 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | bin 3 | .idea/ 4 | 5 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2012 Dave Grijalva 2 | Copyright (c) 2021 golang-jwt maintainers 3 | 4 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 5 | 6 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 7 | 8 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 9 | 10 | -------------------------------------------------------------------------------- /MIGRATION_GUIDE.md: -------------------------------------------------------------------------------- 1 | # Migration Guide (v5.0.0) 2 | 3 | Version `v5` contains a major rework of core functionalities in the `jwt-go` 4 | library. This includes support for several validation options as well as a 5 | re-design of the `Claims` interface. Lastly, we reworked how errors work under 6 | the hood, which should provide a better overall developer experience. 7 | 8 | Starting from [v5.0.0](https://github.com/golang-jwt/jwt/releases/tag/v5.0.0), 9 | the import path will be: 10 | 11 | "github.com/golang-jwt/jwt/v5" 12 | 13 | For most users, changing the import path *should* suffice. However, since we 14 | intentionally changed and cleaned some of the public API, existing programs 15 | might need to be updated. The following sections describe significant changes 16 | and corresponding updates for existing programs. 17 | 18 | ## Parsing and Validation Options 19 | 20 | Under the hood, a new `Validator` struct takes care of validating the claims. A 21 | long awaited feature has been the option to fine-tune the validation of tokens. 22 | This is now possible with several `ParserOption` functions that can be appended 23 | to most `Parse` functions, such as `ParseWithClaims`. The most important options 24 | and changes are: 25 | * Added `WithLeeway` to support specifying the leeway that is allowed when 26 | validating time-based claims, such as `exp` or `nbf`. 27 | * Changed default behavior to not check the `iat` claim. Usage of this claim 28 | is OPTIONAL according to the JWT RFC. The claim itself is also purely 29 | informational according to the RFC, so a strict validation failure is not 30 | recommended. If you want to check for sensible values in these claims, 31 | please use the `WithIssuedAt` parser option. 32 | * Added `WithAudience`, `WithSubject` and `WithIssuer` to support checking for 33 | expected `aud`, `sub` and `iss`. 34 | * Added `WithStrictDecoding` and `WithPaddingAllowed` options to allow 35 | previously global settings to enable base64 strict encoding and the parsing 36 | of base64 strings with padding. The latter is strictly speaking against the 37 | standard, but unfortunately some of the major identity providers issue some 38 | of these incorrect tokens. Both options are disabled by default. 39 | 40 | ## Changes to the `Claims` interface 41 | 42 | ### Complete Restructuring 43 | 44 | Previously, the claims interface was satisfied with an implementation of a 45 | `Valid() error` function. This had several issues: 46 | * The different claim types (struct claims, map claims, etc.) then contained 47 | similar (but not 100 % identical) code of how this validation was done. This 48 | lead to a lot of (almost) duplicate code and was hard to maintain 49 | * It was not really semantically close to what a "claim" (or a set of claims) 50 | really is; which is a list of defined key/value pairs with a certain 51 | semantic meaning. 52 | 53 | Since all the validation functionality is now extracted into the validator, all 54 | `VerifyXXX` and `Valid` functions have been removed from the `Claims` interface. 55 | Instead, the interface now represents a list of getters to retrieve values with 56 | a specific meaning. This allows us to completely decouple the validation logic 57 | with the underlying storage representation of the claim, which could be a 58 | struct, a map or even something stored in a database. 59 | 60 | ```go 61 | type Claims interface { 62 | GetExpirationTime() (*NumericDate, error) 63 | GetIssuedAt() (*NumericDate, error) 64 | GetNotBefore() (*NumericDate, error) 65 | GetIssuer() (string, error) 66 | GetSubject() (string, error) 67 | GetAudience() (ClaimStrings, error) 68 | } 69 | ``` 70 | 71 | Users that previously directly called the `Valid` function on their claims, 72 | e.g., to perform validation independently of parsing/verifying a token, can now 73 | use the `jwt.NewValidator` function to create a `Validator` independently of the 74 | `Parser`. 75 | 76 | ```go 77 | var v = jwt.NewValidator(jwt.WithLeeway(5*time.Second)) 78 | v.Validate(myClaims) 79 | ``` 80 | 81 | ### Supported Claim Types and Removal of `StandardClaims` 82 | 83 | The two standard claim types supported by this library, `MapClaims` and 84 | `RegisteredClaims` both implement the necessary functions of this interface. The 85 | old `StandardClaims` struct, which has already been deprecated in `v4` is now 86 | removed. 87 | 88 | Users using custom claims, in most cases, will not experience any changes in the 89 | behavior as long as they embedded `RegisteredClaims`. If they created a new 90 | claim type from scratch, they now need to implemented the proper getter 91 | functions. 92 | 93 | ### Migrating Application Specific Logic of the old `Valid` 94 | 95 | Previously, users could override the `Valid` method in a custom claim, for 96 | example to extend the validation with application-specific claims. However, this 97 | was always very dangerous, since once could easily disable the standard 98 | validation and signature checking. 99 | 100 | In order to avoid that, while still supporting the use-case, a new 101 | `ClaimsValidator` interface has been introduced. This interface consists of the 102 | `Validate() error` function. If the validator sees, that a `Claims` struct 103 | implements this interface, the errors returned to the `Validate` function will 104 | be *appended* to the regular standard validation. It is not possible to disable 105 | the standard validation anymore (even only by accident). 106 | 107 | Usage examples can be found in [example_test.go](./example_test.go), to build 108 | claims structs like the following. 109 | 110 | ```go 111 | // MyCustomClaims includes all registered claims, plus Foo. 112 | type MyCustomClaims struct { 113 | Foo string `json:"foo"` 114 | jwt.RegisteredClaims 115 | } 116 | 117 | // Validate can be used to execute additional application-specific claims 118 | // validation. 119 | func (m MyCustomClaims) Validate() error { 120 | if m.Foo != "bar" { 121 | return errors.New("must be foobar") 122 | } 123 | 124 | return nil 125 | } 126 | ``` 127 | 128 | ## Changes to the `Token` and `Parser` struct 129 | 130 | The previously global functions `DecodeSegment` and `EncodeSegment` were moved 131 | to the `Parser` and `Token` struct respectively. This will allow us in the 132 | future to configure the behavior of these two based on options supplied on the 133 | parser or the token (creation). This also removes two previously global 134 | variables and moves them to parser options `WithStrictDecoding` and 135 | `WithPaddingAllowed`. 136 | 137 | In order to do that, we had to adjust the way signing methods work. Previously 138 | they were given a base64 encoded signature in `Verify` and were expected to 139 | return a base64 encoded version of the signature in `Sign`, both as a `string`. 140 | However, this made it necessary to have `DecodeSegment` and `EncodeSegment` 141 | global and was a less than perfect design because we were repeating 142 | encoding/decoding steps for all signing methods. Now, `Sign` and `Verify` 143 | operate on a decoded signature as a `[]byte`, which feels more natural for a 144 | cryptographic operation anyway. Lastly, `Parse` and `SignedString` take care of 145 | the final encoding/decoding part. 146 | 147 | In addition to that, we also changed the `Signature` field on `Token` from a 148 | `string` to `[]byte` and this is also now populated with the decoded form. This 149 | is also more consistent, because the other parts of the JWT, mainly `Header` and 150 | `Claims` were already stored in decoded form in `Token`. Only the signature was 151 | stored in base64 encoded form, which was redundant with the information in the 152 | `Raw` field, which contains the complete token as base64. 153 | 154 | ```go 155 | type Token struct { 156 | Raw string // Raw contains the raw token 157 | Method SigningMethod // Method is the signing method used or to be used 158 | Header map[string]interface{} // Header is the first segment of the token in decoded form 159 | Claims Claims // Claims is the second segment of the token in decoded form 160 | Signature []byte // Signature is the third segment of the token in decoded form 161 | Valid bool // Valid specifies if the token is valid 162 | } 163 | ``` 164 | 165 | Most (if not all) of these changes should not impact the normal usage of this 166 | library. Only users directly accessing the `Signature` field as well as 167 | developers of custom signing methods should be affected. 168 | 169 | # Migration Guide (v4.0.0) 170 | 171 | Starting from [v4.0.0](https://github.com/golang-jwt/jwt/releases/tag/v4.0.0), 172 | the import path will be: 173 | 174 | "github.com/golang-jwt/jwt/v4" 175 | 176 | The `/v4` version will be backwards compatible with existing `v3.x.y` tags in 177 | this repo, as well as `github.com/dgrijalva/jwt-go`. For most users this should 178 | be a drop-in replacement, if you're having troubles migrating, please open an 179 | issue. 180 | 181 | You can replace all occurrences of `github.com/dgrijalva/jwt-go` or 182 | `github.com/golang-jwt/jwt` with `github.com/golang-jwt/jwt/v4`, either manually 183 | or by using tools such as `sed` or `gofmt`. 184 | 185 | And then you'd typically run: 186 | 187 | ``` 188 | go get github.com/golang-jwt/jwt/v4 189 | go mod tidy 190 | ``` 191 | 192 | # Older releases (before v3.2.0) 193 | 194 | The original migration guide for older releases can be found at 195 | https://github.com/dgrijalva/jwt-go/blob/master/MIGRATION_GUIDE.md. 196 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # jwt-go 2 | 3 | [![build](https://github.com/golang-jwt/jwt/actions/workflows/build.yml/badge.svg)](https://github.com/golang-jwt/jwt/actions/workflows/build.yml) 4 | [![Go 5 | Reference](https://pkg.go.dev/badge/github.com/golang-jwt/jwt/v5.svg)](https://pkg.go.dev/github.com/golang-jwt/jwt/v5) 6 | [![Coverage Status](https://coveralls.io/repos/github/golang-jwt/jwt/badge.svg?branch=main)](https://coveralls.io/github/golang-jwt/jwt?branch=main) 7 | 8 | A [go](http://www.golang.org) (or 'golang' for search engine friendliness) 9 | implementation of [JSON Web 10 | Tokens](https://datatracker.ietf.org/doc/html/rfc7519). 11 | 12 | Starting with [v4.0.0](https://github.com/golang-jwt/jwt/releases/tag/v4.0.0) 13 | this project adds Go module support, but maintains backward compatibility with 14 | older `v3.x.y` tags and upstream `github.com/dgrijalva/jwt-go`. See the 15 | [`MIGRATION_GUIDE.md`](./MIGRATION_GUIDE.md) for more information. Version 16 | v5.0.0 introduces major improvements to the validation of tokens, but is not 17 | entirely backward compatible. 18 | 19 | > After the original author of the library suggested migrating the maintenance 20 | > of `jwt-go`, a dedicated team of open source maintainers decided to clone the 21 | > existing library into this repository. See 22 | > [dgrijalva/jwt-go#462](https://github.com/dgrijalva/jwt-go/issues/462) for a 23 | > detailed discussion on this topic. 24 | 25 | 26 | **SECURITY NOTICE:** Some older versions of Go have a security issue in the 27 | crypto/elliptic. The recommendation is to upgrade to at least 1.15 See issue 28 | [dgrijalva/jwt-go#216](https://github.com/dgrijalva/jwt-go/issues/216) for more 29 | detail. 30 | 31 | **SECURITY NOTICE:** It's important that you [validate the `alg` presented is 32 | what you 33 | expect](https://auth0.com/blog/critical-vulnerabilities-in-json-web-token-libraries/). 34 | This library attempts to make it easy to do the right thing by requiring key 35 | types to match the expected alg, but you should take the extra step to verify it in 36 | your usage. See the examples provided. 37 | 38 | ### Supported Go versions 39 | 40 | Our support of Go versions is aligned with Go's [version release 41 | policy](https://golang.org/doc/devel/release#policy). So we will support a major 42 | version of Go until there are two newer major releases. We no longer support 43 | building jwt-go with unsupported Go versions, as these contain security 44 | vulnerabilities that will not be fixed. 45 | 46 | ## What the heck is a JWT? 47 | 48 | JWT.io has [a great introduction](https://jwt.io/introduction) to JSON Web 49 | Tokens. 50 | 51 | In short, it's a signed JSON object that does something useful (for example, 52 | authentication). It's commonly used for `Bearer` tokens in Oauth 2. A token is 53 | made of three parts, separated by `.`'s. The first two parts are JSON objects, 54 | that have been [base64url](https://datatracker.ietf.org/doc/html/rfc4648) 55 | encoded. The last part is the signature, encoded the same way. 56 | 57 | The first part is called the header. It contains the necessary information for 58 | verifying the last part, the signature. For example, which encryption method 59 | was used for signing and what key was used. 60 | 61 | The part in the middle is the interesting bit. It's called the Claims and 62 | contains the actual stuff you care about. Refer to [RFC 63 | 7519](https://datatracker.ietf.org/doc/html/rfc7519) for information about 64 | reserved keys and the proper way to add your own. 65 | 66 | ## What's in the box? 67 | 68 | This library supports the parsing and verification as well as the generation and 69 | signing of JWTs. Current supported signing algorithms are HMAC SHA, RSA, 70 | RSA-PSS, and ECDSA, though hooks are present for adding your own. 71 | 72 | ## Installation Guidelines 73 | 74 | 1. To install the jwt package, you first need to have 75 | [Go](https://go.dev/doc/install) installed, then you can use the command 76 | below to add `jwt-go` as a dependency in your Go program. 77 | 78 | ```sh 79 | go get -u github.com/golang-jwt/jwt/v5 80 | ``` 81 | 82 | 2. Import it in your code: 83 | 84 | ```go 85 | import "github.com/golang-jwt/jwt/v5" 86 | ``` 87 | 88 | ## Usage 89 | 90 | A detailed usage guide, including how to sign and verify tokens can be found on 91 | our [documentation website](https://golang-jwt.github.io/jwt/usage/create/). 92 | 93 | ## Examples 94 | 95 | See [the project documentation](https://pkg.go.dev/github.com/golang-jwt/jwt/v5) 96 | for examples of usage: 97 | 98 | * [Simple example of parsing and validating a 99 | token](https://pkg.go.dev/github.com/golang-jwt/jwt/v5#example-Parse-Hmac) 100 | * [Simple example of building and signing a 101 | token](https://pkg.go.dev/github.com/golang-jwt/jwt/v5#example-New-Hmac) 102 | * [Directory of 103 | Examples](https://pkg.go.dev/github.com/golang-jwt/jwt/v5#pkg-examples) 104 | 105 | ## Compliance 106 | 107 | This library was last reviewed to comply with [RFC 108 | 7519](https://datatracker.ietf.org/doc/html/rfc7519) dated May 2015 with a few 109 | notable differences: 110 | 111 | * In order to protect against accidental use of [Unsecured 112 | JWTs](https://datatracker.ietf.org/doc/html/rfc7519#section-6), tokens using 113 | `alg=none` will only be accepted if the constant 114 | `jwt.UnsafeAllowNoneSignatureType` is provided as the key. 115 | 116 | ## Project Status & Versioning 117 | 118 | This library is considered production ready. Feedback and feature requests are 119 | appreciated. The API should be considered stable. There should be very few 120 | backward-incompatible changes outside of major version updates (and only with 121 | good reason). 122 | 123 | This project uses [Semantic Versioning 2.0.0](http://semver.org). Accepted pull 124 | requests will land on `main`. Periodically, versions will be tagged from 125 | `main`. You can find all the releases on [the project releases 126 | page](https://github.com/golang-jwt/jwt/releases). 127 | 128 | **BREAKING CHANGES:** A full list of breaking changes is available in 129 | `VERSION_HISTORY.md`. See [`MIGRATION_GUIDE.md`](./MIGRATION_GUIDE.md) for more information on updating 130 | your code. 131 | 132 | ## Extensions 133 | 134 | This library publishes all the necessary components for adding your own signing 135 | methods or key functions. Simply implement the `SigningMethod` interface and 136 | register a factory method using `RegisterSigningMethod` or provide a 137 | `jwt.Keyfunc`. 138 | 139 | A common use case would be integrating with different 3rd party signature 140 | providers, like key management services from various cloud providers or Hardware 141 | Security Modules (HSMs) or to implement additional standards. 142 | 143 | | Extension | Purpose | Repo | 144 | | --------- | -------------------------------------------------------------------------------------------------------- | ------------------------------------------ | 145 | | GCP | Integrates with multiple Google Cloud Platform signing tools (AppEngine, IAM API, Cloud KMS) | https://github.com/someone1/gcp-jwt-go | 146 | | AWS | Integrates with AWS Key Management Service, KMS | https://github.com/matelang/jwt-go-aws-kms | 147 | | JWKS | Provides support for JWKS ([RFC 7517](https://datatracker.ietf.org/doc/html/rfc7517)) as a `jwt.Keyfunc` | https://github.com/MicahParks/keyfunc | 148 | 149 | *Disclaimer*: Unless otherwise specified, these integrations are maintained by 150 | third parties and should not be considered as a primary offer by any of the 151 | mentioned cloud providers 152 | 153 | ## More 154 | 155 | Go package documentation can be found [on 156 | pkg.go.dev](https://pkg.go.dev/github.com/golang-jwt/jwt/v5). Additional 157 | documentation can be found on [our project 158 | page](https://golang-jwt.github.io/jwt/). 159 | 160 | The command line utility included in this project (cmd/jwt) provides a 161 | straightforward example of token creation and parsing as well as a useful tool 162 | for debugging your own integration. You'll also find several implementation 163 | examples in the documentation. 164 | 165 | [golang-jwt](https://github.com/orgs/golang-jwt) incorporates a modified version 166 | of the JWT logo, which is distributed under the terms of the [MIT 167 | License](https://github.com/jsonwebtoken/jsonwebtoken.github.io/blob/master/LICENSE.txt). 168 | -------------------------------------------------------------------------------- /SECURITY.md: -------------------------------------------------------------------------------- 1 | # Security Policy 2 | 3 | ## Supported Versions 4 | 5 | As of November 2024 (and until this document is updated), the latest version `v5` is supported. In critical cases, we might supply back-ported patches for `v4`. 6 | 7 | ## Reporting a Vulnerability 8 | 9 | If you think you found a vulnerability, and even if you are not sure, please report it a [GitHub Security Advisory](https://github.com/golang-jwt/jwt/security/advisories/new). Please try be explicit, describe steps to reproduce the security issue with code example(s). 10 | 11 | You will receive a response within a timely manner. If the issue is confirmed, we will do our best to release a patch as soon as possible given the complexity of the problem. 12 | 13 | ## Public Discussions 14 | 15 | Please avoid publicly discussing a potential security vulnerability. 16 | 17 | Let's take this offline and find a solution first, this limits the potential impact as much as possible. 18 | 19 | We appreciate your help! 20 | -------------------------------------------------------------------------------- /VERSION_HISTORY.md: -------------------------------------------------------------------------------- 1 | # `jwt-go` Version History 2 | 3 | The following version history is kept for historic purposes. To retrieve the current changes of each version, please refer to the change-log of the specific release versions on https://github.com/golang-jwt/jwt/releases. 4 | 5 | ## 4.0.0 6 | 7 | * Introduces support for Go modules. The `v4` version will be backwards compatible with `v3.x.y`. 8 | 9 | ## 3.2.2 10 | 11 | * Starting from this release, we are adopting the policy to support the most 2 recent versions of Go currently available. By the time of this release, this is Go 1.15 and 1.16 ([#28](https://github.com/golang-jwt/jwt/pull/28)). 12 | * Fixed a potential issue that could occur when the verification of `exp`, `iat` or `nbf` was not required and contained invalid contents, i.e. non-numeric/date. Thanks for @thaJeztah for making us aware of that and @giorgos-f3 for originally reporting it to the formtech fork ([#40](https://github.com/golang-jwt/jwt/pull/40)). 13 | * Added support for EdDSA / ED25519 ([#36](https://github.com/golang-jwt/jwt/pull/36)). 14 | * Optimized allocations ([#33](https://github.com/golang-jwt/jwt/pull/33)). 15 | 16 | ## 3.2.1 17 | 18 | * **Import Path Change**: See MIGRATION_GUIDE.md for tips on updating your code 19 | * Changed the import path from `github.com/dgrijalva/jwt-go` to `github.com/golang-jwt/jwt` 20 | * Fixed type confusing issue between `string` and `[]string` in `VerifyAudience` ([#12](https://github.com/golang-jwt/jwt/pull/12)). This fixes CVE-2020-26160 21 | 22 | #### 3.2.0 23 | 24 | * Added method `ParseUnverified` to allow users to split up the tasks of parsing and validation 25 | * HMAC signing method returns `ErrInvalidKeyType` instead of `ErrInvalidKey` where appropriate 26 | * Added options to `request.ParseFromRequest`, which allows for an arbitrary list of modifiers to parsing behavior. Initial set include `WithClaims` and `WithParser`. Existing usage of this function will continue to work as before. 27 | * Deprecated `ParseFromRequestWithClaims` to simplify API in the future. 28 | 29 | #### 3.1.0 30 | 31 | * Improvements to `jwt` command line tool 32 | * Added `SkipClaimsValidation` option to `Parser` 33 | * Documentation updates 34 | 35 | #### 3.0.0 36 | 37 | * **Compatibility Breaking Changes**: See MIGRATION_GUIDE.md for tips on updating your code 38 | * Dropped support for `[]byte` keys when using RSA signing methods. This convenience feature could contribute to security vulnerabilities involving mismatched key types with signing methods. 39 | * `ParseFromRequest` has been moved to `request` subpackage and usage has changed 40 | * The `Claims` property on `Token` is now type `Claims` instead of `map[string]interface{}`. The default value is type `MapClaims`, which is an alias to `map[string]interface{}`. This makes it possible to use a custom type when decoding claims. 41 | * Other Additions and Changes 42 | * Added `Claims` interface type to allow users to decode the claims into a custom type 43 | * Added `ParseWithClaims`, which takes a third argument of type `Claims`. Use this function instead of `Parse` if you have a custom type you'd like to decode into. 44 | * Dramatically improved the functionality and flexibility of `ParseFromRequest`, which is now in the `request` subpackage 45 | * Added `ParseFromRequestWithClaims` which is the `FromRequest` equivalent of `ParseWithClaims` 46 | * Added new interface type `Extractor`, which is used for extracting JWT strings from http requests. Used with `ParseFromRequest` and `ParseFromRequestWithClaims`. 47 | * Added several new, more specific, validation errors to error type bitmask 48 | * Moved examples from README to executable example files 49 | * Signing method registry is now thread safe 50 | * Added new property to `ValidationError`, which contains the raw error returned by calls made by parse/verify (such as those returned by keyfunc or json parser) 51 | 52 | #### 2.7.0 53 | 54 | This will likely be the last backwards compatible release before 3.0.0, excluding essential bug fixes. 55 | 56 | * Added new option `-show` to the `jwt` command that will just output the decoded token without verifying 57 | * Error text for expired tokens includes how long it's been expired 58 | * Fixed incorrect error returned from `ParseRSAPublicKeyFromPEM` 59 | * Documentation updates 60 | 61 | #### 2.6.0 62 | 63 | * Exposed inner error within ValidationError 64 | * Fixed validation errors when using UseJSONNumber flag 65 | * Added several unit tests 66 | 67 | #### 2.5.0 68 | 69 | * Added support for signing method none. You shouldn't use this. The API tries to make this clear. 70 | * Updated/fixed some documentation 71 | * Added more helpful error message when trying to parse tokens that begin with `BEARER ` 72 | 73 | #### 2.4.0 74 | 75 | * Added new type, Parser, to allow for configuration of various parsing parameters 76 | * You can now specify a list of valid signing methods. Anything outside this set will be rejected. 77 | * You can now opt to use the `json.Number` type instead of `float64` when parsing token JSON 78 | * Added support for [Travis CI](https://travis-ci.org/dgrijalva/jwt-go) 79 | * Fixed some bugs with ECDSA parsing 80 | 81 | #### 2.3.0 82 | 83 | * Added support for ECDSA signing methods 84 | * Added support for RSA PSS signing methods (requires go v1.4) 85 | 86 | #### 2.2.0 87 | 88 | * Gracefully handle a `nil` `Keyfunc` being passed to `Parse`. Result will now be the parsed token and an error, instead of a panic. 89 | 90 | #### 2.1.0 91 | 92 | Backwards compatible API change that was missed in 2.0.0. 93 | 94 | * The `SignedString` method on `Token` now takes `interface{}` instead of `[]byte` 95 | 96 | #### 2.0.0 97 | 98 | There were two major reasons for breaking backwards compatibility with this update. The first was a refactor required to expand the width of the RSA and HMAC-SHA signing implementations. There will likely be no required code changes to support this change. 99 | 100 | The second update, while unfortunately requiring a small change in integration, is required to open up this library to other signing methods. Not all keys used for all signing methods have a single standard on-disk representation. Requiring `[]byte` as the type for all keys proved too limiting. Additionally, this implementation allows for pre-parsed tokens to be reused, which might matter in an application that parses a high volume of tokens with a small set of keys. Backwards compatibilty has been maintained for passing `[]byte` to the RSA signing methods, but they will also accept `*rsa.PublicKey` and `*rsa.PrivateKey`. 101 | 102 | It is likely the only integration change required here will be to change `func(t *jwt.Token) ([]byte, error)` to `func(t *jwt.Token) (interface{}, error)` when calling `Parse`. 103 | 104 | * **Compatibility Breaking Changes** 105 | * `SigningMethodHS256` is now `*SigningMethodHMAC` instead of `type struct` 106 | * `SigningMethodRS256` is now `*SigningMethodRSA` instead of `type struct` 107 | * `KeyFunc` now returns `interface{}` instead of `[]byte` 108 | * `SigningMethod.Sign` now takes `interface{}` instead of `[]byte` for the key 109 | * `SigningMethod.Verify` now takes `interface{}` instead of `[]byte` for the key 110 | * Renamed type `SigningMethodHS256` to `SigningMethodHMAC`. Specific sizes are now just instances of this type. 111 | * Added public package global `SigningMethodHS256` 112 | * Added public package global `SigningMethodHS384` 113 | * Added public package global `SigningMethodHS512` 114 | * Renamed type `SigningMethodRS256` to `SigningMethodRSA`. Specific sizes are now just instances of this type. 115 | * Added public package global `SigningMethodRS256` 116 | * Added public package global `SigningMethodRS384` 117 | * Added public package global `SigningMethodRS512` 118 | * Moved sample private key for HMAC tests from an inline value to a file on disk. Value is unchanged. 119 | * Refactored the RSA implementation to be easier to read 120 | * Exposed helper methods `ParseRSAPrivateKeyFromPEM` and `ParseRSAPublicKeyFromPEM` 121 | 122 | ## 1.0.2 123 | 124 | * Fixed bug in parsing public keys from certificates 125 | * Added more tests around the parsing of keys for RS256 126 | * Code refactoring in RS256 implementation. No functional changes 127 | 128 | ## 1.0.1 129 | 130 | * Fixed panic if RS256 signing method was passed an invalid key 131 | 132 | ## 1.0.0 133 | 134 | * First versioned release 135 | * API stabilized 136 | * Supports creating, signing, parsing, and validating JWT tokens 137 | * Supports RS256 and HS256 signing methods 138 | -------------------------------------------------------------------------------- /claims.go: -------------------------------------------------------------------------------- 1 | package jwt 2 | 3 | // Claims represent any form of a JWT Claims Set according to 4 | // https://datatracker.ietf.org/doc/html/rfc7519#section-4. In order to have a 5 | // common basis for validation, it is required that an implementation is able to 6 | // supply at least the claim names provided in 7 | // https://datatracker.ietf.org/doc/html/rfc7519#section-4.1 namely `exp`, 8 | // `iat`, `nbf`, `iss`, `sub` and `aud`. 9 | type Claims interface { 10 | GetExpirationTime() (*NumericDate, error) 11 | GetIssuedAt() (*NumericDate, error) 12 | GetNotBefore() (*NumericDate, error) 13 | GetIssuer() (string, error) 14 | GetSubject() (string, error) 15 | GetAudience() (ClaimStrings, error) 16 | } 17 | -------------------------------------------------------------------------------- /cmd/jwt/README.md: -------------------------------------------------------------------------------- 1 | `jwt` command-line tool 2 | ======================= 3 | 4 | This is a simple tool to sign, verify and show JSON Web Tokens from 5 | the command line. 6 | 7 | The following will create and sign a token, then verify it and output the original claims: 8 | 9 | echo {\"foo\":\"bar\"} | ./jwt -key ../../test/sample_key -alg RS256 -sign - | ./jwt -key ../../test/sample_key.pub -alg RS256 -verify - 10 | 11 | Key files should be in PEM format. Other formats are not supported by this tool. 12 | 13 | To simply display a token, use: 14 | 15 | echo $JWT | ./jwt -show - 16 | 17 | You can install this tool with the following command: 18 | 19 | go install github.com/golang-jwt/jwt/v5/cmd/jwt -------------------------------------------------------------------------------- /cmd/jwt/main.go: -------------------------------------------------------------------------------- 1 | // A useful example app. You can use this to debug your tokens on the command line. 2 | // This is also a great place to look at how you might use this library. 3 | // 4 | // Example usage: 5 | // The following will create and sign a token, then verify it and output the original claims. 6 | // 7 | // echo {\"foo\":\"bar\"} | bin/jwt -key test/sample_key -alg RS256 -sign - | bin/jwt -key test/sample_key.pub -verify - 8 | package main 9 | 10 | import ( 11 | "encoding/json" 12 | "flag" 13 | "fmt" 14 | "io" 15 | "os" 16 | "regexp" 17 | "sort" 18 | "strings" 19 | 20 | "github.com/golang-jwt/jwt/v5" 21 | ) 22 | 23 | var ( 24 | // Options 25 | flagAlg = flag.String("alg", "", algHelp()) 26 | flagKey = flag.String("key", "", "path to key file or '-' to read from stdin") 27 | flagCompact = flag.Bool("compact", false, "output compact JSON") 28 | flagDebug = flag.Bool("debug", false, "print out all kinds of debug data") 29 | flagClaims = make(ArgList) 30 | flagHead = make(ArgList) 31 | 32 | // Modes - exactly one of these is required 33 | flagSign = flag.String("sign", "", "path to claims file to sign, '-' to read from stdin, or '+' to use only -claim args") 34 | flagVerify = flag.String("verify", "", "path to JWT token file to verify or '-' to read from stdin") 35 | flagShow = flag.String("show", "", "path to JWT token file to show without verification or '-' to read from stdin") 36 | ) 37 | 38 | func main() { 39 | // Plug in Var flags 40 | flag.Var(flagClaims, "claim", "add additional claims. may be used more than once") 41 | flag.Var(flagHead, "header", "add additional header params. may be used more than once") 42 | 43 | // Usage message if you ask for -help or if you mess up inputs. 44 | flag.Usage = func() { 45 | fmt.Fprintf(os.Stderr, "Usage of %s:\n", os.Args[0]) 46 | fmt.Fprintf(os.Stderr, " One of the following flags is required: sign, verify or show\n") 47 | flag.PrintDefaults() 48 | } 49 | 50 | // Parse command line options 51 | flag.Parse() 52 | 53 | // Do the thing. If something goes wrong, print error to stderr 54 | // and exit with a non-zero status code 55 | if err := start(); err != nil { 56 | fmt.Fprintf(os.Stderr, "Error: %v\n", err) 57 | os.Exit(1) 58 | } 59 | } 60 | 61 | // Figure out which thing to do and then do that 62 | func start() error { 63 | switch { 64 | case *flagSign != "": 65 | return signToken() 66 | case *flagVerify != "": 67 | return verifyToken() 68 | case *flagShow != "": 69 | return showToken() 70 | default: 71 | flag.Usage() 72 | return fmt.Errorf("none of the required flags are present. What do you want me to do?") 73 | } 74 | } 75 | 76 | // Helper func: Read input from specified file or stdin 77 | func loadData(p string) ([]byte, error) { 78 | if p == "" { 79 | return nil, fmt.Errorf("no path specified") 80 | } 81 | 82 | var rdr io.Reader 83 | switch p { 84 | case "-": 85 | rdr = os.Stdin 86 | case "+": 87 | return []byte("{}"), nil 88 | default: 89 | f, err := os.Open(p) 90 | if err != nil { 91 | return nil, err 92 | } 93 | rdr = f 94 | if err := f.Close(); err != nil { 95 | return nil, err 96 | } 97 | } 98 | return io.ReadAll(rdr) 99 | } 100 | 101 | // Print a json object in accordance with the prophecy (or the command line options) 102 | func printJSON(j interface{}) error { 103 | var out []byte 104 | var err error 105 | 106 | if !*flagCompact { 107 | out, err = json.MarshalIndent(j, "", " ") 108 | } else { 109 | out, err = json.Marshal(j) 110 | } 111 | 112 | if err == nil { 113 | fmt.Println(string(out)) 114 | } 115 | 116 | return err 117 | } 118 | 119 | // Verify a token and output the claims. This is a great example 120 | // of how to verify and view a token. 121 | func verifyToken() error { 122 | // get the token 123 | tokData, err := loadData(*flagVerify) 124 | if err != nil { 125 | return fmt.Errorf("couldn't read token: %w", err) 126 | } 127 | 128 | // trim possible whitespace from token 129 | tokData = regexp.MustCompile(`\s*$`).ReplaceAll(tokData, []byte{}) 130 | if *flagDebug { 131 | fmt.Fprintf(os.Stderr, "Token len: %v bytes\n", len(tokData)) 132 | } 133 | 134 | // Parse the token. Load the key from command line option 135 | token, err := jwt.Parse(string(tokData), func(t *jwt.Token) (interface{}, error) { 136 | if isNone() { 137 | return jwt.UnsafeAllowNoneSignatureType, nil 138 | } 139 | data, err := loadData(*flagKey) 140 | if err != nil { 141 | return nil, err 142 | } 143 | switch { 144 | case isEs(): 145 | return jwt.ParseECPublicKeyFromPEM(data) 146 | case isRs(): 147 | return jwt.ParseRSAPublicKeyFromPEM(data) 148 | case isEd(): 149 | return jwt.ParseEdPublicKeyFromPEM(data) 150 | default: 151 | return data, nil 152 | } 153 | }) 154 | 155 | // Print an error if we can't parse for some reason 156 | if err != nil { 157 | return fmt.Errorf("couldn't parse token: %w", err) 158 | } 159 | 160 | // Print some debug data 161 | if *flagDebug { 162 | fmt.Fprintf(os.Stderr, "Header:\n%v\n", token.Header) 163 | fmt.Fprintf(os.Stderr, "Claims:\n%v\n", token.Claims) 164 | } 165 | 166 | // Print the token details 167 | if err := printJSON(token.Claims); err != nil { 168 | return fmt.Errorf("failed to output claims: %w", err) 169 | } 170 | 171 | return nil 172 | } 173 | 174 | // Create, sign, and output a token. This is a great, simple example of 175 | // how to use this library to create and sign a token. 176 | func signToken() error { 177 | // get the token data from command line arguments 178 | tokData, err := loadData(*flagSign) 179 | if err != nil { 180 | return fmt.Errorf("couldn't read token: %w", err) 181 | } else if *flagDebug { 182 | fmt.Fprintf(os.Stderr, "Token: %v bytes", len(tokData)) 183 | } 184 | 185 | // parse the JSON of the claims 186 | var claims jwt.MapClaims 187 | if err := json.Unmarshal(tokData, &claims); err != nil { 188 | return fmt.Errorf("couldn't parse claims JSON: %w", err) 189 | } 190 | 191 | // add command line claims 192 | if len(flagClaims) > 0 { 193 | for k, v := range flagClaims { 194 | claims[k] = v 195 | } 196 | } 197 | 198 | // get the key 199 | var key interface{} 200 | if isNone() { 201 | key = jwt.UnsafeAllowNoneSignatureType 202 | } else { 203 | key, err = loadData(*flagKey) 204 | if err != nil { 205 | return fmt.Errorf("couldn't read key: %w", err) 206 | } 207 | } 208 | 209 | // get the signing alg 210 | alg := jwt.GetSigningMethod(*flagAlg) 211 | if alg == nil { 212 | return fmt.Errorf("couldn't find signing method: %v", *flagAlg) 213 | } 214 | 215 | // create a new token 216 | token := jwt.NewWithClaims(alg, claims) 217 | 218 | // add command line headers 219 | if len(flagHead) > 0 { 220 | for k, v := range flagHead { 221 | token.Header[k] = v 222 | } 223 | } 224 | 225 | switch { 226 | case isEs(): 227 | k, ok := key.([]byte) 228 | if !ok { 229 | return fmt.Errorf("couldn't convert key data to key") 230 | } 231 | key, err = jwt.ParseECPrivateKeyFromPEM(k) 232 | if err != nil { 233 | return err 234 | } 235 | case isRs(): 236 | k, ok := key.([]byte) 237 | if !ok { 238 | return fmt.Errorf("couldn't convert key data to key") 239 | } 240 | key, err = jwt.ParseRSAPrivateKeyFromPEM(k) 241 | if err != nil { 242 | return err 243 | } 244 | case isEd(): 245 | k, ok := key.([]byte) 246 | if !ok { 247 | return fmt.Errorf("couldn't convert key data to key") 248 | } 249 | key, err = jwt.ParseEdPrivateKeyFromPEM(k) 250 | if err != nil { 251 | return err 252 | } 253 | } 254 | 255 | out, err := token.SignedString(key) 256 | if err != nil { 257 | return fmt.Errorf("error signing token: %w", err) 258 | } 259 | fmt.Println(out) 260 | 261 | return nil 262 | } 263 | 264 | // showToken pretty-prints the token on the command line. 265 | func showToken() error { 266 | // get the token 267 | tokData, err := loadData(*flagShow) 268 | if err != nil { 269 | return fmt.Errorf("couldn't read token: %w", err) 270 | } 271 | 272 | // trim possible whitespace from token 273 | tokData = regexp.MustCompile(`\s*$`).ReplaceAll(tokData, []byte{}) 274 | if *flagDebug { 275 | fmt.Fprintf(os.Stderr, "Token len: %v bytes\n", len(tokData)) 276 | } 277 | 278 | token, _, err := jwt.NewParser().ParseUnverified(string(tokData), make(jwt.MapClaims)) 279 | if err != nil { 280 | return fmt.Errorf("malformed token: %w", err) 281 | } 282 | 283 | // Print the token details 284 | fmt.Println("Header:") 285 | if err := printJSON(token.Header); err != nil { 286 | return fmt.Errorf("failed to output header: %w", err) 287 | } 288 | 289 | fmt.Println("Claims:") 290 | if err := printJSON(token.Claims); err != nil { 291 | return fmt.Errorf("failed to output claims: %w", err) 292 | } 293 | 294 | return nil 295 | } 296 | 297 | func isEs() bool { 298 | return strings.HasPrefix(*flagAlg, "ES") 299 | } 300 | 301 | func isRs() bool { 302 | return strings.HasPrefix(*flagAlg, "RS") || strings.HasPrefix(*flagAlg, "PS") 303 | } 304 | 305 | func isEd() bool { 306 | return *flagAlg == "EdDSA" 307 | } 308 | 309 | func isNone() bool { 310 | return *flagAlg == "none" 311 | } 312 | 313 | func algHelp() string { 314 | algs := jwt.GetAlgorithms() 315 | sort.Strings(algs) 316 | 317 | var b strings.Builder 318 | b.WriteString("signing algorithm identifier, one of\n") 319 | for i, alg := range algs { 320 | if i > 0 { 321 | if i%7 == 0 { 322 | b.WriteString(",\n") 323 | } else { 324 | b.WriteString(", ") 325 | } 326 | } 327 | b.WriteString(alg) 328 | } 329 | return b.String() 330 | } 331 | 332 | type ArgList map[string]string 333 | 334 | func (l ArgList) String() string { 335 | data, _ := json.Marshal(l) 336 | return string(data) 337 | } 338 | 339 | func (l ArgList) Set(arg string) error { 340 | parts := strings.SplitN(arg, "=", 2) 341 | if len(parts) != 2 { 342 | return fmt.Errorf("invalid argument '%v'. Must use format 'key=value'. %v", arg, parts) 343 | } 344 | l[parts[0]] = parts[1] 345 | return nil 346 | } 347 | -------------------------------------------------------------------------------- /doc.go: -------------------------------------------------------------------------------- 1 | // Package jwt is a Go implementation of JSON Web Tokens: http://self-issued.info/docs/draft-jones-json-web-token.html 2 | // 3 | // See README.md for more info. 4 | package jwt 5 | -------------------------------------------------------------------------------- /ecdsa.go: -------------------------------------------------------------------------------- 1 | package jwt 2 | 3 | import ( 4 | "crypto" 5 | "crypto/ecdsa" 6 | "crypto/rand" 7 | "errors" 8 | "math/big" 9 | ) 10 | 11 | var ( 12 | // Sadly this is missing from crypto/ecdsa compared to crypto/rsa 13 | ErrECDSAVerification = errors.New("crypto/ecdsa: verification error") 14 | ) 15 | 16 | // SigningMethodECDSA implements the ECDSA family of signing methods. 17 | // Expects *ecdsa.PrivateKey for signing and *ecdsa.PublicKey for verification 18 | type SigningMethodECDSA struct { 19 | Name string 20 | Hash crypto.Hash 21 | KeySize int 22 | CurveBits int 23 | } 24 | 25 | // Specific instances for EC256 and company 26 | var ( 27 | SigningMethodES256 *SigningMethodECDSA 28 | SigningMethodES384 *SigningMethodECDSA 29 | SigningMethodES512 *SigningMethodECDSA 30 | ) 31 | 32 | func init() { 33 | // ES256 34 | SigningMethodES256 = &SigningMethodECDSA{"ES256", crypto.SHA256, 32, 256} 35 | RegisterSigningMethod(SigningMethodES256.Alg(), func() SigningMethod { 36 | return SigningMethodES256 37 | }) 38 | 39 | // ES384 40 | SigningMethodES384 = &SigningMethodECDSA{"ES384", crypto.SHA384, 48, 384} 41 | RegisterSigningMethod(SigningMethodES384.Alg(), func() SigningMethod { 42 | return SigningMethodES384 43 | }) 44 | 45 | // ES512 46 | SigningMethodES512 = &SigningMethodECDSA{"ES512", crypto.SHA512, 66, 521} 47 | RegisterSigningMethod(SigningMethodES512.Alg(), func() SigningMethod { 48 | return SigningMethodES512 49 | }) 50 | } 51 | 52 | func (m *SigningMethodECDSA) Alg() string { 53 | return m.Name 54 | } 55 | 56 | // Verify implements token verification for the SigningMethod. 57 | // For this verify method, key must be an ecdsa.PublicKey struct 58 | func (m *SigningMethodECDSA) Verify(signingString string, sig []byte, key interface{}) error { 59 | // Get the key 60 | var ecdsaKey *ecdsa.PublicKey 61 | switch k := key.(type) { 62 | case *ecdsa.PublicKey: 63 | ecdsaKey = k 64 | default: 65 | return newError("ECDSA verify expects *ecdsa.PublicKey", ErrInvalidKeyType) 66 | } 67 | 68 | if len(sig) != 2*m.KeySize { 69 | return ErrECDSAVerification 70 | } 71 | 72 | r := big.NewInt(0).SetBytes(sig[:m.KeySize]) 73 | s := big.NewInt(0).SetBytes(sig[m.KeySize:]) 74 | 75 | // Create hasher 76 | if !m.Hash.Available() { 77 | return ErrHashUnavailable 78 | } 79 | hasher := m.Hash.New() 80 | hasher.Write([]byte(signingString)) 81 | 82 | // Verify the signature 83 | if verifystatus := ecdsa.Verify(ecdsaKey, hasher.Sum(nil), r, s); verifystatus { 84 | return nil 85 | } 86 | 87 | return ErrECDSAVerification 88 | } 89 | 90 | // Sign implements token signing for the SigningMethod. 91 | // For this signing method, key must be an ecdsa.PrivateKey struct 92 | func (m *SigningMethodECDSA) Sign(signingString string, key interface{}) ([]byte, error) { 93 | // Get the key 94 | var ecdsaKey *ecdsa.PrivateKey 95 | switch k := key.(type) { 96 | case *ecdsa.PrivateKey: 97 | ecdsaKey = k 98 | default: 99 | return nil, newError("ECDSA sign expects *ecdsa.PrivateKey", ErrInvalidKeyType) 100 | } 101 | 102 | // Create the hasher 103 | if !m.Hash.Available() { 104 | return nil, ErrHashUnavailable 105 | } 106 | 107 | hasher := m.Hash.New() 108 | hasher.Write([]byte(signingString)) 109 | 110 | // Sign the string and return r, s 111 | if r, s, err := ecdsa.Sign(rand.Reader, ecdsaKey, hasher.Sum(nil)); err == nil { 112 | curveBits := ecdsaKey.Curve.Params().BitSize 113 | 114 | if m.CurveBits != curveBits { 115 | return nil, ErrInvalidKey 116 | } 117 | 118 | keyBytes := curveBits / 8 119 | if curveBits%8 > 0 { 120 | keyBytes += 1 121 | } 122 | 123 | // We serialize the outputs (r and s) into big-endian byte arrays 124 | // padded with zeros on the left to make sure the sizes work out. 125 | // Output must be 2*keyBytes long. 126 | out := make([]byte, 2*keyBytes) 127 | r.FillBytes(out[0:keyBytes]) // r is assigned to the first half of output. 128 | s.FillBytes(out[keyBytes:]) // s is assigned to the second half of output. 129 | 130 | return out, nil 131 | } else { 132 | return nil, err 133 | } 134 | } 135 | -------------------------------------------------------------------------------- /ecdsa_test.go: -------------------------------------------------------------------------------- 1 | package jwt_test 2 | 3 | import ( 4 | "crypto/ecdsa" 5 | "os" 6 | "reflect" 7 | "strings" 8 | "testing" 9 | 10 | "github.com/golang-jwt/jwt/v5" 11 | ) 12 | 13 | var ecdsaTestData = []struct { 14 | name string 15 | keys map[string]string 16 | tokenString string 17 | alg string 18 | claims map[string]interface{} 19 | valid bool 20 | }{ 21 | { 22 | "Basic ES256", 23 | map[string]string{"private": "test/ec256-private.pem", "public": "test/ec256-public.pem"}, 24 | "eyJ0eXAiOiJKV1QiLCJhbGciOiJFUzI1NiJ9.eyJmb28iOiJiYXIifQ.feG39E-bn8HXAKhzDZq7yEAPWYDhZlwTn3sePJnU9VrGMmwdXAIEyoOnrjreYlVM_Z4N13eK9-TmMTWyfKJtHQ", 25 | "ES256", 26 | map[string]interface{}{"foo": "bar"}, 27 | true, 28 | }, 29 | { 30 | "Basic ES384", 31 | map[string]string{"private": "test/ec384-private.pem", "public": "test/ec384-public.pem"}, 32 | "eyJ0eXAiOiJKV1QiLCJhbGciOiJFUzM4NCJ9.eyJmb28iOiJiYXIifQ.ngAfKMbJUh0WWubSIYe5GMsA-aHNKwFbJk_wq3lq23aPp8H2anb1rRILIzVR0gUf4a8WzDtrzmiikuPWyCS6CN4-PwdgTk-5nehC7JXqlaBZU05p3toM3nWCwm_LXcld", 33 | "ES384", 34 | map[string]interface{}{"foo": "bar"}, 35 | true, 36 | }, 37 | { 38 | "Basic ES512", 39 | map[string]string{"private": "test/ec512-private.pem", "public": "test/ec512-public.pem"}, 40 | "eyJ0eXAiOiJKV1QiLCJhbGciOiJFUzUxMiJ9.eyJmb28iOiJiYXIifQ.AAU0TvGQOcdg2OvrwY73NHKgfk26UDekh9Prz-L_iWuTBIBqOFCWwwLsRiHB1JOddfKAls5do1W0jR_F30JpVd-6AJeTjGKA4C1A1H6gIKwRY0o_tFDIydZCl_lMBMeG5VNFAjO86-WCSKwc3hqaGkq1MugPRq_qrF9AVbuEB4JPLyL5", 41 | "ES512", 42 | map[string]interface{}{"foo": "bar"}, 43 | true, 44 | }, 45 | { 46 | "basic ES256 invalid: foo => bar", 47 | map[string]string{"private": "test/ec256-private.pem", "public": "test/ec256-public.pem"}, 48 | "eyJhbGciOiJFUzI1NiIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIifQ.MEQCIHoSJnmGlPaVQDqacx_2XlXEhhqtWceVopjomc2PJLtdAiAUTeGPoNYxZw0z8mgOnnIcjoxRuNDVZvybRZF3wR1l8W", 49 | "ES256", 50 | map[string]interface{}{"foo": "bar"}, 51 | false, 52 | }, 53 | } 54 | 55 | func TestECDSAVerify(t *testing.T) { 56 | for _, data := range ecdsaTestData { 57 | var err error 58 | 59 | key, _ := os.ReadFile(data.keys["public"]) 60 | 61 | var ecdsaKey *ecdsa.PublicKey 62 | if ecdsaKey, err = jwt.ParseECPublicKeyFromPEM(key); err != nil { 63 | t.Errorf("Unable to parse ECDSA public key: %v", err) 64 | } 65 | 66 | parts := strings.Split(data.tokenString, ".") 67 | 68 | method := jwt.GetSigningMethod(data.alg) 69 | err = method.Verify(strings.Join(parts[0:2], "."), decodeSegment(t, parts[2]), ecdsaKey) 70 | if data.valid && err != nil { 71 | t.Errorf("[%v] Error while verifying key: %v", data.name, err) 72 | } 73 | if !data.valid && err == nil { 74 | t.Errorf("[%v] Invalid key passed validation", data.name) 75 | } 76 | } 77 | } 78 | 79 | func TestECDSASign(t *testing.T) { 80 | for _, data := range ecdsaTestData { 81 | var err error 82 | key, _ := os.ReadFile(data.keys["private"]) 83 | 84 | var ecdsaKey *ecdsa.PrivateKey 85 | if ecdsaKey, err = jwt.ParseECPrivateKeyFromPEM(key); err != nil { 86 | t.Errorf("Unable to parse ECDSA private key: %v", err) 87 | } 88 | 89 | if data.valid { 90 | parts := strings.Split(data.tokenString, ".") 91 | toSign := strings.Join(parts[0:2], ".") 92 | method := jwt.GetSigningMethod(data.alg) 93 | sig, err := method.Sign(toSign, ecdsaKey) 94 | if err != nil { 95 | t.Errorf("[%v] Error signing token: %v", data.name, err) 96 | } 97 | 98 | ssig := encodeSegment(sig) 99 | if ssig == parts[2] { 100 | t.Errorf("[%v] Identical signatures\nbefore:\n%v\nafter:\n%v", data.name, parts[2], ssig) 101 | } 102 | 103 | err = method.Verify(toSign, sig, ecdsaKey.Public()) 104 | if err != nil { 105 | t.Errorf("[%v] Sign produced an invalid signature: %v", data.name, err) 106 | } 107 | } 108 | } 109 | } 110 | 111 | func BenchmarkECDSAParsing(b *testing.B) { 112 | for _, data := range ecdsaTestData { 113 | key, _ := os.ReadFile(data.keys["private"]) 114 | 115 | b.Run(data.name, func(b *testing.B) { 116 | b.ReportAllocs() 117 | b.ResetTimer() 118 | b.RunParallel(func(pb *testing.PB) { 119 | for pb.Next() { 120 | if _, err := jwt.ParseECPrivateKeyFromPEM(key); err != nil { 121 | b.Fatalf("Unable to parse ECDSA private key: %v", err) 122 | } 123 | } 124 | }) 125 | }) 126 | } 127 | } 128 | 129 | func BenchmarkECDSASigning(b *testing.B) { 130 | for _, data := range ecdsaTestData { 131 | key, _ := os.ReadFile(data.keys["private"]) 132 | 133 | ecdsaKey, err := jwt.ParseECPrivateKeyFromPEM(key) 134 | if err != nil { 135 | b.Fatalf("Unable to parse ECDSA private key: %v", err) 136 | } 137 | 138 | method := jwt.GetSigningMethod(data.alg) 139 | 140 | b.Run(data.name, func(b *testing.B) { 141 | benchmarkSigning(b, method, ecdsaKey) 142 | }) 143 | 144 | // Directly call method.Sign without the decoration of *Token. 145 | b.Run(data.name+"/sign-only", func(b *testing.B) { 146 | if !data.valid { 147 | b.Skipf("Skipping because data is not valid") 148 | } 149 | 150 | parts := strings.Split(data.tokenString, ".") 151 | toSign := strings.Join(parts[0:2], ".") 152 | 153 | b.ReportAllocs() 154 | b.ResetTimer() 155 | for i := 0; i < b.N; i++ { 156 | sig, err := method.Sign(toSign, ecdsaKey) 157 | if err != nil { 158 | b.Fatalf("[%v] Error signing token: %v", data.name, err) 159 | } 160 | if reflect.DeepEqual(sig, decodeSegment(b, parts[2])) { 161 | b.Fatalf("[%v] Identical signatures\nbefore:\n%v\nafter:\n%v", data.name, parts[2], sig) 162 | } 163 | } 164 | }) 165 | } 166 | } 167 | 168 | func decodeSegment(t interface{ Fatalf(string, ...any) }, signature string) (sig []byte) { 169 | var err error 170 | sig, err = jwt.NewParser().DecodeSegment(signature) 171 | if err != nil { 172 | t.Fatalf("could not decode segment: %v", err) 173 | } 174 | 175 | return 176 | } 177 | 178 | func encodeSegment(sig []byte) string { 179 | return (&jwt.Token{}).EncodeSegment(sig) 180 | } 181 | -------------------------------------------------------------------------------- /ecdsa_utils.go: -------------------------------------------------------------------------------- 1 | package jwt 2 | 3 | import ( 4 | "crypto/ecdsa" 5 | "crypto/x509" 6 | "encoding/pem" 7 | "errors" 8 | ) 9 | 10 | var ( 11 | ErrNotECPublicKey = errors.New("key is not a valid ECDSA public key") 12 | ErrNotECPrivateKey = errors.New("key is not a valid ECDSA private key") 13 | ) 14 | 15 | // ParseECPrivateKeyFromPEM parses a PEM encoded Elliptic Curve Private Key Structure 16 | func ParseECPrivateKeyFromPEM(key []byte) (*ecdsa.PrivateKey, error) { 17 | var err error 18 | 19 | // Parse PEM block 20 | var block *pem.Block 21 | if block, _ = pem.Decode(key); block == nil { 22 | return nil, ErrKeyMustBePEMEncoded 23 | } 24 | 25 | // Parse the key 26 | var parsedKey interface{} 27 | if parsedKey, err = x509.ParseECPrivateKey(block.Bytes); err != nil { 28 | if parsedKey, err = x509.ParsePKCS8PrivateKey(block.Bytes); err != nil { 29 | return nil, err 30 | } 31 | } 32 | 33 | var pkey *ecdsa.PrivateKey 34 | var ok bool 35 | if pkey, ok = parsedKey.(*ecdsa.PrivateKey); !ok { 36 | return nil, ErrNotECPrivateKey 37 | } 38 | 39 | return pkey, nil 40 | } 41 | 42 | // ParseECPublicKeyFromPEM parses a PEM encoded PKCS1 or PKCS8 public key 43 | func ParseECPublicKeyFromPEM(key []byte) (*ecdsa.PublicKey, error) { 44 | var err error 45 | 46 | // Parse PEM block 47 | var block *pem.Block 48 | if block, _ = pem.Decode(key); block == nil { 49 | return nil, ErrKeyMustBePEMEncoded 50 | } 51 | 52 | // Parse the key 53 | var parsedKey interface{} 54 | if parsedKey, err = x509.ParsePKIXPublicKey(block.Bytes); err != nil { 55 | if cert, err := x509.ParseCertificate(block.Bytes); err == nil { 56 | parsedKey = cert.PublicKey 57 | } else { 58 | return nil, err 59 | } 60 | } 61 | 62 | var pkey *ecdsa.PublicKey 63 | var ok bool 64 | if pkey, ok = parsedKey.(*ecdsa.PublicKey); !ok { 65 | return nil, ErrNotECPublicKey 66 | } 67 | 68 | return pkey, nil 69 | } 70 | -------------------------------------------------------------------------------- /ed25519.go: -------------------------------------------------------------------------------- 1 | package jwt 2 | 3 | import ( 4 | "crypto" 5 | "crypto/ed25519" 6 | "crypto/rand" 7 | "errors" 8 | ) 9 | 10 | var ( 11 | ErrEd25519Verification = errors.New("ed25519: verification error") 12 | ) 13 | 14 | // SigningMethodEd25519 implements the EdDSA family. 15 | // Expects ed25519.PrivateKey for signing and ed25519.PublicKey for verification 16 | type SigningMethodEd25519 struct{} 17 | 18 | // Specific instance for EdDSA 19 | var ( 20 | SigningMethodEdDSA *SigningMethodEd25519 21 | ) 22 | 23 | func init() { 24 | SigningMethodEdDSA = &SigningMethodEd25519{} 25 | RegisterSigningMethod(SigningMethodEdDSA.Alg(), func() SigningMethod { 26 | return SigningMethodEdDSA 27 | }) 28 | } 29 | 30 | func (m *SigningMethodEd25519) Alg() string { 31 | return "EdDSA" 32 | } 33 | 34 | // Verify implements token verification for the SigningMethod. 35 | // For this verify method, key must be an ed25519.PublicKey 36 | func (m *SigningMethodEd25519) Verify(signingString string, sig []byte, key interface{}) error { 37 | var ed25519Key ed25519.PublicKey 38 | var ok bool 39 | 40 | if ed25519Key, ok = key.(ed25519.PublicKey); !ok { 41 | return newError("Ed25519 verify expects ed25519.PublicKey", ErrInvalidKeyType) 42 | } 43 | 44 | if len(ed25519Key) != ed25519.PublicKeySize { 45 | return ErrInvalidKey 46 | } 47 | 48 | // Verify the signature 49 | if !ed25519.Verify(ed25519Key, []byte(signingString), sig) { 50 | return ErrEd25519Verification 51 | } 52 | 53 | return nil 54 | } 55 | 56 | // Sign implements token signing for the SigningMethod. 57 | // For this signing method, key must be an ed25519.PrivateKey 58 | func (m *SigningMethodEd25519) Sign(signingString string, key interface{}) ([]byte, error) { 59 | var ed25519Key crypto.Signer 60 | var ok bool 61 | 62 | if ed25519Key, ok = key.(crypto.Signer); !ok { 63 | return nil, newError("Ed25519 sign expects crypto.Signer", ErrInvalidKeyType) 64 | } 65 | 66 | if _, ok := ed25519Key.Public().(ed25519.PublicKey); !ok { 67 | return nil, ErrInvalidKey 68 | } 69 | 70 | // Sign the string and return the result. ed25519 performs a two-pass hash 71 | // as part of its algorithm. Therefore, we need to pass a non-prehashed 72 | // message into the Sign function, as indicated by crypto.Hash(0) 73 | sig, err := ed25519Key.Sign(rand.Reader, []byte(signingString), crypto.Hash(0)) 74 | if err != nil { 75 | return nil, err 76 | } 77 | 78 | return sig, nil 79 | } 80 | -------------------------------------------------------------------------------- /ed25519_test.go: -------------------------------------------------------------------------------- 1 | package jwt_test 2 | 3 | import ( 4 | "os" 5 | "strings" 6 | "testing" 7 | 8 | "github.com/golang-jwt/jwt/v5" 9 | ) 10 | 11 | var ed25519TestData = []struct { 12 | name string 13 | keys map[string]string 14 | tokenString string 15 | alg string 16 | claims map[string]interface{} 17 | valid bool 18 | }{ 19 | { 20 | "Basic Ed25519", 21 | map[string]string{"private": "test/ed25519-private.pem", "public": "test/ed25519-public.pem"}, 22 | "eyJhbGciOiJFRDI1NTE5IiwidHlwIjoiSldUIn0.eyJmb28iOiJiYXIifQ.ESuVzZq1cECrt9Od_gLPVG-_6uRP_8Nq-ajx6CtmlDqRJZqdejro2ilkqaQgSL-siE_3JMTUW7UwAorLaTyFCw", 23 | "EdDSA", 24 | map[string]interface{}{"foo": "bar"}, 25 | true, 26 | }, 27 | { 28 | "Basic Ed25519", 29 | map[string]string{"private": "test/ed25519-private.pem", "public": "test/ed25519-public.pem"}, 30 | "eyJhbGciOiJFRDI1NTE5IiwidHlwIjoiSldUIn0.eyJmb28iOiJiYXoifQ.ESuVzZq1cECrt9Od_gLPVG-_6uRP_8Nq-ajx6CtmlDqRJZqdejro2ilkqaQgSL-siE_3JMTUW7UwAorLaTyFCw", 31 | "EdDSA", 32 | map[string]interface{}{"foo": "bar"}, 33 | false, 34 | }, 35 | } 36 | 37 | func TestEd25519Verify(t *testing.T) { 38 | for _, data := range ed25519TestData { 39 | var err error 40 | 41 | key, _ := os.ReadFile(data.keys["public"]) 42 | 43 | ed25519Key, err := jwt.ParseEdPublicKeyFromPEM(key) 44 | if err != nil { 45 | t.Errorf("Unable to parse Ed25519 public key: %v", err) 46 | } 47 | 48 | parts := strings.Split(data.tokenString, ".") 49 | 50 | method := jwt.GetSigningMethod(data.alg) 51 | 52 | err = method.Verify(strings.Join(parts[0:2], "."), decodeSegment(t, parts[2]), ed25519Key) 53 | if data.valid && err != nil { 54 | t.Errorf("[%v] Error while verifying key: %v", data.name, err) 55 | } 56 | if !data.valid && err == nil { 57 | t.Errorf("[%v] Invalid key passed validation", data.name) 58 | } 59 | } 60 | } 61 | 62 | func TestEd25519Sign(t *testing.T) { 63 | for _, data := range ed25519TestData { 64 | var err error 65 | key, _ := os.ReadFile(data.keys["private"]) 66 | 67 | ed25519Key, err := jwt.ParseEdPrivateKeyFromPEM(key) 68 | if err != nil { 69 | t.Errorf("Unable to parse Ed25519 private key: %v", err) 70 | } 71 | 72 | parts := strings.Split(data.tokenString, ".") 73 | 74 | method := jwt.GetSigningMethod(data.alg) 75 | 76 | sig, err := method.Sign(strings.Join(parts[0:2], "."), ed25519Key) 77 | if err != nil { 78 | t.Errorf("[%v] Error signing token: %v", data.name, err) 79 | } 80 | 81 | ssig := encodeSegment(sig) 82 | if ssig == parts[2] && !data.valid { 83 | t.Errorf("[%v] Identical signatures\nbefore:\n%v\nafter:\n%v", data.name, parts[2], ssig) 84 | } 85 | } 86 | } 87 | -------------------------------------------------------------------------------- /ed25519_utils.go: -------------------------------------------------------------------------------- 1 | package jwt 2 | 3 | import ( 4 | "crypto" 5 | "crypto/ed25519" 6 | "crypto/x509" 7 | "encoding/pem" 8 | "errors" 9 | ) 10 | 11 | var ( 12 | ErrNotEdPrivateKey = errors.New("key is not a valid Ed25519 private key") 13 | ErrNotEdPublicKey = errors.New("key is not a valid Ed25519 public key") 14 | ) 15 | 16 | // ParseEdPrivateKeyFromPEM parses a PEM-encoded Edwards curve private key 17 | func ParseEdPrivateKeyFromPEM(key []byte) (crypto.PrivateKey, error) { 18 | var err error 19 | 20 | // Parse PEM block 21 | var block *pem.Block 22 | if block, _ = pem.Decode(key); block == nil { 23 | return nil, ErrKeyMustBePEMEncoded 24 | } 25 | 26 | // Parse the key 27 | var parsedKey interface{} 28 | if parsedKey, err = x509.ParsePKCS8PrivateKey(block.Bytes); err != nil { 29 | return nil, err 30 | } 31 | 32 | var pkey ed25519.PrivateKey 33 | var ok bool 34 | if pkey, ok = parsedKey.(ed25519.PrivateKey); !ok { 35 | return nil, ErrNotEdPrivateKey 36 | } 37 | 38 | return pkey, nil 39 | } 40 | 41 | // ParseEdPublicKeyFromPEM parses a PEM-encoded Edwards curve public key 42 | func ParseEdPublicKeyFromPEM(key []byte) (crypto.PublicKey, error) { 43 | var err error 44 | 45 | // Parse PEM block 46 | var block *pem.Block 47 | if block, _ = pem.Decode(key); block == nil { 48 | return nil, ErrKeyMustBePEMEncoded 49 | } 50 | 51 | // Parse the key 52 | var parsedKey interface{} 53 | if parsedKey, err = x509.ParsePKIXPublicKey(block.Bytes); err != nil { 54 | return nil, err 55 | } 56 | 57 | var pkey ed25519.PublicKey 58 | var ok bool 59 | if pkey, ok = parsedKey.(ed25519.PublicKey); !ok { 60 | return nil, ErrNotEdPublicKey 61 | } 62 | 63 | return pkey, nil 64 | } 65 | -------------------------------------------------------------------------------- /errors.go: -------------------------------------------------------------------------------- 1 | package jwt 2 | 3 | import ( 4 | "errors" 5 | "strings" 6 | ) 7 | 8 | var ( 9 | ErrInvalidKey = errors.New("key is invalid") 10 | ErrInvalidKeyType = errors.New("key is of invalid type") 11 | ErrHashUnavailable = errors.New("the requested hash function is unavailable") 12 | ErrTokenMalformed = errors.New("token is malformed") 13 | ErrTokenUnverifiable = errors.New("token is unverifiable") 14 | ErrTokenSignatureInvalid = errors.New("token signature is invalid") 15 | ErrTokenRequiredClaimMissing = errors.New("token is missing required claim") 16 | ErrTokenInvalidAudience = errors.New("token has invalid audience") 17 | ErrTokenExpired = errors.New("token is expired") 18 | ErrTokenUsedBeforeIssued = errors.New("token used before issued") 19 | ErrTokenInvalidIssuer = errors.New("token has invalid issuer") 20 | ErrTokenInvalidSubject = errors.New("token has invalid subject") 21 | ErrTokenNotValidYet = errors.New("token is not valid yet") 22 | ErrTokenInvalidId = errors.New("token has invalid id") 23 | ErrTokenInvalidClaims = errors.New("token has invalid claims") 24 | ErrInvalidType = errors.New("invalid type for claim") 25 | ) 26 | 27 | // joinedError is an error type that works similar to what [errors.Join] 28 | // produces, with the exception that it has a nice error string; mainly its 29 | // error messages are concatenated using a comma, rather than a newline. 30 | type joinedError struct { 31 | errs []error 32 | } 33 | 34 | func (je joinedError) Error() string { 35 | msg := []string{} 36 | for _, err := range je.errs { 37 | msg = append(msg, err.Error()) 38 | } 39 | 40 | return strings.Join(msg, ", ") 41 | } 42 | 43 | // joinErrors joins together multiple errors. Useful for scenarios where 44 | // multiple errors next to each other occur, e.g., in claims validation. 45 | func joinErrors(errs ...error) error { 46 | return &joinedError{ 47 | errs: errs, 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /errors_go1_20.go: -------------------------------------------------------------------------------- 1 | //go:build go1.20 2 | // +build go1.20 3 | 4 | package jwt 5 | 6 | import ( 7 | "fmt" 8 | ) 9 | 10 | // Unwrap implements the multiple error unwrapping for this error type, which is 11 | // possible in Go 1.20. 12 | func (je joinedError) Unwrap() []error { 13 | return je.errs 14 | } 15 | 16 | // newError creates a new error message with a detailed error message. The 17 | // message will be prefixed with the contents of the supplied error type. 18 | // Additionally, more errors, that provide more context can be supplied which 19 | // will be appended to the message. This makes use of Go 1.20's possibility to 20 | // include more than one %w formatting directive in [fmt.Errorf]. 21 | // 22 | // For example, 23 | // 24 | // newError("no keyfunc was provided", ErrTokenUnverifiable) 25 | // 26 | // will produce the error string 27 | // 28 | // "token is unverifiable: no keyfunc was provided" 29 | func newError(message string, err error, more ...error) error { 30 | var format string 31 | var args []any 32 | if message != "" { 33 | format = "%w: %s" 34 | args = []any{err, message} 35 | } else { 36 | format = "%w" 37 | args = []any{err} 38 | } 39 | 40 | for _, e := range more { 41 | format += ": %w" 42 | args = append(args, e) 43 | } 44 | 45 | err = fmt.Errorf(format, args...) 46 | return err 47 | } 48 | -------------------------------------------------------------------------------- /errors_go_other.go: -------------------------------------------------------------------------------- 1 | //go:build !go1.20 2 | // +build !go1.20 3 | 4 | package jwt 5 | 6 | import ( 7 | "errors" 8 | "fmt" 9 | ) 10 | 11 | // Is implements checking for multiple errors using [errors.Is], since multiple 12 | // error unwrapping is not possible in versions less than Go 1.20. 13 | func (je joinedError) Is(err error) bool { 14 | for _, e := range je.errs { 15 | if errors.Is(e, err) { 16 | return true 17 | } 18 | } 19 | 20 | return false 21 | } 22 | 23 | // wrappedErrors is a workaround for wrapping multiple errors in environments 24 | // where Go 1.20 is not available. It basically uses the already implemented 25 | // functionality of joinedError to handle multiple errors with supplies a 26 | // custom error message that is identical to the one we produce in Go 1.20 using 27 | // multiple %w directives. 28 | type wrappedErrors struct { 29 | msg string 30 | joinedError 31 | } 32 | 33 | // Error returns the stored error string 34 | func (we wrappedErrors) Error() string { 35 | return we.msg 36 | } 37 | 38 | // newError creates a new error message with a detailed error message. The 39 | // message will be prefixed with the contents of the supplied error type. 40 | // Additionally, more errors, that provide more context can be supplied which 41 | // will be appended to the message. Since we cannot use of Go 1.20's possibility 42 | // to include more than one %w formatting directive in [fmt.Errorf], we have to 43 | // emulate that. 44 | // 45 | // For example, 46 | // 47 | // newError("no keyfunc was provided", ErrTokenUnverifiable) 48 | // 49 | // will produce the error string 50 | // 51 | // "token is unverifiable: no keyfunc was provided" 52 | func newError(message string, err error, more ...error) error { 53 | // We cannot wrap multiple errors here with %w, so we have to be a little 54 | // bit creative. Basically, we are using %s instead of %w to produce the 55 | // same error message and then throw the result into a custom error struct. 56 | var format string 57 | var args []any 58 | if message != "" { 59 | format = "%s: %s" 60 | args = []any{err, message} 61 | } else { 62 | format = "%s" 63 | args = []any{err} 64 | } 65 | errs := []error{err} 66 | 67 | for _, e := range more { 68 | format += ": %s" 69 | args = append(args, e) 70 | errs = append(errs, e) 71 | } 72 | 73 | err = &wrappedErrors{ 74 | msg: fmt.Sprintf(format, args...), 75 | joinedError: joinedError{errs: errs}, 76 | } 77 | return err 78 | } 79 | -------------------------------------------------------------------------------- /errors_test.go: -------------------------------------------------------------------------------- 1 | package jwt 2 | 3 | import ( 4 | "errors" 5 | "io" 6 | "testing" 7 | ) 8 | 9 | func Test_joinErrors(t *testing.T) { 10 | type args struct { 11 | errs []error 12 | } 13 | tests := []struct { 14 | name string 15 | args args 16 | wantErrors []error 17 | wantMessage string 18 | }{ 19 | { 20 | name: "multiple errors", 21 | args: args{ 22 | errs: []error{ErrTokenNotValidYet, ErrTokenExpired}, 23 | }, 24 | wantErrors: []error{ErrTokenNotValidYet, ErrTokenExpired}, 25 | wantMessage: "token is not valid yet, token is expired", 26 | }, 27 | } 28 | for _, tt := range tests { 29 | t.Run(tt.name, func(t *testing.T) { 30 | err := joinErrors(tt.args.errs...) 31 | for _, wantErr := range tt.wantErrors { 32 | if !errors.Is(err, wantErr) { 33 | t.Errorf("joinErrors() error = %v, does not contain %v", err, wantErr) 34 | } 35 | } 36 | 37 | if err.Error() != tt.wantMessage { 38 | t.Errorf("joinErrors() error.Error() = %v, wantMessage %v", err, tt.wantMessage) 39 | } 40 | }) 41 | } 42 | } 43 | 44 | func Test_newError(t *testing.T) { 45 | type args struct { 46 | message string 47 | err error 48 | more []error 49 | } 50 | tests := []struct { 51 | name string 52 | args args 53 | wantErrors []error 54 | wantMessage string 55 | }{ 56 | { 57 | name: "single error", 58 | args: args{message: "something is wrong", err: ErrTokenMalformed}, 59 | wantMessage: "token is malformed: something is wrong", 60 | wantErrors: []error{ErrTokenMalformed}, 61 | }, 62 | { 63 | name: "two errors", 64 | args: args{message: "something is wrong", err: ErrTokenMalformed, more: []error{io.ErrUnexpectedEOF}}, 65 | wantMessage: "token is malformed: something is wrong: unexpected EOF", 66 | wantErrors: []error{ErrTokenMalformed}, 67 | }, 68 | { 69 | name: "two errors, no detail", 70 | args: args{message: "", err: ErrTokenInvalidClaims, more: []error{ErrTokenExpired}}, 71 | wantMessage: "token has invalid claims: token is expired", 72 | wantErrors: []error{ErrTokenInvalidClaims, ErrTokenExpired}, 73 | }, 74 | { 75 | name: "two errors, no detail and join error", 76 | args: args{message: "", err: ErrTokenInvalidClaims, more: []error{joinErrors(ErrTokenExpired, ErrTokenNotValidYet)}}, 77 | wantMessage: "token has invalid claims: token is expired, token is not valid yet", 78 | wantErrors: []error{ErrTokenInvalidClaims, ErrTokenExpired, ErrTokenNotValidYet}, 79 | }, 80 | } 81 | for _, tt := range tests { 82 | t.Run(tt.name, func(t *testing.T) { 83 | err := newError(tt.args.message, tt.args.err, tt.args.more...) 84 | for _, wantErr := range tt.wantErrors { 85 | if !errors.Is(err, wantErr) { 86 | t.Errorf("newError() error = %v, does not contain %v", err, wantErr) 87 | } 88 | } 89 | 90 | if err.Error() != tt.wantMessage { 91 | t.Errorf("newError() error.Error() = %v, wantMessage %v", err, tt.wantMessage) 92 | } 93 | }) 94 | } 95 | } 96 | -------------------------------------------------------------------------------- /example_test.go: -------------------------------------------------------------------------------- 1 | package jwt_test 2 | 3 | import ( 4 | "errors" 5 | "fmt" 6 | "log" 7 | "time" 8 | 9 | "github.com/golang-jwt/jwt/v5" 10 | ) 11 | 12 | // Example (atypical) using the RegisteredClaims type by itself to parse a token. 13 | // The RegisteredClaims type is designed to be embedded into your custom types 14 | // to provide standard validation features. You can use it alone, but there's 15 | // no way to retrieve other fields after parsing. 16 | // See the CustomClaimsType example for intended usage. 17 | func ExampleNewWithClaims_registeredClaims() { 18 | mySigningKey := []byte("AllYourBase") 19 | 20 | // Create the Claims 21 | claims := &jwt.RegisteredClaims{ 22 | ExpiresAt: jwt.NewNumericDate(time.Unix(1516239022, 0)), 23 | Issuer: "test", 24 | } 25 | 26 | token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims) 27 | ss, err := token.SignedString(mySigningKey) 28 | fmt.Println(ss, err) 29 | // Output: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJ0ZXN0IiwiZXhwIjoxNTE2MjM5MDIyfQ.0XN_1Tpp9FszFOonIBpwha0c_SfnNI22DhTnjMshPg8 30 | } 31 | 32 | // Example creating a token using a custom claims type. The RegisteredClaims is embedded 33 | // in the custom type to allow for easy encoding, parsing and validation of registered claims. 34 | func ExampleNewWithClaims_customClaimsType() { 35 | mySigningKey := []byte("AllYourBase") 36 | 37 | type MyCustomClaims struct { 38 | Foo string `json:"foo"` 39 | jwt.RegisteredClaims 40 | } 41 | 42 | // Create claims with multiple fields populated 43 | claims := MyCustomClaims{ 44 | "bar", 45 | jwt.RegisteredClaims{ 46 | // A usual scenario is to set the expiration time relative to the current time 47 | ExpiresAt: jwt.NewNumericDate(time.Now().Add(24 * time.Hour)), 48 | IssuedAt: jwt.NewNumericDate(time.Now()), 49 | NotBefore: jwt.NewNumericDate(time.Now()), 50 | Issuer: "test", 51 | Subject: "somebody", 52 | ID: "1", 53 | Audience: []string{"somebody_else"}, 54 | }, 55 | } 56 | 57 | fmt.Printf("foo: %v\n", claims.Foo) 58 | 59 | // Create claims while leaving out some of the optional fields 60 | claims = MyCustomClaims{ 61 | "bar", 62 | jwt.RegisteredClaims{ 63 | // Also fixed dates can be used for the NumericDate 64 | ExpiresAt: jwt.NewNumericDate(time.Unix(1516239022, 0)), 65 | Issuer: "test", 66 | }, 67 | } 68 | 69 | token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims) 70 | ss, err := token.SignedString(mySigningKey) 71 | fmt.Println(ss, err) 72 | 73 | // Output: foo: bar 74 | // eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIiLCJpc3MiOiJ0ZXN0IiwiZXhwIjoxNTE2MjM5MDIyfQ.xVuY2FZ_MRXMIEgVQ7J-TFtaucVFRXUzHm9LmV41goM 75 | } 76 | 77 | // Example creating a token using a custom claims type. The RegisteredClaims is embedded 78 | // in the custom type to allow for easy encoding, parsing and validation of standard claims. 79 | func ExampleParseWithClaims_customClaimsType() { 80 | tokenString := "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIiLCJpc3MiOiJ0ZXN0IiwiYXVkIjoic2luZ2xlIn0.QAWg1vGvnqRuCFTMcPkjZljXHh8U3L_qUjszOtQbeaA" 81 | 82 | type MyCustomClaims struct { 83 | Foo string `json:"foo"` 84 | jwt.RegisteredClaims 85 | } 86 | 87 | token, err := jwt.ParseWithClaims(tokenString, &MyCustomClaims{}, func(token *jwt.Token) (interface{}, error) { 88 | return []byte("AllYourBase"), nil 89 | }) 90 | if err != nil { 91 | log.Fatal(err) 92 | } else if claims, ok := token.Claims.(*MyCustomClaims); ok { 93 | fmt.Println(claims.Foo, claims.Issuer) 94 | } else { 95 | log.Fatal("unknown claims type, cannot proceed") 96 | } 97 | 98 | // Output: bar test 99 | } 100 | 101 | // Example creating a token using a custom claims type and validation options. The RegisteredClaims is embedded 102 | // in the custom type to allow for easy encoding, parsing and validation of standard claims. 103 | func ExampleParseWithClaims_validationOptions() { 104 | tokenString := "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIiLCJpc3MiOiJ0ZXN0IiwiYXVkIjoic2luZ2xlIn0.QAWg1vGvnqRuCFTMcPkjZljXHh8U3L_qUjszOtQbeaA" 105 | 106 | type MyCustomClaims struct { 107 | Foo string `json:"foo"` 108 | jwt.RegisteredClaims 109 | } 110 | 111 | token, err := jwt.ParseWithClaims(tokenString, &MyCustomClaims{}, func(token *jwt.Token) (interface{}, error) { 112 | return []byte("AllYourBase"), nil 113 | }, jwt.WithLeeway(5*time.Second)) 114 | if err != nil { 115 | log.Fatal(err) 116 | } else if claims, ok := token.Claims.(*MyCustomClaims); ok { 117 | fmt.Println(claims.Foo, claims.Issuer) 118 | } else { 119 | log.Fatal("unknown claims type, cannot proceed") 120 | } 121 | 122 | // Output: bar test 123 | } 124 | 125 | type MyCustomClaims struct { 126 | Foo string `json:"foo"` 127 | jwt.RegisteredClaims 128 | } 129 | 130 | // Ensure we implement [jwt.ClaimsValidator] at compile time so we know our custom Validate method is used. 131 | var _ jwt.ClaimsValidator = (*MyCustomClaims)(nil) 132 | 133 | // Validate can be used to execute additional application-specific claims 134 | // validation. 135 | func (m MyCustomClaims) Validate() error { 136 | if m.Foo != "bar" { 137 | return errors.New("must be foobar") 138 | } 139 | 140 | return nil 141 | } 142 | 143 | // Example creating a token using a custom claims type and validation options. 144 | // The RegisteredClaims is embedded in the custom type to allow for easy 145 | // encoding, parsing and validation of standard claims and the function 146 | // CustomValidation is implemented. 147 | func ExampleParseWithClaims_customValidation() { 148 | tokenString := "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIiLCJpc3MiOiJ0ZXN0IiwiYXVkIjoic2luZ2xlIn0.QAWg1vGvnqRuCFTMcPkjZljXHh8U3L_qUjszOtQbeaA" 149 | 150 | token, err := jwt.ParseWithClaims(tokenString, &MyCustomClaims{}, func(token *jwt.Token) (interface{}, error) { 151 | return []byte("AllYourBase"), nil 152 | }, jwt.WithLeeway(5*time.Second)) 153 | if err != nil { 154 | log.Fatal(err) 155 | } else if claims, ok := token.Claims.(*MyCustomClaims); ok { 156 | fmt.Println(claims.Foo, claims.Issuer) 157 | } else { 158 | log.Fatal("unknown claims type, cannot proceed") 159 | } 160 | 161 | // Output: bar test 162 | } 163 | 164 | // An example of parsing the error types using errors.Is. 165 | func ExampleParse_errorChecking() { 166 | // Token from another example. This token is expired 167 | var tokenString = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIiLCJleHAiOjE1MDAwLCJpc3MiOiJ0ZXN0In0.HE7fK0xOQwFEr4WDgRWj4teRPZ6i3GLwD5YCm6Pwu_c" 168 | 169 | token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) { 170 | return []byte("AllYourBase"), nil 171 | }) 172 | 173 | switch { 174 | case token.Valid: 175 | fmt.Println("You look nice today") 176 | case errors.Is(err, jwt.ErrTokenMalformed): 177 | fmt.Println("That's not even a token") 178 | case errors.Is(err, jwt.ErrTokenSignatureInvalid): 179 | // Invalid signature 180 | fmt.Println("Invalid signature") 181 | case errors.Is(err, jwt.ErrTokenExpired) || errors.Is(err, jwt.ErrTokenNotValidYet): 182 | // Token is either expired or not active yet 183 | fmt.Println("Timing is everything") 184 | default: 185 | fmt.Println("Couldn't handle this token:", err) 186 | } 187 | 188 | // Output: Timing is everything 189 | } 190 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/golang-jwt/jwt/v5 2 | 3 | go 1.18 4 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/golang-jwt/jwt/048854f1b0ac96c0a843d52fc09d7878b853683f/go.sum -------------------------------------------------------------------------------- /hmac.go: -------------------------------------------------------------------------------- 1 | package jwt 2 | 3 | import ( 4 | "crypto" 5 | "crypto/hmac" 6 | "errors" 7 | ) 8 | 9 | // SigningMethodHMAC implements the HMAC-SHA family of signing methods. 10 | // Expects key type of []byte for both signing and validation 11 | type SigningMethodHMAC struct { 12 | Name string 13 | Hash crypto.Hash 14 | } 15 | 16 | // Specific instances for HS256 and company 17 | var ( 18 | SigningMethodHS256 *SigningMethodHMAC 19 | SigningMethodHS384 *SigningMethodHMAC 20 | SigningMethodHS512 *SigningMethodHMAC 21 | ErrSignatureInvalid = errors.New("signature is invalid") 22 | ) 23 | 24 | func init() { 25 | // HS256 26 | SigningMethodHS256 = &SigningMethodHMAC{"HS256", crypto.SHA256} 27 | RegisterSigningMethod(SigningMethodHS256.Alg(), func() SigningMethod { 28 | return SigningMethodHS256 29 | }) 30 | 31 | // HS384 32 | SigningMethodHS384 = &SigningMethodHMAC{"HS384", crypto.SHA384} 33 | RegisterSigningMethod(SigningMethodHS384.Alg(), func() SigningMethod { 34 | return SigningMethodHS384 35 | }) 36 | 37 | // HS512 38 | SigningMethodHS512 = &SigningMethodHMAC{"HS512", crypto.SHA512} 39 | RegisterSigningMethod(SigningMethodHS512.Alg(), func() SigningMethod { 40 | return SigningMethodHS512 41 | }) 42 | } 43 | 44 | func (m *SigningMethodHMAC) Alg() string { 45 | return m.Name 46 | } 47 | 48 | // Verify implements token verification for the SigningMethod. Returns nil if 49 | // the signature is valid. Key must be []byte. 50 | // 51 | // Note it is not advised to provide a []byte which was converted from a 'human 52 | // readable' string using a subset of ASCII characters. To maximize entropy, you 53 | // should ideally be providing a []byte key which was produced from a 54 | // cryptographically random source, e.g. crypto/rand. Additional information 55 | // about this, and why we intentionally are not supporting string as a key can 56 | // be found on our usage guide 57 | // https://golang-jwt.github.io/jwt/usage/signing_methods/#signing-methods-and-key-types. 58 | func (m *SigningMethodHMAC) Verify(signingString string, sig []byte, key interface{}) error { 59 | // Verify the key is the right type 60 | keyBytes, ok := key.([]byte) 61 | if !ok { 62 | return newError("HMAC verify expects []byte", ErrInvalidKeyType) 63 | } 64 | 65 | // Can we use the specified hashing method? 66 | if !m.Hash.Available() { 67 | return ErrHashUnavailable 68 | } 69 | 70 | // This signing method is symmetric, so we validate the signature 71 | // by reproducing the signature from the signing string and key, then 72 | // comparing that against the provided signature. 73 | hasher := hmac.New(m.Hash.New, keyBytes) 74 | hasher.Write([]byte(signingString)) 75 | if !hmac.Equal(sig, hasher.Sum(nil)) { 76 | return ErrSignatureInvalid 77 | } 78 | 79 | // No validation errors. Signature is good. 80 | return nil 81 | } 82 | 83 | // Sign implements token signing for the SigningMethod. Key must be []byte. 84 | // 85 | // Note it is not advised to provide a []byte which was converted from a 'human 86 | // readable' string using a subset of ASCII characters. To maximize entropy, you 87 | // should ideally be providing a []byte key which was produced from a 88 | // cryptographically random source, e.g. crypto/rand. Additional information 89 | // about this, and why we intentionally are not supporting string as a key can 90 | // be found on our usage guide https://golang-jwt.github.io/jwt/usage/signing_methods/. 91 | func (m *SigningMethodHMAC) Sign(signingString string, key interface{}) ([]byte, error) { 92 | if keyBytes, ok := key.([]byte); ok { 93 | if !m.Hash.Available() { 94 | return nil, ErrHashUnavailable 95 | } 96 | 97 | hasher := hmac.New(m.Hash.New, keyBytes) 98 | hasher.Write([]byte(signingString)) 99 | 100 | return hasher.Sum(nil), nil 101 | } 102 | 103 | return nil, newError("HMAC sign expects []byte", ErrInvalidKeyType) 104 | } 105 | -------------------------------------------------------------------------------- /hmac_example_test.go: -------------------------------------------------------------------------------- 1 | package jwt_test 2 | 3 | import ( 4 | "fmt" 5 | "log" 6 | "os" 7 | "time" 8 | 9 | "github.com/golang-jwt/jwt/v5" 10 | ) 11 | 12 | // For HMAC signing method, the key can be any []byte. It is recommended to generate 13 | // a key using crypto/rand or something equivalent. You need the same key for signing 14 | // and validating. 15 | var hmacSampleSecret []byte 16 | 17 | func init() { 18 | // Load sample key data 19 | if keyData, e := os.ReadFile("test/hmacTestKey"); e == nil { 20 | hmacSampleSecret = keyData 21 | } else { 22 | panic(e) 23 | } 24 | } 25 | 26 | // Example creating, signing, and encoding a JWT token using the HMAC signing method 27 | func ExampleNew_hmac() { 28 | // Create a new token object, specifying signing method and the claims 29 | // you would like it to contain. 30 | token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{ 31 | "foo": "bar", 32 | "nbf": time.Date(2015, 10, 10, 12, 0, 0, 0, time.UTC).Unix(), 33 | }) 34 | 35 | // Sign and get the complete encoded token as a string using the secret 36 | tokenString, err := token.SignedString(hmacSampleSecret) 37 | 38 | fmt.Println(tokenString, err) 39 | // Output: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIiLCJuYmYiOjE0NDQ0Nzg0MDB9.u1riaD1rW97opCoAuRCTy4w58Br-Zk-bh7vLiRIsrpU 40 | } 41 | 42 | // Example parsing and validating a token using the HMAC signing method 43 | func ExampleParse_hmac() { 44 | // sample token string taken from the New example 45 | tokenString := "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIiLCJuYmYiOjE0NDQ0Nzg0MDB9.u1riaD1rW97opCoAuRCTy4w58Br-Zk-bh7vLiRIsrpU" 46 | 47 | // Parse takes the token string and a function for looking up the key. The latter is especially 48 | // useful if you use multiple keys for your application. The standard is to use 'kid' in the 49 | // head of the token to identify which key to use, but the parsed token (head and claims) is provided 50 | // to the callback, providing flexibility. 51 | token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) { 52 | // hmacSampleSecret is a []byte containing your secret, e.g. []byte("my_secret_key") 53 | return hmacSampleSecret, nil 54 | }, jwt.WithValidMethods([]string{jwt.SigningMethodHS256.Alg()})) 55 | if err != nil { 56 | log.Fatal(err) 57 | } 58 | 59 | if claims, ok := token.Claims.(jwt.MapClaims); ok { 60 | fmt.Println(claims["foo"], claims["nbf"]) 61 | } else { 62 | fmt.Println(err) 63 | } 64 | 65 | // Output: bar 1.4444784e+09 66 | } 67 | -------------------------------------------------------------------------------- /hmac_test.go: -------------------------------------------------------------------------------- 1 | package jwt_test 2 | 3 | import ( 4 | "os" 5 | "reflect" 6 | "strings" 7 | "testing" 8 | 9 | "github.com/golang-jwt/jwt/v5" 10 | ) 11 | 12 | var hmacTestData = []struct { 13 | name string 14 | tokenString string 15 | alg string 16 | claims map[string]interface{} 17 | valid bool 18 | }{ 19 | { 20 | "web sample", 21 | "eyJ0eXAiOiJKV1QiLA0KICJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJqb2UiLA0KICJleHAiOjEzMDA4MTkzODAsDQogImh0dHA6Ly9leGFtcGxlLmNvbS9pc19yb290Ijp0cnVlfQ.dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk", 22 | "HS256", 23 | map[string]interface{}{"iss": "joe", "exp": 1300819380, "http://example.com/is_root": true}, 24 | true, 25 | }, 26 | { 27 | "HS384", 28 | "eyJhbGciOiJIUzM4NCIsInR5cCI6IkpXVCJ9.eyJleHAiOjEuMzAwODE5MzhlKzA5LCJodHRwOi8vZXhhbXBsZS5jb20vaXNfcm9vdCI6dHJ1ZSwiaXNzIjoiam9lIn0.KWZEuOD5lbBxZ34g7F-SlVLAQ_r5KApWNWlZIIMyQVz5Zs58a7XdNzj5_0EcNoOy", 29 | "HS384", 30 | map[string]interface{}{"iss": "joe", "exp": 1300819380, "http://example.com/is_root": true}, 31 | true, 32 | }, 33 | { 34 | "HS512", 35 | "eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJleHAiOjEuMzAwODE5MzhlKzA5LCJodHRwOi8vZXhhbXBsZS5jb20vaXNfcm9vdCI6dHJ1ZSwiaXNzIjoiam9lIn0.CN7YijRX6Aw1n2jyI2Id1w90ja-DEMYiWixhYCyHnrZ1VfJRaFQz1bEbjjA5Fn4CLYaUG432dEYmSbS4Saokmw", 36 | "HS512", 37 | map[string]interface{}{"iss": "joe", "exp": 1300819380, "http://example.com/is_root": true}, 38 | true, 39 | }, 40 | { 41 | "web sample: invalid", 42 | "eyJ0eXAiOiJKV1QiLA0KICJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJqb2UiLA0KICJleHAiOjEzMDA4MTkzODAsDQogImh0dHA6Ly9leGFtcGxlLmNvbS9pc19yb290Ijp0cnVlfQ.dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXo", 43 | "HS256", 44 | map[string]interface{}{"iss": "joe", "exp": 1300819380, "http://example.com/is_root": true}, 45 | false, 46 | }, 47 | } 48 | 49 | // Sample data from http://tools.ietf.org/html/draft-jones-json-web-signature-04#appendix-A.1 50 | var hmacTestKey, _ = os.ReadFile("test/hmacTestKey") 51 | 52 | func TestHMACVerify(t *testing.T) { 53 | for _, data := range hmacTestData { 54 | parts := strings.Split(data.tokenString, ".") 55 | 56 | method := jwt.GetSigningMethod(data.alg) 57 | err := method.Verify(strings.Join(parts[0:2], "."), decodeSegment(t, parts[2]), hmacTestKey) 58 | if data.valid && err != nil { 59 | t.Errorf("[%v] Error while verifying key: %v", data.name, err) 60 | } 61 | if !data.valid && err == nil { 62 | t.Errorf("[%v] Invalid key passed validation", data.name) 63 | } 64 | } 65 | } 66 | 67 | func TestHMACSign(t *testing.T) { 68 | for _, data := range hmacTestData { 69 | if !data.valid { 70 | continue 71 | } 72 | parts := strings.Split(data.tokenString, ".") 73 | method := jwt.GetSigningMethod(data.alg) 74 | sig, err := method.Sign(strings.Join(parts[0:2], "."), hmacTestKey) 75 | if err != nil { 76 | t.Errorf("[%v] Error signing token: %v", data.name, err) 77 | } 78 | if !reflect.DeepEqual(sig, decodeSegment(t, parts[2])) { 79 | t.Errorf("[%v] Incorrect signature.\nwas:\n%v\nexpecting:\n%v", data.name, sig, parts[2]) 80 | } 81 | } 82 | } 83 | 84 | func BenchmarkHS256Signing(b *testing.B) { 85 | benchmarkSigning(b, jwt.SigningMethodHS256, hmacTestKey) 86 | } 87 | 88 | func BenchmarkHS384Signing(b *testing.B) { 89 | benchmarkSigning(b, jwt.SigningMethodHS384, hmacTestKey) 90 | } 91 | 92 | func BenchmarkHS512Signing(b *testing.B) { 93 | benchmarkSigning(b, jwt.SigningMethodHS512, hmacTestKey) 94 | } 95 | -------------------------------------------------------------------------------- /http_example_test.go: -------------------------------------------------------------------------------- 1 | package jwt_test 2 | 3 | // Example HTTP auth using asymmetric crypto/RSA keys 4 | // This is based on a (now outdated) example at https://gist.github.com/cryptix/45c33ecf0ae54828e63b 5 | 6 | import ( 7 | "crypto/rsa" 8 | "fmt" 9 | "io" 10 | "log" 11 | "net" 12 | "net/http" 13 | "net/url" 14 | "os" 15 | "strings" 16 | "time" 17 | 18 | "github.com/golang-jwt/jwt/v5" 19 | "github.com/golang-jwt/jwt/v5/request" 20 | ) 21 | 22 | // location of the files used for signing and verification 23 | const ( 24 | privKeyPath = "test/sample_key" // openssl genrsa -out app.rsa keysize 25 | pubKeyPath = "test/sample_key.pub" // openssl rsa -in app.rsa -pubout > app.rsa.pub 26 | ) 27 | 28 | var ( 29 | verifyKey *rsa.PublicKey 30 | signKey *rsa.PrivateKey 31 | serverPort int 32 | ) 33 | 34 | // read the key files before starting http handlers 35 | func init() { 36 | signBytes, err := os.ReadFile(privKeyPath) 37 | fatal(err) 38 | 39 | signKey, err = jwt.ParseRSAPrivateKeyFromPEM(signBytes) 40 | fatal(err) 41 | 42 | verifyBytes, err := os.ReadFile(pubKeyPath) 43 | fatal(err) 44 | 45 | verifyKey, err = jwt.ParseRSAPublicKeyFromPEM(verifyBytes) 46 | fatal(err) 47 | 48 | http.HandleFunc("/authenticate", authHandler) 49 | http.HandleFunc("/restricted", restrictedHandler) 50 | 51 | // Setup listener 52 | listener, err := net.ListenTCP("tcp", &net.TCPAddr{}) 53 | fatal(err) 54 | serverPort = listener.Addr().(*net.TCPAddr).Port 55 | 56 | log.Println("Listening...") 57 | go func() { 58 | fatal(http.Serve(listener, nil)) 59 | }() 60 | } 61 | 62 | func fatal(err error) { 63 | if err != nil { 64 | log.Fatal(err) 65 | } 66 | } 67 | 68 | // Define some custom types were going to use within our tokens 69 | type CustomerInfo struct { 70 | Name string 71 | Kind string 72 | } 73 | 74 | type CustomClaimsExample struct { 75 | jwt.RegisteredClaims 76 | TokenType string 77 | CustomerInfo 78 | } 79 | 80 | func Example_getTokenViaHTTP() { 81 | // See func authHandler for an example auth handler that produces a token 82 | res, err := http.PostForm(fmt.Sprintf("http://localhost:%v/authenticate", serverPort), url.Values{ 83 | "user": {"test"}, 84 | "pass": {"known"}, 85 | }) 86 | fatal(err) 87 | 88 | if res.StatusCode != 200 { 89 | fmt.Println("Unexpected status code", res.StatusCode) 90 | } 91 | 92 | // Read the token out of the response body 93 | buf, err := io.ReadAll(res.Body) 94 | fatal(err) 95 | _ = res.Body.Close() 96 | tokenString := strings.TrimSpace(string(buf)) 97 | 98 | // Parse the token 99 | token, err := jwt.ParseWithClaims(tokenString, &CustomClaimsExample{}, func(token *jwt.Token) (interface{}, error) { 100 | // since we only use the one private key to sign the tokens, 101 | // we also only use its public counter part to verify 102 | return verifyKey, nil 103 | }) 104 | fatal(err) 105 | 106 | claims := token.Claims.(*CustomClaimsExample) 107 | fmt.Println(claims.Name) 108 | 109 | // Output: test 110 | } 111 | 112 | func Example_useTokenViaHTTP() { 113 | // Make a sample token 114 | // In a real world situation, this token will have been acquired from 115 | // some other API call (see Example_getTokenViaHTTP) 116 | token, err := createToken("foo") 117 | fatal(err) 118 | 119 | // Make request. See func restrictedHandler for example request processor 120 | req, err := http.NewRequest("GET", fmt.Sprintf("http://localhost:%v/restricted", serverPort), nil) 121 | fatal(err) 122 | req.Header.Set("Authorization", fmt.Sprintf("Bearer %v", token)) 123 | res, err := http.DefaultClient.Do(req) 124 | fatal(err) 125 | 126 | // Read the response body 127 | buf, err := io.ReadAll(res.Body) 128 | fatal(err) 129 | _ = res.Body.Close() 130 | fmt.Printf("%s", buf) 131 | 132 | // Output: Welcome, foo 133 | } 134 | 135 | func createToken(user string) (string, error) { 136 | // create a signer for rsa 256 137 | t := jwt.New(jwt.GetSigningMethod("RS256")) 138 | 139 | // set our claims 140 | t.Claims = &CustomClaimsExample{ 141 | jwt.RegisteredClaims{ 142 | // set the expire time 143 | // see https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.4 144 | ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Minute * 1)), 145 | }, 146 | "level1", 147 | CustomerInfo{user, "human"}, 148 | } 149 | 150 | // Creat token string 151 | return t.SignedString(signKey) 152 | } 153 | 154 | // reads the form values, checks them and creates the token 155 | func authHandler(w http.ResponseWriter, r *http.Request) { 156 | // make sure its post 157 | if r.Method != "POST" { 158 | w.WriteHeader(http.StatusBadRequest) 159 | _, _ = fmt.Fprintln(w, "No POST", r.Method) 160 | return 161 | } 162 | 163 | user := r.FormValue("user") 164 | pass := r.FormValue("pass") 165 | 166 | log.Printf("Authenticate: user[%s] pass[%s]\n", user, pass) 167 | 168 | // check values 169 | if user != "test" || pass != "known" { 170 | w.WriteHeader(http.StatusForbidden) 171 | _, _ = fmt.Fprintln(w, "Wrong info") 172 | return 173 | } 174 | 175 | tokenString, err := createToken(user) 176 | if err != nil { 177 | w.WriteHeader(http.StatusInternalServerError) 178 | _, _ = fmt.Fprintln(w, "Sorry, error while Signing Token!") 179 | log.Printf("Token Signing error: %v\n", err) 180 | return 181 | } 182 | 183 | w.Header().Set("Content-Type", "application/jwt") 184 | w.WriteHeader(http.StatusOK) 185 | _, _ = fmt.Fprintln(w, tokenString) 186 | } 187 | 188 | // only accessible with a valid token 189 | func restrictedHandler(w http.ResponseWriter, r *http.Request) { 190 | // Get token from request 191 | token, err := request.ParseFromRequest(r, request.OAuth2Extractor, func(token *jwt.Token) (interface{}, error) { 192 | // since we only use the one private key to sign the tokens, 193 | // we also only use its public counter part to verify 194 | return verifyKey, nil 195 | }, request.WithClaims(&CustomClaimsExample{})) 196 | 197 | // If the token is missing or invalid, return error 198 | if err != nil { 199 | w.WriteHeader(http.StatusUnauthorized) 200 | _, _ = fmt.Fprintln(w, "Invalid token:", err) 201 | return 202 | } 203 | 204 | // Token is valid 205 | _, _ = fmt.Fprintln(w, "Welcome,", token.Claims.(*CustomClaimsExample).Name) 206 | } 207 | -------------------------------------------------------------------------------- /jwt_test.go: -------------------------------------------------------------------------------- 1 | package jwt 2 | 3 | import ( 4 | "testing" 5 | ) 6 | 7 | func TestSplitToken(t *testing.T) { 8 | t.Parallel() 9 | 10 | tests := []struct { 11 | name string 12 | input string 13 | expected []string 14 | isValid bool 15 | }{ 16 | { 17 | name: "valid token with three parts", 18 | input: "header.claims.signature", 19 | expected: []string{"header", "claims", "signature"}, 20 | isValid: true, 21 | }, 22 | { 23 | name: "invalid token with two parts only", 24 | input: "header.claims", 25 | expected: nil, 26 | isValid: false, 27 | }, 28 | { 29 | name: "invalid token with one part only", 30 | input: "header", 31 | expected: nil, 32 | isValid: false, 33 | }, 34 | { 35 | name: "invalid token with extra delimiter", 36 | input: "header.claims.signature.extra", 37 | expected: nil, 38 | isValid: false, 39 | }, 40 | { 41 | name: "invalid empty token", 42 | input: "", 43 | expected: nil, 44 | isValid: false, 45 | }, 46 | { 47 | name: "valid token with empty parts", 48 | input: "..signature", 49 | expected: []string{"", "", "signature"}, 50 | isValid: true, 51 | }, 52 | { 53 | // We are just splitting the token into parts, so we don't care about the actual values. 54 | // It is up to the caller to validate the parts. 55 | name: "valid token with all parts empty", 56 | input: "..", 57 | expected: []string{"", "", ""}, 58 | isValid: true, 59 | }, 60 | { 61 | name: "invalid token with just delimiters and extra part", 62 | input: "...", 63 | expected: nil, 64 | isValid: false, 65 | }, 66 | { 67 | name: "invalid token with many delimiters", 68 | input: "header.claims.signature..................", 69 | expected: nil, 70 | isValid: false, 71 | }, 72 | } 73 | 74 | for _, tt := range tests { 75 | t.Run(tt.name, func(t *testing.T) { 76 | parts, ok := splitToken(tt.input) 77 | if ok != tt.isValid { 78 | t.Errorf("expected %t, got %t", tt.isValid, ok) 79 | } 80 | if ok { 81 | for i, part := range tt.expected { 82 | if parts[i] != part { 83 | t.Errorf("expected %s, got %s", part, parts[i]) 84 | } 85 | } 86 | } 87 | }) 88 | } 89 | } 90 | -------------------------------------------------------------------------------- /map_claims.go: -------------------------------------------------------------------------------- 1 | package jwt 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | ) 7 | 8 | // MapClaims is a claims type that uses the map[string]interface{} for JSON 9 | // decoding. This is the default claims type if you don't supply one 10 | type MapClaims map[string]interface{} 11 | 12 | // GetExpirationTime implements the Claims interface. 13 | func (m MapClaims) GetExpirationTime() (*NumericDate, error) { 14 | return m.parseNumericDate("exp") 15 | } 16 | 17 | // GetNotBefore implements the Claims interface. 18 | func (m MapClaims) GetNotBefore() (*NumericDate, error) { 19 | return m.parseNumericDate("nbf") 20 | } 21 | 22 | // GetIssuedAt implements the Claims interface. 23 | func (m MapClaims) GetIssuedAt() (*NumericDate, error) { 24 | return m.parseNumericDate("iat") 25 | } 26 | 27 | // GetAudience implements the Claims interface. 28 | func (m MapClaims) GetAudience() (ClaimStrings, error) { 29 | return m.parseClaimsString("aud") 30 | } 31 | 32 | // GetIssuer implements the Claims interface. 33 | func (m MapClaims) GetIssuer() (string, error) { 34 | return m.parseString("iss") 35 | } 36 | 37 | // GetSubject implements the Claims interface. 38 | func (m MapClaims) GetSubject() (string, error) { 39 | return m.parseString("sub") 40 | } 41 | 42 | // parseNumericDate tries to parse a key in the map claims type as a number 43 | // date. This will succeed, if the underlying type is either a [float64] or a 44 | // [json.Number]. Otherwise, nil will be returned. 45 | func (m MapClaims) parseNumericDate(key string) (*NumericDate, error) { 46 | v, ok := m[key] 47 | if !ok { 48 | return nil, nil 49 | } 50 | 51 | switch exp := v.(type) { 52 | case float64: 53 | if exp == 0 { 54 | return nil, nil 55 | } 56 | 57 | return newNumericDateFromSeconds(exp), nil 58 | case json.Number: 59 | v, _ := exp.Float64() 60 | 61 | return newNumericDateFromSeconds(v), nil 62 | } 63 | 64 | return nil, newError(fmt.Sprintf("%s is invalid", key), ErrInvalidType) 65 | } 66 | 67 | // parseClaimsString tries to parse a key in the map claims type as a 68 | // [ClaimsStrings] type, which can either be a string or an array of string. 69 | func (m MapClaims) parseClaimsString(key string) (ClaimStrings, error) { 70 | var cs []string 71 | switch v := m[key].(type) { 72 | case string: 73 | cs = append(cs, v) 74 | case []string: 75 | cs = v 76 | case []interface{}: 77 | for _, a := range v { 78 | vs, ok := a.(string) 79 | if !ok { 80 | return nil, newError(fmt.Sprintf("%s is invalid", key), ErrInvalidType) 81 | } 82 | cs = append(cs, vs) 83 | } 84 | } 85 | 86 | return cs, nil 87 | } 88 | 89 | // parseString tries to parse a key in the map claims type as a [string] type. 90 | // If the key does not exist, an empty string is returned. If the key has the 91 | // wrong type, an error is returned. 92 | func (m MapClaims) parseString(key string) (string, error) { 93 | var ( 94 | ok bool 95 | raw interface{} 96 | iss string 97 | ) 98 | raw, ok = m[key] 99 | if !ok { 100 | return "", nil 101 | } 102 | 103 | iss, ok = raw.(string) 104 | if !ok { 105 | return "", newError(fmt.Sprintf("%s is invalid", key), ErrInvalidType) 106 | } 107 | 108 | return iss, nil 109 | } 110 | -------------------------------------------------------------------------------- /map_claims_test.go: -------------------------------------------------------------------------------- 1 | package jwt 2 | 3 | import ( 4 | "testing" 5 | "time" 6 | ) 7 | 8 | func TestVerifyAud(t *testing.T) { 9 | var nilInterface interface{} 10 | var nilListInterface []interface{} 11 | var intListInterface interface{} = []int{1, 2, 3} 12 | type test struct { 13 | Name string 14 | MapClaims MapClaims 15 | Expected bool 16 | Comparison []string 17 | MatchAllAud bool 18 | Required bool 19 | } 20 | tests := []test{ 21 | // Matching Claim in aud 22 | // Required = true 23 | {Name: "String Aud matching required", MapClaims: MapClaims{"aud": "example.com"}, Expected: true, Required: true, Comparison: []string{"example.com"}}, 24 | {Name: "[]String Aud with match required", MapClaims: MapClaims{"aud": []string{"example.com", "example.example.com"}}, Expected: true, Required: true, Comparison: []string{"example.com"}}, 25 | {Name: "[]String Aud with []match any required", MapClaims: MapClaims{"aud": []string{"example.com", "example.example.com"}}, Expected: true, Required: true, Comparison: []string{"example.com", "auth.example.com"}}, 26 | {Name: "[]String Aud with []match all required", MapClaims: MapClaims{"aud": []string{"example.com", "example.example.com"}}, Expected: true, Required: true, Comparison: []string{"example.com", "example.example.com"}, MatchAllAud: true}, 27 | 28 | // Required = false 29 | {Name: "String Aud with match not required", MapClaims: MapClaims{"aud": "example.com"}, Expected: true, Required: false, Comparison: []string{"example.com"}}, 30 | {Name: "Empty String Aud with match not required", MapClaims: MapClaims{}, Expected: true, Required: false, Comparison: []string{"example.com"}}, 31 | {Name: "Empty String Aud with match not required", MapClaims: MapClaims{"aud": ""}, Expected: true, Required: false, Comparison: []string{"example.com"}}, 32 | {Name: "Nil String Aud with match not required", MapClaims: MapClaims{"aud": nil}, Expected: true, Required: false, Comparison: []string{"example.com"}}, 33 | 34 | {Name: "[]String Aud with match not required", MapClaims: MapClaims{"aud": []string{"example.com", "example.example.com"}}, Expected: true, Required: false, Comparison: []string{"example.com"}}, 35 | {Name: "Empty []String Aud with match not required", MapClaims: MapClaims{"aud": []string{}}, Expected: true, Required: false, Comparison: []string{"example.com"}}, 36 | 37 | // Non-Matching Claim in aud 38 | // Required = true 39 | {Name: "String Aud without match required", MapClaims: MapClaims{"aud": "not.example.com"}, Expected: false, Required: true, Comparison: []string{"example.com"}}, 40 | {Name: "Empty String Aud without match required", MapClaims: MapClaims{"aud": ""}, Expected: false, Required: true, Comparison: []string{"example.com"}}, 41 | {Name: "[]String Aud without match required", MapClaims: MapClaims{"aud": []string{"not.example.com", "example.example.com"}}, Expected: false, Required: true, Comparison: []string{"example.com"}}, 42 | {Name: "Empty []String Aud without match required", MapClaims: MapClaims{"aud": []string{""}}, Expected: false, Required: true, Comparison: []string{"example.com"}}, 43 | {Name: "String Aud without match not required", MapClaims: MapClaims{"aud": "not.example.com"}, Expected: false, Required: true, Comparison: []string{"example.com"}}, 44 | {Name: "Empty String Aud without match not required", MapClaims: MapClaims{"aud": ""}, Expected: false, Required: true, Comparison: []string{"example.com"}}, 45 | {Name: "[]String Aud without match not required", MapClaims: MapClaims{"aud": []string{"not.example.com", "example.example.com"}}, Expected: false, Required: true, Comparison: []string{"example.com"}}, 46 | 47 | // Required = false 48 | {Name: "Empty []String Aud without match required", MapClaims: MapClaims{"aud": []string{""}}, Expected: true, Required: false, Comparison: []string{"example.com"}}, 49 | 50 | // []interface{} 51 | {Name: "Empty []interface{} Aud without match required", MapClaims: MapClaims{"aud": nilListInterface}, Expected: true, Required: false, Comparison: []string{"example.com"}}, 52 | {Name: "[]interface{} Aud with match required", MapClaims: MapClaims{"aud": []interface{}{"a", "foo", "example.com"}}, Expected: true, Required: true, Comparison: []string{"example.com"}}, 53 | {Name: "[]interface{} Aud with match but invalid types", MapClaims: MapClaims{"aud": []interface{}{"a", 5, "example.com"}}, Expected: false, Required: true, Comparison: []string{"example.com"}}, 54 | {Name: "[]interface{} Aud int with match required", MapClaims: MapClaims{"aud": intListInterface}, Expected: false, Required: true, Comparison: []string{"example.com"}}, 55 | 56 | // interface{} 57 | {Name: "Empty interface{} Aud without match not required", MapClaims: MapClaims{"aud": nilInterface}, Expected: true, Required: false, Comparison: []string{"example.com"}}, 58 | } 59 | 60 | for _, test := range tests { 61 | t.Run(test.Name, func(t *testing.T) { 62 | var opts []ParserOption 63 | 64 | if test.Required && test.MatchAllAud { 65 | opts = append(opts, WithAllAudiences(test.Comparison...)) 66 | } else if test.Required { 67 | opts = append(opts, WithAudience(test.Comparison...)) 68 | } 69 | 70 | validator := NewValidator(opts...) 71 | got := validator.Validate(test.MapClaims) 72 | 73 | if (got == nil) != test.Expected { 74 | t.Errorf("Expected %v, got %v", test.Expected, (got == nil)) 75 | } 76 | }) 77 | } 78 | } 79 | 80 | func TestMapclaimsVerifyIssuedAtInvalidTypeString(t *testing.T) { 81 | mapClaims := MapClaims{ 82 | "iat": "foo", 83 | } 84 | want := false 85 | got := NewValidator(WithIssuedAt()).Validate(mapClaims) 86 | if want != (got == nil) { 87 | t.Fatalf("Failed to verify claims, wanted: %v got %v", want, (got == nil)) 88 | } 89 | } 90 | 91 | func TestMapclaimsVerifyNotBeforeInvalidTypeString(t *testing.T) { 92 | mapClaims := MapClaims{ 93 | "nbf": "foo", 94 | } 95 | want := false 96 | got := NewValidator().Validate(mapClaims) 97 | if want != (got == nil) { 98 | t.Fatalf("Failed to verify claims, wanted: %v got %v", want, (got == nil)) 99 | } 100 | } 101 | 102 | func TestMapclaimsVerifyExpiresAtInvalidTypeString(t *testing.T) { 103 | mapClaims := MapClaims{ 104 | "exp": "foo", 105 | } 106 | want := false 107 | got := NewValidator().Validate(mapClaims) 108 | 109 | if want != (got == nil) { 110 | t.Fatalf("Failed to verify claims, wanted: %v got %v", want, (got == nil)) 111 | } 112 | } 113 | 114 | func TestMapClaimsVerifyExpiresAtExpire(t *testing.T) { 115 | exp := time.Now() 116 | mapClaims := MapClaims{ 117 | "exp": float64(exp.Unix()), 118 | } 119 | want := false 120 | got := NewValidator(WithTimeFunc(func() time.Time { 121 | return exp 122 | })).Validate(mapClaims) 123 | if want != (got == nil) { 124 | t.Fatalf("Failed to verify claims, wanted: %v got %v", want, (got == nil)) 125 | } 126 | 127 | got = NewValidator(WithTimeFunc(func() time.Time { 128 | return exp.Add(1 * time.Second) 129 | })).Validate(mapClaims) 130 | if want != (got == nil) { 131 | t.Fatalf("Failed to verify claims, wanted: %v got %v", want, (got == nil)) 132 | } 133 | 134 | want = true 135 | got = NewValidator(WithTimeFunc(func() time.Time { 136 | return exp.Add(-1 * time.Second) 137 | })).Validate(mapClaims) 138 | if want != (got == nil) { 139 | t.Fatalf("Failed to verify claims, wanted: %v got %v", want, (got == nil)) 140 | } 141 | } 142 | 143 | func TestMapClaims_parseString(t *testing.T) { 144 | type args struct { 145 | key string 146 | } 147 | tests := []struct { 148 | name string 149 | m MapClaims 150 | args args 151 | want string 152 | wantErr bool 153 | }{ 154 | { 155 | name: "missing key", 156 | m: MapClaims{}, 157 | args: args{ 158 | key: "mykey", 159 | }, 160 | want: "", 161 | wantErr: false, 162 | }, 163 | { 164 | name: "wrong key type", 165 | m: MapClaims{"mykey": 4}, 166 | args: args{ 167 | key: "mykey", 168 | }, 169 | want: "", 170 | wantErr: true, 171 | }, 172 | { 173 | name: "correct key type", 174 | m: MapClaims{"mykey": "mystring"}, 175 | args: args{ 176 | key: "mykey", 177 | }, 178 | want: "mystring", 179 | wantErr: false, 180 | }, 181 | } 182 | for _, tt := range tests { 183 | t.Run(tt.name, func(t *testing.T) { 184 | got, err := tt.m.parseString(tt.args.key) 185 | if (err != nil) != tt.wantErr { 186 | t.Errorf("MapClaims.parseString() error = %v, wantErr %v", err, tt.wantErr) 187 | return 188 | } 189 | if got != tt.want { 190 | t.Errorf("MapClaims.parseString() = %v, want %v", got, tt.want) 191 | } 192 | }) 193 | } 194 | } 195 | -------------------------------------------------------------------------------- /none.go: -------------------------------------------------------------------------------- 1 | package jwt 2 | 3 | // SigningMethodNone implements the none signing method. This is required by the spec 4 | // but you probably should never use it. 5 | var SigningMethodNone *signingMethodNone 6 | 7 | const UnsafeAllowNoneSignatureType unsafeNoneMagicConstant = "none signing method allowed" 8 | 9 | var NoneSignatureTypeDisallowedError error 10 | 11 | type signingMethodNone struct{} 12 | type unsafeNoneMagicConstant string 13 | 14 | func init() { 15 | SigningMethodNone = &signingMethodNone{} 16 | NoneSignatureTypeDisallowedError = newError("'none' signature type is not allowed", ErrTokenUnverifiable) 17 | 18 | RegisterSigningMethod(SigningMethodNone.Alg(), func() SigningMethod { 19 | return SigningMethodNone 20 | }) 21 | } 22 | 23 | func (m *signingMethodNone) Alg() string { 24 | return "none" 25 | } 26 | 27 | // Only allow 'none' alg type if UnsafeAllowNoneSignatureType is specified as the key 28 | func (m *signingMethodNone) Verify(signingString string, sig []byte, key interface{}) (err error) { 29 | // Key must be UnsafeAllowNoneSignatureType to prevent accidentally 30 | // accepting 'none' signing method 31 | if _, ok := key.(unsafeNoneMagicConstant); !ok { 32 | return NoneSignatureTypeDisallowedError 33 | } 34 | // If signing method is none, signature must be an empty string 35 | if len(sig) != 0 { 36 | return newError("'none' signing method with non-empty signature", ErrTokenUnverifiable) 37 | } 38 | 39 | // Accept 'none' signing method. 40 | return nil 41 | } 42 | 43 | // Only allow 'none' signing if UnsafeAllowNoneSignatureType is specified as the key 44 | func (m *signingMethodNone) Sign(signingString string, key interface{}) ([]byte, error) { 45 | if _, ok := key.(unsafeNoneMagicConstant); ok { 46 | return []byte{}, nil 47 | } 48 | 49 | return nil, NoneSignatureTypeDisallowedError 50 | } 51 | -------------------------------------------------------------------------------- /none_test.go: -------------------------------------------------------------------------------- 1 | package jwt_test 2 | 3 | import ( 4 | "reflect" 5 | "strings" 6 | "testing" 7 | 8 | "github.com/golang-jwt/jwt/v5" 9 | ) 10 | 11 | var noneTestData = []struct { 12 | name string 13 | tokenString string 14 | alg string 15 | key interface{} 16 | claims map[string]interface{} 17 | valid bool 18 | }{ 19 | { 20 | "Basic", 21 | "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJmb28iOiJiYXIifQ.", 22 | "none", 23 | jwt.UnsafeAllowNoneSignatureType, 24 | map[string]interface{}{"foo": "bar"}, 25 | true, 26 | }, 27 | { 28 | "Basic - no key", 29 | "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJmb28iOiJiYXIifQ.", 30 | "none", 31 | nil, 32 | map[string]interface{}{"foo": "bar"}, 33 | false, 34 | }, 35 | { 36 | "Signed", 37 | "eyJhbGciOiJSUzM4NCIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIifQ.W-jEzRfBigtCWsinvVVuldiuilzVdU5ty0MvpLaSaqK9PlAWWlDQ1VIQ_qSKzwL5IXaZkvZFJXT3yL3n7OUVu7zCNJzdwznbC8Z-b0z2lYvcklJYi2VOFRcGbJtXUqgjk2oGsiqUMUMOLP70TTefkpsgqDxbRh9CDUfpOJgW-dU7cmgaoswe3wjUAUi6B6G2YEaiuXC0XScQYSYVKIzgKXJV8Zw-7AN_DBUI4GkTpsvQ9fVVjZM9csQiEXhYekyrKu1nu_POpQonGd8yqkIyXPECNmmqH5jH4sFiF67XhD7_JpkvLziBpI-uh86evBUadmHhb9Otqw3uV3NTaXLzJw", 38 | "none", 39 | jwt.UnsafeAllowNoneSignatureType, 40 | map[string]interface{}{"foo": "bar"}, 41 | false, 42 | }, 43 | } 44 | 45 | func TestNoneVerify(t *testing.T) { 46 | for _, data := range noneTestData { 47 | parts := strings.Split(data.tokenString, ".") 48 | 49 | method := jwt.GetSigningMethod(data.alg) 50 | err := method.Verify(strings.Join(parts[0:2], "."), decodeSegment(t, parts[2]), data.key) 51 | if data.valid && err != nil { 52 | t.Errorf("[%v] Error while verifying key: %v", data.name, err) 53 | } 54 | if !data.valid && err == nil { 55 | t.Errorf("[%v] Invalid key passed validation", data.name) 56 | } 57 | } 58 | } 59 | 60 | func TestNoneSign(t *testing.T) { 61 | for _, data := range noneTestData { 62 | if !data.valid { 63 | continue 64 | } 65 | parts := strings.Split(data.tokenString, ".") 66 | method := jwt.GetSigningMethod(data.alg) 67 | sig, err := method.Sign(strings.Join(parts[0:2], "."), data.key) 68 | if err != nil { 69 | t.Errorf("[%v] Error signing token: %v", data.name, err) 70 | } 71 | if !reflect.DeepEqual(sig, decodeSegment(t, parts[2])) { 72 | t.Errorf("[%v] Incorrect signature.\nwas:\n%v\nexpecting:\n%v", data.name, sig, parts[2]) 73 | } 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /parser.go: -------------------------------------------------------------------------------- 1 | package jwt 2 | 3 | import ( 4 | "bytes" 5 | "encoding/base64" 6 | "encoding/json" 7 | "fmt" 8 | "strings" 9 | ) 10 | 11 | const tokenDelimiter = "." 12 | 13 | type Parser struct { 14 | // If populated, only these methods will be considered valid. 15 | validMethods []string 16 | 17 | // Use JSON Number format in JSON decoder. 18 | useJSONNumber bool 19 | 20 | // Skip claims validation during token parsing. 21 | skipClaimsValidation bool 22 | 23 | validator *Validator 24 | 25 | decodeStrict bool 26 | 27 | decodePaddingAllowed bool 28 | } 29 | 30 | // NewParser creates a new Parser with the specified options 31 | func NewParser(options ...ParserOption) *Parser { 32 | p := &Parser{ 33 | validator: &Validator{}, 34 | } 35 | 36 | // Loop through our parsing options and apply them 37 | for _, option := range options { 38 | option(p) 39 | } 40 | 41 | return p 42 | } 43 | 44 | // Parse parses, validates, verifies the signature and returns the parsed token. 45 | // keyFunc will receive the parsed token and should return the key for validating. 46 | func (p *Parser) Parse(tokenString string, keyFunc Keyfunc) (*Token, error) { 47 | return p.ParseWithClaims(tokenString, MapClaims{}, keyFunc) 48 | } 49 | 50 | // ParseWithClaims parses, validates, and verifies like Parse, but supplies a default object implementing the Claims 51 | // interface. This provides default values which can be overridden and allows a caller to use their own type, rather 52 | // than the default MapClaims implementation of Claims. 53 | // 54 | // Note: If you provide a custom claim implementation that embeds one of the standard claims (such as RegisteredClaims), 55 | // make sure that a) you either embed a non-pointer version of the claims or b) if you are using a pointer, allocate the 56 | // proper memory for it before passing in the overall claims, otherwise you might run into a panic. 57 | func (p *Parser) ParseWithClaims(tokenString string, claims Claims, keyFunc Keyfunc) (*Token, error) { 58 | token, parts, err := p.ParseUnverified(tokenString, claims) 59 | if err != nil { 60 | return token, err 61 | } 62 | 63 | // Verify signing method is in the required set 64 | if p.validMethods != nil { 65 | var signingMethodValid = false 66 | var alg = token.Method.Alg() 67 | for _, m := range p.validMethods { 68 | if m == alg { 69 | signingMethodValid = true 70 | break 71 | } 72 | } 73 | if !signingMethodValid { 74 | // signing method is not in the listed set 75 | return token, newError(fmt.Sprintf("signing method %v is invalid", alg), ErrTokenSignatureInvalid) 76 | } 77 | } 78 | 79 | // Decode signature 80 | token.Signature, err = p.DecodeSegment(parts[2]) 81 | if err != nil { 82 | return token, newError("could not base64 decode signature", ErrTokenMalformed, err) 83 | } 84 | text := strings.Join(parts[0:2], ".") 85 | 86 | // Lookup key(s) 87 | if keyFunc == nil { 88 | // keyFunc was not provided. short circuiting validation 89 | return token, newError("no keyfunc was provided", ErrTokenUnverifiable) 90 | } 91 | 92 | got, err := keyFunc(token) 93 | if err != nil { 94 | return token, newError("error while executing keyfunc", ErrTokenUnverifiable, err) 95 | } 96 | 97 | switch have := got.(type) { 98 | case VerificationKeySet: 99 | if len(have.Keys) == 0 { 100 | return token, newError("keyfunc returned empty verification key set", ErrTokenUnverifiable) 101 | } 102 | // Iterate through keys and verify signature, skipping the rest when a match is found. 103 | // Return the last error if no match is found. 104 | for _, key := range have.Keys { 105 | if err = token.Method.Verify(text, token.Signature, key); err == nil { 106 | break 107 | } 108 | } 109 | default: 110 | err = token.Method.Verify(text, token.Signature, have) 111 | } 112 | if err != nil { 113 | return token, newError("", ErrTokenSignatureInvalid, err) 114 | } 115 | 116 | // Validate Claims 117 | if !p.skipClaimsValidation { 118 | // Make sure we have at least a default validator 119 | if p.validator == nil { 120 | p.validator = NewValidator() 121 | } 122 | 123 | if err := p.validator.Validate(claims); err != nil { 124 | return token, newError("", ErrTokenInvalidClaims, err) 125 | } 126 | } 127 | 128 | // No errors so far, token is valid. 129 | token.Valid = true 130 | 131 | return token, nil 132 | } 133 | 134 | // ParseUnverified parses the token but doesn't validate the signature. 135 | // 136 | // WARNING: Don't use this method unless you know what you're doing. 137 | // 138 | // It's only ever useful in cases where you know the signature is valid (since it has already 139 | // been or will be checked elsewhere in the stack) and you want to extract values from it. 140 | func (p *Parser) ParseUnverified(tokenString string, claims Claims) (token *Token, parts []string, err error) { 141 | var ok bool 142 | parts, ok = splitToken(tokenString) 143 | if !ok { 144 | return nil, nil, newError("token contains an invalid number of segments", ErrTokenMalformed) 145 | } 146 | 147 | token = &Token{Raw: tokenString} 148 | 149 | // parse Header 150 | var headerBytes []byte 151 | if headerBytes, err = p.DecodeSegment(parts[0]); err != nil { 152 | return token, parts, newError("could not base64 decode header", ErrTokenMalformed, err) 153 | } 154 | if err = json.Unmarshal(headerBytes, &token.Header); err != nil { 155 | return token, parts, newError("could not JSON decode header", ErrTokenMalformed, err) 156 | } 157 | 158 | // parse Claims 159 | token.Claims = claims 160 | 161 | claimBytes, err := p.DecodeSegment(parts[1]) 162 | if err != nil { 163 | return token, parts, newError("could not base64 decode claim", ErrTokenMalformed, err) 164 | } 165 | 166 | // If `useJSONNumber` is enabled then we must use *json.Decoder to decode 167 | // the claims. However, this comes with a performance penalty so only use 168 | // it if we must and, otherwise, simple use json.Unmarshal. 169 | if !p.useJSONNumber { 170 | // JSON Unmarshal. Special case for map type to avoid weird pointer behavior. 171 | if c, ok := token.Claims.(MapClaims); ok { 172 | err = json.Unmarshal(claimBytes, &c) 173 | } else { 174 | err = json.Unmarshal(claimBytes, &claims) 175 | } 176 | } else { 177 | dec := json.NewDecoder(bytes.NewBuffer(claimBytes)) 178 | dec.UseNumber() 179 | // JSON Decode. Special case for map type to avoid weird pointer behavior. 180 | if c, ok := token.Claims.(MapClaims); ok { 181 | err = dec.Decode(&c) 182 | } else { 183 | err = dec.Decode(&claims) 184 | } 185 | } 186 | if err != nil { 187 | return token, parts, newError("could not JSON decode claim", ErrTokenMalformed, err) 188 | } 189 | 190 | // Lookup signature method 191 | if method, ok := token.Header["alg"].(string); ok { 192 | if token.Method = GetSigningMethod(method); token.Method == nil { 193 | return token, parts, newError("signing method (alg) is unavailable", ErrTokenUnverifiable) 194 | } 195 | } else { 196 | return token, parts, newError("signing method (alg) is unspecified", ErrTokenUnverifiable) 197 | } 198 | 199 | return token, parts, nil 200 | } 201 | 202 | // splitToken splits a token string into three parts: header, claims, and signature. It will only 203 | // return true if the token contains exactly two delimiters and three parts. In all other cases, it 204 | // will return nil parts and false. 205 | func splitToken(token string) ([]string, bool) { 206 | parts := make([]string, 3) 207 | header, remain, ok := strings.Cut(token, tokenDelimiter) 208 | if !ok { 209 | return nil, false 210 | } 211 | parts[0] = header 212 | claims, remain, ok := strings.Cut(remain, tokenDelimiter) 213 | if !ok { 214 | return nil, false 215 | } 216 | parts[1] = claims 217 | // One more cut to ensure the signature is the last part of the token and there are no more 218 | // delimiters. This avoids an issue where malicious input could contain additional delimiters 219 | // causing unecessary overhead parsing tokens. 220 | signature, _, unexpected := strings.Cut(remain, tokenDelimiter) 221 | if unexpected { 222 | return nil, false 223 | } 224 | parts[2] = signature 225 | 226 | return parts, true 227 | } 228 | 229 | // DecodeSegment decodes a JWT specific base64url encoding. This function will 230 | // take into account whether the [Parser] is configured with additional options, 231 | // such as [WithStrictDecoding] or [WithPaddingAllowed]. 232 | func (p *Parser) DecodeSegment(seg string) ([]byte, error) { 233 | encoding := base64.RawURLEncoding 234 | 235 | if p.decodePaddingAllowed { 236 | if l := len(seg) % 4; l > 0 { 237 | seg += strings.Repeat("=", 4-l) 238 | } 239 | encoding = base64.URLEncoding 240 | } 241 | 242 | if p.decodeStrict { 243 | encoding = encoding.Strict() 244 | } 245 | return encoding.DecodeString(seg) 246 | } 247 | 248 | // Parse parses, validates, verifies the signature and returns the parsed token. 249 | // keyFunc will receive the parsed token and should return the cryptographic key 250 | // for verifying the signature. The caller is strongly encouraged to set the 251 | // WithValidMethods option to validate the 'alg' claim in the token matches the 252 | // expected algorithm. For more details about the importance of validating the 253 | // 'alg' claim, see 254 | // https://auth0.com/blog/critical-vulnerabilities-in-json-web-token-libraries/ 255 | func Parse(tokenString string, keyFunc Keyfunc, options ...ParserOption) (*Token, error) { 256 | return NewParser(options...).Parse(tokenString, keyFunc) 257 | } 258 | 259 | // ParseWithClaims is a shortcut for NewParser().ParseWithClaims(). 260 | // 261 | // Note: If you provide a custom claim implementation that embeds one of the 262 | // standard claims (such as RegisteredClaims), make sure that a) you either 263 | // embed a non-pointer version of the claims or b) if you are using a pointer, 264 | // allocate the proper memory for it before passing in the overall claims, 265 | // otherwise you might run into a panic. 266 | func ParseWithClaims(tokenString string, claims Claims, keyFunc Keyfunc, options ...ParserOption) (*Token, error) { 267 | return NewParser(options...).ParseWithClaims(tokenString, claims, keyFunc) 268 | } 269 | -------------------------------------------------------------------------------- /parser_option.go: -------------------------------------------------------------------------------- 1 | package jwt 2 | 3 | import "time" 4 | 5 | // ParserOption is used to implement functional-style options that modify the 6 | // behavior of the parser. To add new options, just create a function (ideally 7 | // beginning with With or Without) that returns an anonymous function that takes 8 | // a *Parser type as input and manipulates its configuration accordingly. 9 | type ParserOption func(*Parser) 10 | 11 | // WithValidMethods is an option to supply algorithm methods that the parser 12 | // will check. Only those methods will be considered valid. It is heavily 13 | // encouraged to use this option in order to prevent attacks such as 14 | // https://auth0.com/blog/critical-vulnerabilities-in-json-web-token-libraries/. 15 | func WithValidMethods(methods []string) ParserOption { 16 | return func(p *Parser) { 17 | p.validMethods = methods 18 | } 19 | } 20 | 21 | // WithJSONNumber is an option to configure the underlying JSON parser with 22 | // UseNumber. 23 | func WithJSONNumber() ParserOption { 24 | return func(p *Parser) { 25 | p.useJSONNumber = true 26 | } 27 | } 28 | 29 | // WithoutClaimsValidation is an option to disable claims validation. This 30 | // option should only be used if you exactly know what you are doing. 31 | func WithoutClaimsValidation() ParserOption { 32 | return func(p *Parser) { 33 | p.skipClaimsValidation = true 34 | } 35 | } 36 | 37 | // WithLeeway returns the ParserOption for specifying the leeway window. 38 | func WithLeeway(leeway time.Duration) ParserOption { 39 | return func(p *Parser) { 40 | p.validator.leeway = leeway 41 | } 42 | } 43 | 44 | // WithTimeFunc returns the ParserOption for specifying the time func. The 45 | // primary use-case for this is testing. If you are looking for a way to account 46 | // for clock-skew, WithLeeway should be used instead. 47 | func WithTimeFunc(f func() time.Time) ParserOption { 48 | return func(p *Parser) { 49 | p.validator.timeFunc = f 50 | } 51 | } 52 | 53 | // WithIssuedAt returns the ParserOption to enable verification 54 | // of issued-at. 55 | func WithIssuedAt() ParserOption { 56 | return func(p *Parser) { 57 | p.validator.verifyIat = true 58 | } 59 | } 60 | 61 | // WithExpirationRequired returns the ParserOption to make exp claim required. 62 | // By default exp claim is optional. 63 | func WithExpirationRequired() ParserOption { 64 | return func(p *Parser) { 65 | p.validator.requireExp = true 66 | } 67 | } 68 | 69 | // WithAudience configures the validator to require any of the specified 70 | // audiences in the `aud` claim. Validation will fail if the audience is not 71 | // listed in the token or the `aud` claim is missing. 72 | // 73 | // NOTE: While the `aud` claim is OPTIONAL in a JWT, the handling of it is 74 | // application-specific. Since this validation API is helping developers in 75 | // writing secure application, we decided to REQUIRE the existence of the claim, 76 | // if an audience is expected. 77 | func WithAudience(aud ...string) ParserOption { 78 | return func(p *Parser) { 79 | p.validator.expectedAud = aud 80 | } 81 | } 82 | 83 | // WithAllAudiences configures the validator to require all the specified 84 | // audiences in the `aud` claim. Validation will fail if the specified audiences 85 | // are not listed in the token or the `aud` claim is missing. Duplicates within 86 | // the list are de-duplicated since internally, we use a map to look up the 87 | // audiences. 88 | // 89 | // NOTE: While the `aud` claim is OPTIONAL in a JWT, the handling of it is 90 | // application-specific. Since this validation API is helping developers in 91 | // writing secure application, we decided to REQUIRE the existence of the claim, 92 | // if an audience is expected. 93 | func WithAllAudiences(aud ...string) ParserOption { 94 | return func(p *Parser) { 95 | p.validator.expectedAud = aud 96 | p.validator.expectAllAud = true 97 | } 98 | } 99 | 100 | // WithIssuer configures the validator to require the specified issuer in the 101 | // `iss` claim. Validation will fail if a different issuer is specified in the 102 | // token or the `iss` claim is missing. 103 | // 104 | // NOTE: While the `iss` claim is OPTIONAL in a JWT, the handling of it is 105 | // application-specific. Since this validation API is helping developers in 106 | // writing secure application, we decided to REQUIRE the existence of the claim, 107 | // if an issuer is expected. 108 | func WithIssuer(iss string) ParserOption { 109 | return func(p *Parser) { 110 | p.validator.expectedIss = iss 111 | } 112 | } 113 | 114 | // WithSubject configures the validator to require the specified subject in the 115 | // `sub` claim. Validation will fail if a different subject is specified in the 116 | // token or the `sub` claim is missing. 117 | // 118 | // NOTE: While the `sub` claim is OPTIONAL in a JWT, the handling of it is 119 | // application-specific. Since this validation API is helping developers in 120 | // writing secure application, we decided to REQUIRE the existence of the claim, 121 | // if a subject is expected. 122 | func WithSubject(sub string) ParserOption { 123 | return func(p *Parser) { 124 | p.validator.expectedSub = sub 125 | } 126 | } 127 | 128 | // WithPaddingAllowed will enable the codec used for decoding JWTs to allow 129 | // padding. Note that the JWS RFC7515 states that the tokens will utilize a 130 | // Base64url encoding with no padding. Unfortunately, some implementations of 131 | // JWT are producing non-standard tokens, and thus require support for decoding. 132 | func WithPaddingAllowed() ParserOption { 133 | return func(p *Parser) { 134 | p.decodePaddingAllowed = true 135 | } 136 | } 137 | 138 | // WithStrictDecoding will switch the codec used for decoding JWTs into strict 139 | // mode. In this mode, the decoder requires that trailing padding bits are zero, 140 | // as described in RFC 4648 section 3.5. 141 | func WithStrictDecoding() ParserOption { 142 | return func(p *Parser) { 143 | p.decodeStrict = true 144 | } 145 | } 146 | -------------------------------------------------------------------------------- /registered_claims.go: -------------------------------------------------------------------------------- 1 | package jwt 2 | 3 | // RegisteredClaims are a structured version of the JWT Claims Set, 4 | // restricted to Registered Claim Names, as referenced at 5 | // https://datatracker.ietf.org/doc/html/rfc7519#section-4.1 6 | // 7 | // This type can be used on its own, but then additional private and 8 | // public claims embedded in the JWT will not be parsed. The typical use-case 9 | // therefore is to embedded this in a user-defined claim type. 10 | // 11 | // See examples for how to use this with your own claim types. 12 | type RegisteredClaims struct { 13 | // the `iss` (Issuer) claim. See https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.1 14 | Issuer string `json:"iss,omitempty"` 15 | 16 | // the `sub` (Subject) claim. See https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.2 17 | Subject string `json:"sub,omitempty"` 18 | 19 | // the `aud` (Audience) claim. See https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.3 20 | Audience ClaimStrings `json:"aud,omitempty"` 21 | 22 | // the `exp` (Expiration Time) claim. See https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.4 23 | ExpiresAt *NumericDate `json:"exp,omitempty"` 24 | 25 | // the `nbf` (Not Before) claim. See https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.5 26 | NotBefore *NumericDate `json:"nbf,omitempty"` 27 | 28 | // the `iat` (Issued At) claim. See https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.6 29 | IssuedAt *NumericDate `json:"iat,omitempty"` 30 | 31 | // the `jti` (JWT ID) claim. See https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.7 32 | ID string `json:"jti,omitempty"` 33 | } 34 | 35 | // GetExpirationTime implements the Claims interface. 36 | func (c RegisteredClaims) GetExpirationTime() (*NumericDate, error) { 37 | return c.ExpiresAt, nil 38 | } 39 | 40 | // GetNotBefore implements the Claims interface. 41 | func (c RegisteredClaims) GetNotBefore() (*NumericDate, error) { 42 | return c.NotBefore, nil 43 | } 44 | 45 | // GetIssuedAt implements the Claims interface. 46 | func (c RegisteredClaims) GetIssuedAt() (*NumericDate, error) { 47 | return c.IssuedAt, nil 48 | } 49 | 50 | // GetAudience implements the Claims interface. 51 | func (c RegisteredClaims) GetAudience() (ClaimStrings, error) { 52 | return c.Audience, nil 53 | } 54 | 55 | // GetIssuer implements the Claims interface. 56 | func (c RegisteredClaims) GetIssuer() (string, error) { 57 | return c.Issuer, nil 58 | } 59 | 60 | // GetSubject implements the Claims interface. 61 | func (c RegisteredClaims) GetSubject() (string, error) { 62 | return c.Subject, nil 63 | } 64 | -------------------------------------------------------------------------------- /request/doc.go: -------------------------------------------------------------------------------- 1 | // Utility package for extracting JWT tokens from 2 | // HTTP requests. 3 | // 4 | // The main function is ParseFromRequest and it's WithClaims variant. 5 | // See examples for how to use the various Extractor implementations 6 | // or roll your own. 7 | package request 8 | -------------------------------------------------------------------------------- /request/extractor.go: -------------------------------------------------------------------------------- 1 | package request 2 | 3 | import ( 4 | "errors" 5 | "net/http" 6 | "strings" 7 | ) 8 | 9 | // Errors 10 | var ( 11 | ErrNoTokenInRequest = errors.New("no token present in request") 12 | ) 13 | 14 | // Extractor is an interface for extracting a token from an HTTP request. 15 | // The ExtractToken method should return a token string or an error. 16 | // If no token is present, you must return ErrNoTokenInRequest. 17 | type Extractor interface { 18 | ExtractToken(*http.Request) (string, error) 19 | } 20 | 21 | // HeaderExtractor is an extractor for finding a token in a header. 22 | // Looks at each specified header in order until there's a match 23 | type HeaderExtractor []string 24 | 25 | func (e HeaderExtractor) ExtractToken(req *http.Request) (string, error) { 26 | // loop over header names and return the first one that contains data 27 | for _, header := range e { 28 | if ah := req.Header.Get(header); ah != "" { 29 | return ah, nil 30 | } 31 | } 32 | return "", ErrNoTokenInRequest 33 | } 34 | 35 | // ArgumentExtractor extracts a token from request arguments. This includes a POSTed form or 36 | // GET URL arguments. Argument names are tried in order until there's a match. 37 | // This extractor calls `ParseMultipartForm` on the request 38 | type ArgumentExtractor []string 39 | 40 | func (e ArgumentExtractor) ExtractToken(req *http.Request) (string, error) { 41 | // Make sure form is parsed. We are explicitly ignoring errors at this point 42 | _ = req.ParseMultipartForm(10e6) 43 | 44 | // loop over arg names and return the first one that contains data 45 | for _, arg := range e { 46 | if ah := req.Form.Get(arg); ah != "" { 47 | return ah, nil 48 | } 49 | } 50 | 51 | return "", ErrNoTokenInRequest 52 | } 53 | 54 | // MultiExtractor tries Extractors in order until one returns a token string or an error occurs 55 | type MultiExtractor []Extractor 56 | 57 | func (e MultiExtractor) ExtractToken(req *http.Request) (string, error) { 58 | // loop over header names and return the first one that contains data 59 | for _, extractor := range e { 60 | if tok, err := extractor.ExtractToken(req); tok != "" { 61 | return tok, nil 62 | } else if !errors.Is(err, ErrNoTokenInRequest) { 63 | return "", err 64 | } 65 | } 66 | return "", ErrNoTokenInRequest 67 | } 68 | 69 | // PostExtractionFilter wraps an Extractor in this to post-process the value before it's handed off. 70 | // See AuthorizationHeaderExtractor for an example 71 | type PostExtractionFilter struct { 72 | Extractor 73 | Filter func(string) (string, error) 74 | } 75 | 76 | func (e *PostExtractionFilter) ExtractToken(req *http.Request) (string, error) { 77 | if tok, err := e.Extractor.ExtractToken(req); tok != "" { 78 | return e.Filter(tok) 79 | } else { 80 | return "", err 81 | } 82 | } 83 | 84 | // BearerExtractor extracts a token from the Authorization header. 85 | // The header is expected to match the format "Bearer XX", where "XX" is the 86 | // JWT token. 87 | type BearerExtractor struct{} 88 | 89 | func (e BearerExtractor) ExtractToken(req *http.Request) (string, error) { 90 | tokenHeader := req.Header.Get("Authorization") 91 | // The usual convention is for "Bearer" to be title-cased. However, there's no 92 | // strict rule around this, and it's best to follow the robustness principle here. 93 | if len(tokenHeader) < 7 || !strings.EqualFold(tokenHeader[:7], "bearer ") { 94 | return "", ErrNoTokenInRequest 95 | } 96 | return tokenHeader[7:], nil 97 | } 98 | -------------------------------------------------------------------------------- /request/extractor_example_test.go: -------------------------------------------------------------------------------- 1 | package request 2 | 3 | import ( 4 | "fmt" 5 | "net/url" 6 | ) 7 | 8 | const ( 9 | exampleTokenA = "A" 10 | ) 11 | 12 | func ExampleHeaderExtractor() { 13 | req := makeExampleRequest("GET", "/", map[string]string{"Token": exampleTokenA}, nil) 14 | tokenString, err := HeaderExtractor{"Token"}.ExtractToken(req) 15 | if err == nil { 16 | fmt.Println(tokenString) 17 | } else { 18 | fmt.Println(err) 19 | } 20 | // Output: A 21 | } 22 | 23 | func ExampleArgumentExtractor() { 24 | req := makeExampleRequest("GET", "/", nil, url.Values{"token": {extractorTestTokenA}}) 25 | tokenString, err := ArgumentExtractor{"token"}.ExtractToken(req) 26 | if err == nil { 27 | fmt.Println(tokenString) 28 | } else { 29 | fmt.Println(err) 30 | } 31 | // Output: A 32 | } 33 | -------------------------------------------------------------------------------- /request/extractor_test.go: -------------------------------------------------------------------------------- 1 | package request 2 | 3 | import ( 4 | "fmt" 5 | "net/http" 6 | "net/url" 7 | "testing" 8 | ) 9 | 10 | var extractorTestTokenA = "A" 11 | var extractorTestTokenB = "B" 12 | 13 | var extractorTestData = []struct { 14 | name string 15 | extractor Extractor 16 | headers map[string]string 17 | query url.Values 18 | token string 19 | err error 20 | }{ 21 | { 22 | name: "simple header", 23 | extractor: HeaderExtractor{"Foo"}, 24 | headers: map[string]string{"Foo": extractorTestTokenA}, 25 | query: nil, 26 | token: extractorTestTokenA, 27 | err: nil, 28 | }, 29 | { 30 | name: "simple argument", 31 | extractor: ArgumentExtractor{"token"}, 32 | headers: map[string]string{}, 33 | query: url.Values{"token": {extractorTestTokenA}}, 34 | token: extractorTestTokenA, 35 | err: nil, 36 | }, 37 | { 38 | name: "multiple extractors", 39 | extractor: MultiExtractor{ 40 | HeaderExtractor{"Foo"}, 41 | ArgumentExtractor{"token"}, 42 | }, 43 | headers: map[string]string{"Foo": extractorTestTokenA}, 44 | query: url.Values{"token": {extractorTestTokenB}}, 45 | token: extractorTestTokenA, 46 | err: nil, 47 | }, 48 | { 49 | name: "simple miss", 50 | extractor: HeaderExtractor{"This-Header-Is-Not-Set"}, 51 | headers: map[string]string{"Foo": extractorTestTokenA}, 52 | query: nil, 53 | token: "", 54 | err: ErrNoTokenInRequest, 55 | }, 56 | { 57 | name: "filter", 58 | extractor: AuthorizationHeaderExtractor, 59 | headers: map[string]string{"Authorization": "Bearer " + extractorTestTokenA}, 60 | query: nil, 61 | token: extractorTestTokenA, 62 | err: nil, 63 | }, 64 | } 65 | 66 | func TestExtractor(t *testing.T) { 67 | // Bearer token request 68 | for _, data := range extractorTestData { 69 | // Make request from test struct 70 | r := makeExampleRequest("GET", "/", data.headers, data.query) 71 | 72 | // Test extractor 73 | token, err := data.extractor.ExtractToken(r) 74 | if token != data.token { 75 | t.Errorf("[%v] Expected token '%v'. Got '%v'", data.name, data.token, token) 76 | continue 77 | } 78 | if err != data.err { 79 | t.Errorf("[%v] Expected error '%v'. Got '%v'", data.name, data.err, err) 80 | continue 81 | } 82 | } 83 | } 84 | 85 | func makeExampleRequest(method, path string, headers map[string]string, urlArgs url.Values) *http.Request { 86 | r, _ := http.NewRequest(method, fmt.Sprintf("%v?%v", path, urlArgs.Encode()), nil) 87 | for k, v := range headers { 88 | r.Header.Set(k, v) 89 | } 90 | return r 91 | } 92 | 93 | func TestBearerExtractor(t *testing.T) { 94 | request := makeExampleRequest("POST", "https://example.com/", map[string]string{"Authorization": "Bearer ToKen"}, nil) 95 | token, err := BearerExtractor{}.ExtractToken(request) 96 | if err != nil || token != "ToKen" { 97 | t.Errorf("ExtractToken did not return token, returned: %v, %v", token, err) 98 | } 99 | 100 | request = makeExampleRequest("POST", "https://example.com/", map[string]string{"Authorization": "Bearo ToKen"}, nil) 101 | token, err = BearerExtractor{}.ExtractToken(request) 102 | if err == nil || token != "" { 103 | t.Errorf("ExtractToken did not return error, returned: %v, %v", token, err) 104 | } 105 | 106 | request = makeExampleRequest("POST", "https://example.com/", map[string]string{"Authorization": "BeArEr HeLO"}, nil) 107 | token, err = BearerExtractor{}.ExtractToken(request) 108 | if err != nil || token != "HeLO" { 109 | t.Errorf("ExtractToken did not return token, returned: %v, %v", token, err) 110 | } 111 | } 112 | -------------------------------------------------------------------------------- /request/oauth2.go: -------------------------------------------------------------------------------- 1 | package request 2 | 3 | import ( 4 | "strings" 5 | ) 6 | 7 | // Strips 'Bearer ' prefix from bearer token string 8 | func stripBearerPrefixFromTokenString(tok string) (string, error) { 9 | // Should be a bearer token 10 | if len(tok) > 6 && strings.EqualFold(tok[:7], "bearer ") { 11 | return tok[7:], nil 12 | } 13 | return tok, nil 14 | } 15 | 16 | // AuthorizationHeaderExtractor extracts a bearer token from Authorization header 17 | // Uses PostExtractionFilter to strip "Bearer " prefix from header 18 | var AuthorizationHeaderExtractor = &PostExtractionFilter{ 19 | HeaderExtractor{"Authorization"}, 20 | stripBearerPrefixFromTokenString, 21 | } 22 | 23 | // OAuth2Extractor is an Extractor for OAuth2 access tokens. Looks in 'Authorization' 24 | // header then 'access_token' argument for a token. 25 | var OAuth2Extractor = &MultiExtractor{ 26 | AuthorizationHeaderExtractor, 27 | ArgumentExtractor{"access_token"}, 28 | } 29 | -------------------------------------------------------------------------------- /request/request.go: -------------------------------------------------------------------------------- 1 | package request 2 | 3 | import ( 4 | "net/http" 5 | 6 | "github.com/golang-jwt/jwt/v5" 7 | ) 8 | 9 | // ParseFromRequest extracts and parses a JWT token from an HTTP request. 10 | // This behaves the same as Parse, but accepts a request and an extractor 11 | // instead of a token string. The Extractor interface allows you to define 12 | // the logic for extracting a token. Several useful implementations are provided. 13 | // 14 | // You can provide options to modify parsing behavior 15 | func ParseFromRequest(req *http.Request, extractor Extractor, keyFunc jwt.Keyfunc, options ...ParseFromRequestOption) (token *jwt.Token, err error) { 16 | // Create basic parser struct 17 | p := &fromRequestParser{req, extractor, nil, nil} 18 | 19 | // Handle options 20 | for _, option := range options { 21 | option(p) 22 | } 23 | 24 | // Set defaults 25 | if p.claims == nil { 26 | p.claims = jwt.MapClaims{} 27 | } 28 | if p.parser == nil { 29 | p.parser = &jwt.Parser{} 30 | } 31 | 32 | // perform extract 33 | tokenString, err := p.extractor.ExtractToken(req) 34 | if err != nil { 35 | return nil, err 36 | } 37 | 38 | // perform parse 39 | return p.parser.ParseWithClaims(tokenString, p.claims, keyFunc) 40 | } 41 | 42 | // ParseFromRequestWithClaims is an alias for ParseFromRequest but with custom Claims type. 43 | // 44 | // Deprecated: use ParseFromRequest and the WithClaims option 45 | func ParseFromRequestWithClaims(req *http.Request, extractor Extractor, claims jwt.Claims, keyFunc jwt.Keyfunc) (token *jwt.Token, err error) { 46 | return ParseFromRequest(req, extractor, keyFunc, WithClaims(claims)) 47 | } 48 | 49 | type fromRequestParser struct { 50 | req *http.Request 51 | extractor Extractor 52 | claims jwt.Claims 53 | parser *jwt.Parser 54 | } 55 | 56 | type ParseFromRequestOption func(*fromRequestParser) 57 | 58 | // WithClaims parses with custom claims 59 | func WithClaims(claims jwt.Claims) ParseFromRequestOption { 60 | return func(p *fromRequestParser) { 61 | p.claims = claims 62 | } 63 | } 64 | 65 | // WithParser parses using a custom parser 66 | func WithParser(parser *jwt.Parser) ParseFromRequestOption { 67 | return func(p *fromRequestParser) { 68 | p.parser = parser 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /request/request_test.go: -------------------------------------------------------------------------------- 1 | package request 2 | 3 | import ( 4 | "fmt" 5 | "net/http" 6 | "net/url" 7 | "reflect" 8 | "strings" 9 | "testing" 10 | 11 | "github.com/golang-jwt/jwt/v5" 12 | "github.com/golang-jwt/jwt/v5/test" 13 | ) 14 | 15 | var requestTestData = []struct { 16 | name string 17 | claims jwt.MapClaims 18 | extractor Extractor 19 | headers map[string]string 20 | query url.Values 21 | valid bool 22 | }{ 23 | { 24 | "authorization bearer token", 25 | jwt.MapClaims{"foo": "bar"}, 26 | AuthorizationHeaderExtractor, 27 | map[string]string{"Authorization": "Bearer %v"}, 28 | url.Values{}, 29 | true, 30 | }, 31 | { 32 | "oauth bearer token - header", 33 | jwt.MapClaims{"foo": "bar"}, 34 | OAuth2Extractor, 35 | map[string]string{"Authorization": "Bearer %v"}, 36 | url.Values{}, 37 | true, 38 | }, 39 | { 40 | "oauth bearer token - url", 41 | jwt.MapClaims{"foo": "bar"}, 42 | OAuth2Extractor, 43 | map[string]string{}, 44 | url.Values{"access_token": {"%v"}}, 45 | true, 46 | }, 47 | { 48 | "url token", 49 | jwt.MapClaims{"foo": "bar"}, 50 | ArgumentExtractor{"token"}, 51 | map[string]string{}, 52 | url.Values{"token": {"%v"}}, 53 | true, 54 | }, 55 | } 56 | 57 | func TestParseRequest(t *testing.T) { 58 | // load keys from disk 59 | privateKey := test.LoadRSAPrivateKeyFromDisk("../test/sample_key") 60 | publicKey := test.LoadRSAPublicKeyFromDisk("../test/sample_key.pub") 61 | keyfunc := func(*jwt.Token) (interface{}, error) { 62 | return publicKey, nil 63 | } 64 | 65 | // Bearer token request 66 | for _, data := range requestTestData { 67 | // Make token from claims 68 | tokenString := test.MakeSampleToken(data.claims, jwt.SigningMethodRS256, privateKey) 69 | 70 | // Make query string 71 | for k, vv := range data.query { 72 | for i, v := range vv { 73 | if strings.Contains(v, "%v") { 74 | data.query[k][i] = fmt.Sprintf(v, tokenString) 75 | } 76 | } 77 | } 78 | 79 | // Make request from test struct 80 | r, _ := http.NewRequest("GET", fmt.Sprintf("/?%v", data.query.Encode()), nil) 81 | for k, v := range data.headers { 82 | if strings.Contains(v, "%v") { 83 | r.Header.Set(k, fmt.Sprintf(v, tokenString)) 84 | } else { 85 | r.Header.Set(k, tokenString) 86 | } 87 | } 88 | token, err := ParseFromRequestWithClaims(r, data.extractor, jwt.MapClaims{}, keyfunc) 89 | 90 | if token == nil { 91 | t.Errorf("[%v] Token was not found: %v", data.name, err) 92 | continue 93 | } 94 | if !reflect.DeepEqual(data.claims, token.Claims) { 95 | t.Errorf("[%v] Claims mismatch. Expecting: %v Got: %v", data.name, data.claims, token.Claims) 96 | } 97 | if data.valid && err != nil { 98 | t.Errorf("[%v] Error while verifying token: %v", data.name, err) 99 | } 100 | if !data.valid && err == nil { 101 | t.Errorf("[%v] Invalid token passed validation", data.name) 102 | } 103 | } 104 | } 105 | -------------------------------------------------------------------------------- /rsa.go: -------------------------------------------------------------------------------- 1 | package jwt 2 | 3 | import ( 4 | "crypto" 5 | "crypto/rand" 6 | "crypto/rsa" 7 | ) 8 | 9 | // SigningMethodRSA implements the RSA family of signing methods. 10 | // Expects *rsa.PrivateKey for signing and *rsa.PublicKey for validation 11 | type SigningMethodRSA struct { 12 | Name string 13 | Hash crypto.Hash 14 | } 15 | 16 | // Specific instances for RS256 and company 17 | var ( 18 | SigningMethodRS256 *SigningMethodRSA 19 | SigningMethodRS384 *SigningMethodRSA 20 | SigningMethodRS512 *SigningMethodRSA 21 | ) 22 | 23 | func init() { 24 | // RS256 25 | SigningMethodRS256 = &SigningMethodRSA{"RS256", crypto.SHA256} 26 | RegisterSigningMethod(SigningMethodRS256.Alg(), func() SigningMethod { 27 | return SigningMethodRS256 28 | }) 29 | 30 | // RS384 31 | SigningMethodRS384 = &SigningMethodRSA{"RS384", crypto.SHA384} 32 | RegisterSigningMethod(SigningMethodRS384.Alg(), func() SigningMethod { 33 | return SigningMethodRS384 34 | }) 35 | 36 | // RS512 37 | SigningMethodRS512 = &SigningMethodRSA{"RS512", crypto.SHA512} 38 | RegisterSigningMethod(SigningMethodRS512.Alg(), func() SigningMethod { 39 | return SigningMethodRS512 40 | }) 41 | } 42 | 43 | func (m *SigningMethodRSA) Alg() string { 44 | return m.Name 45 | } 46 | 47 | // Verify implements token verification for the SigningMethod 48 | // For this signing method, must be an *rsa.PublicKey structure. 49 | func (m *SigningMethodRSA) Verify(signingString string, sig []byte, key interface{}) error { 50 | var rsaKey *rsa.PublicKey 51 | var ok bool 52 | 53 | if rsaKey, ok = key.(*rsa.PublicKey); !ok { 54 | return newError("RSA verify expects *rsa.PublicKey", ErrInvalidKeyType) 55 | } 56 | 57 | // Create hasher 58 | if !m.Hash.Available() { 59 | return ErrHashUnavailable 60 | } 61 | hasher := m.Hash.New() 62 | hasher.Write([]byte(signingString)) 63 | 64 | // Verify the signature 65 | return rsa.VerifyPKCS1v15(rsaKey, m.Hash, hasher.Sum(nil), sig) 66 | } 67 | 68 | // Sign implements token signing for the SigningMethod 69 | // For this signing method, must be an *rsa.PrivateKey structure. 70 | func (m *SigningMethodRSA) Sign(signingString string, key interface{}) ([]byte, error) { 71 | var rsaKey *rsa.PrivateKey 72 | var ok bool 73 | 74 | // Validate type of key 75 | if rsaKey, ok = key.(*rsa.PrivateKey); !ok { 76 | return nil, newError("RSA sign expects *rsa.PrivateKey", ErrInvalidKeyType) 77 | } 78 | 79 | // Create the hasher 80 | if !m.Hash.Available() { 81 | return nil, ErrHashUnavailable 82 | } 83 | 84 | hasher := m.Hash.New() 85 | hasher.Write([]byte(signingString)) 86 | 87 | // Sign the string and return the encoded bytes 88 | if sigBytes, err := rsa.SignPKCS1v15(rand.Reader, rsaKey, m.Hash, hasher.Sum(nil)); err == nil { 89 | return sigBytes, nil 90 | } else { 91 | return nil, err 92 | } 93 | } 94 | -------------------------------------------------------------------------------- /rsa_pss.go: -------------------------------------------------------------------------------- 1 | //go:build go1.4 2 | // +build go1.4 3 | 4 | package jwt 5 | 6 | import ( 7 | "crypto" 8 | "crypto/rand" 9 | "crypto/rsa" 10 | ) 11 | 12 | // SigningMethodRSAPSS implements the RSAPSS family of signing methods signing methods 13 | type SigningMethodRSAPSS struct { 14 | *SigningMethodRSA 15 | Options *rsa.PSSOptions 16 | // VerifyOptions is optional. If set overrides Options for rsa.VerifyPPS. 17 | // Used to accept tokens signed with rsa.PSSSaltLengthAuto, what doesn't follow 18 | // https://tools.ietf.org/html/rfc7518#section-3.5 but was used previously. 19 | // See https://github.com/dgrijalva/jwt-go/issues/285#issuecomment-437451244 for details. 20 | VerifyOptions *rsa.PSSOptions 21 | } 22 | 23 | // Specific instances for RS/PS and company. 24 | var ( 25 | SigningMethodPS256 *SigningMethodRSAPSS 26 | SigningMethodPS384 *SigningMethodRSAPSS 27 | SigningMethodPS512 *SigningMethodRSAPSS 28 | ) 29 | 30 | func init() { 31 | // PS256 32 | SigningMethodPS256 = &SigningMethodRSAPSS{ 33 | SigningMethodRSA: &SigningMethodRSA{ 34 | Name: "PS256", 35 | Hash: crypto.SHA256, 36 | }, 37 | Options: &rsa.PSSOptions{ 38 | SaltLength: rsa.PSSSaltLengthEqualsHash, 39 | }, 40 | VerifyOptions: &rsa.PSSOptions{ 41 | SaltLength: rsa.PSSSaltLengthAuto, 42 | }, 43 | } 44 | RegisterSigningMethod(SigningMethodPS256.Alg(), func() SigningMethod { 45 | return SigningMethodPS256 46 | }) 47 | 48 | // PS384 49 | SigningMethodPS384 = &SigningMethodRSAPSS{ 50 | SigningMethodRSA: &SigningMethodRSA{ 51 | Name: "PS384", 52 | Hash: crypto.SHA384, 53 | }, 54 | Options: &rsa.PSSOptions{ 55 | SaltLength: rsa.PSSSaltLengthEqualsHash, 56 | }, 57 | VerifyOptions: &rsa.PSSOptions{ 58 | SaltLength: rsa.PSSSaltLengthAuto, 59 | }, 60 | } 61 | RegisterSigningMethod(SigningMethodPS384.Alg(), func() SigningMethod { 62 | return SigningMethodPS384 63 | }) 64 | 65 | // PS512 66 | SigningMethodPS512 = &SigningMethodRSAPSS{ 67 | SigningMethodRSA: &SigningMethodRSA{ 68 | Name: "PS512", 69 | Hash: crypto.SHA512, 70 | }, 71 | Options: &rsa.PSSOptions{ 72 | SaltLength: rsa.PSSSaltLengthEqualsHash, 73 | }, 74 | VerifyOptions: &rsa.PSSOptions{ 75 | SaltLength: rsa.PSSSaltLengthAuto, 76 | }, 77 | } 78 | RegisterSigningMethod(SigningMethodPS512.Alg(), func() SigningMethod { 79 | return SigningMethodPS512 80 | }) 81 | } 82 | 83 | // Verify implements token verification for the SigningMethod. 84 | // For this verify method, key must be an rsa.PublicKey struct 85 | func (m *SigningMethodRSAPSS) Verify(signingString string, sig []byte, key interface{}) error { 86 | var rsaKey *rsa.PublicKey 87 | switch k := key.(type) { 88 | case *rsa.PublicKey: 89 | rsaKey = k 90 | default: 91 | return newError("RSA-PSS verify expects *rsa.PublicKey", ErrInvalidKeyType) 92 | } 93 | 94 | // Create hasher 95 | if !m.Hash.Available() { 96 | return ErrHashUnavailable 97 | } 98 | hasher := m.Hash.New() 99 | hasher.Write([]byte(signingString)) 100 | 101 | opts := m.Options 102 | if m.VerifyOptions != nil { 103 | opts = m.VerifyOptions 104 | } 105 | 106 | return rsa.VerifyPSS(rsaKey, m.Hash, hasher.Sum(nil), sig, opts) 107 | } 108 | 109 | // Sign implements token signing for the SigningMethod. 110 | // For this signing method, key must be an rsa.PrivateKey struct 111 | func (m *SigningMethodRSAPSS) Sign(signingString string, key interface{}) ([]byte, error) { 112 | var rsaKey *rsa.PrivateKey 113 | 114 | switch k := key.(type) { 115 | case *rsa.PrivateKey: 116 | rsaKey = k 117 | default: 118 | return nil, newError("RSA-PSS sign expects *rsa.PrivateKey", ErrInvalidKeyType) 119 | } 120 | 121 | // Create the hasher 122 | if !m.Hash.Available() { 123 | return nil, ErrHashUnavailable 124 | } 125 | 126 | hasher := m.Hash.New() 127 | hasher.Write([]byte(signingString)) 128 | 129 | // Sign the string and return the encoded bytes 130 | if sigBytes, err := rsa.SignPSS(rand.Reader, rsaKey, m.Hash, hasher.Sum(nil), m.Options); err == nil { 131 | return sigBytes, nil 132 | } else { 133 | return nil, err 134 | } 135 | } 136 | -------------------------------------------------------------------------------- /rsa_pss_test.go: -------------------------------------------------------------------------------- 1 | //go:build go1.4 2 | // +build go1.4 3 | 4 | package jwt_test 5 | 6 | import ( 7 | "crypto/rsa" 8 | "os" 9 | "strings" 10 | "testing" 11 | "time" 12 | 13 | "github.com/golang-jwt/jwt/v5" 14 | "github.com/golang-jwt/jwt/v5/test" 15 | ) 16 | 17 | var rsaPSSTestData = []struct { 18 | name string 19 | tokenString string 20 | alg string 21 | claims map[string]interface{} 22 | valid bool 23 | }{ 24 | { 25 | "Basic PS256", 26 | "eyJhbGciOiJQUzI1NiIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIifQ.PPG4xyDVY8ffp4CcxofNmsTDXsrVG2npdQuibLhJbv4ClyPTUtR5giNSvuxo03kB6I8VXVr0Y9X7UxhJVEoJOmULAwRWaUsDnIewQa101cVhMa6iR8X37kfFoiZ6NkS-c7henVkkQWu2HtotkEtQvN5hFlk8IevXXPmvZlhQhwzB1sGzGYnoi1zOfuL98d3BIjUjtlwii5w6gYG2AEEzp7HnHCsb3jIwUPdq86Oe6hIFjtBwduIK90ca4UqzARpcfwxHwVLMpatKask00AgGVI0ysdk0BLMjmLutquD03XbThHScC2C2_Pp4cHWgMzvbgLU2RYYZcZRKr46QeNgz9w", 27 | "PS256", 28 | map[string]interface{}{"foo": "bar"}, 29 | true, 30 | }, 31 | { 32 | "Basic PS384", 33 | "eyJhbGciOiJQUzM4NCIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIifQ.w7-qqgj97gK4fJsq_DCqdYQiylJjzWONvD0qWWWhqEOFk2P1eDULPnqHRnjgTXoO4HAw4YIWCsZPet7nR3Xxq4ZhMqvKW8b7KlfRTb9cH8zqFvzMmybQ4jv2hKc3bXYqVow3AoR7hN_CWXI3Dv6Kd2X5xhtxRHI6IL39oTVDUQ74LACe-9t4c3QRPuj6Pq1H4FAT2E2kW_0KOc6EQhCLWEhm2Z2__OZskDC8AiPpP8Kv4k2vB7l0IKQu8Pr4RcNBlqJdq8dA5D3hk5TLxP8V5nG1Ib80MOMMqoS3FQvSLyolFX-R_jZ3-zfq6Ebsqr0yEb0AH2CfsECF7935Pa0FKQ", 34 | "PS384", 35 | map[string]interface{}{"foo": "bar"}, 36 | true, 37 | }, 38 | { 39 | "Basic PS512", 40 | "eyJhbGciOiJQUzUxMiIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIifQ.GX1HWGzFaJevuSLavqqFYaW8_TpvcjQ8KfC5fXiSDzSiT9UD9nB_ikSmDNyDILNdtjZLSvVKfXxZJqCfefxAtiozEDDdJthZ-F0uO4SPFHlGiXszvKeodh7BuTWRI2wL9-ZO4mFa8nq3GMeQAfo9cx11i7nfN8n2YNQ9SHGovG7_T_AvaMZB_jT6jkDHpwGR9mz7x1sycckEo6teLdHRnH_ZdlHlxqknmyTu8Odr5Xh0sJFOL8BepWbbvIIn-P161rRHHiDWFv6nhlHwZnVzjx7HQrWSGb6-s2cdLie9QL_8XaMcUpjLkfOMKkDOfHo6AvpL7Jbwi83Z2ZTHjJWB-A", 41 | "PS512", 42 | map[string]interface{}{"foo": "bar"}, 43 | true, 44 | }, 45 | { 46 | "basic PS256 invalid: foo => bar", 47 | "eyJhbGciOiJQUzI1NiIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIifQ.PPG4xyDVY8ffp4CcxofNmsTDXsrVG2npdQuibLhJbv4ClyPTUtR5giNSvuxo03kB6I8VXVr0Y9X7UxhJVEoJOmULAwRWaUsDnIewQa101cVhMa6iR8X37kfFoiZ6NkS-c7henVkkQWu2HtotkEtQvN5hFlk8IevXXPmvZlhQhwzB1sGzGYnoi1zOfuL98d3BIjUjtlwii5w6gYG2AEEzp7HnHCsb3jIwUPdq86Oe6hIFjtBwduIK90ca4UqzARpcfwxHwVLMpatKask00AgGVI0ysdk0BLMjmLutquD03XbThHScC2C2_Pp4cHWgMzvbgLU2RYYZcZRKr46QeNgz9W", 48 | "PS256", 49 | map[string]interface{}{"foo": "bar"}, 50 | false, 51 | }, 52 | } 53 | 54 | func TestRSAPSSVerify(t *testing.T) { 55 | var err error 56 | 57 | key, _ := os.ReadFile("test/sample_key.pub") 58 | var rsaPSSKey *rsa.PublicKey 59 | if rsaPSSKey, err = jwt.ParseRSAPublicKeyFromPEM(key); err != nil { 60 | t.Errorf("Unable to parse RSA public key: %v", err) 61 | } 62 | 63 | for _, data := range rsaPSSTestData { 64 | parts := strings.Split(data.tokenString, ".") 65 | 66 | method := jwt.GetSigningMethod(data.alg) 67 | err := method.Verify(strings.Join(parts[0:2], "."), decodeSegment(t, parts[2]), rsaPSSKey) 68 | if data.valid && err != nil { 69 | t.Errorf("[%v] Error while verifying key: %v", data.name, err) 70 | } 71 | if !data.valid && err == nil { 72 | t.Errorf("[%v] Invalid key passed validation", data.name) 73 | } 74 | } 75 | } 76 | 77 | func TestRSAPSSSign(t *testing.T) { 78 | var err error 79 | 80 | key, _ := os.ReadFile("test/sample_key") 81 | var rsaPSSKey *rsa.PrivateKey 82 | if rsaPSSKey, err = jwt.ParseRSAPrivateKeyFromPEM(key); err != nil { 83 | t.Errorf("Unable to parse RSA private key: %v", err) 84 | } 85 | 86 | for _, data := range rsaPSSTestData { 87 | if !data.valid { 88 | continue 89 | } 90 | parts := strings.Split(data.tokenString, ".") 91 | method := jwt.GetSigningMethod(data.alg) 92 | sig, err := method.Sign(strings.Join(parts[0:2], "."), rsaPSSKey) 93 | if err != nil { 94 | t.Errorf("[%v] Error signing token: %v", data.name, err) 95 | } 96 | 97 | ssig := encodeSegment(sig) 98 | if ssig == parts[2] { 99 | t.Errorf("[%v] Signatures shouldn't match\nnew:\n%v\noriginal:\n%v", data.name, ssig, parts[2]) 100 | } 101 | } 102 | } 103 | 104 | func TestRSAPSSSaltLengthCompatibility(t *testing.T) { 105 | // Fails token verify, if salt length is auto. 106 | ps256SaltLengthEqualsHash := &jwt.SigningMethodRSAPSS{ 107 | SigningMethodRSA: jwt.SigningMethodPS256.SigningMethodRSA, 108 | Options: &rsa.PSSOptions{ 109 | SaltLength: rsa.PSSSaltLengthEqualsHash, 110 | }, 111 | } 112 | 113 | // Behaves as before https://github.com/dgrijalva/jwt-go/issues/285 fix. 114 | ps256SaltLengthAuto := &jwt.SigningMethodRSAPSS{ 115 | SigningMethodRSA: jwt.SigningMethodPS256.SigningMethodRSA, 116 | Options: &rsa.PSSOptions{ 117 | SaltLength: rsa.PSSSaltLengthAuto, 118 | }, 119 | } 120 | if !verify(t, jwt.SigningMethodPS256, makeToken(ps256SaltLengthEqualsHash)) { 121 | t.Error("SigningMethodPS256 should accept salt length that is defined in RFC") 122 | } 123 | if !verify(t, ps256SaltLengthEqualsHash, makeToken(jwt.SigningMethodPS256)) { 124 | t.Error("Sign by SigningMethodPS256 should have salt length that is defined in RFC") 125 | } 126 | if !verify(t, jwt.SigningMethodPS256, makeToken(ps256SaltLengthAuto)) { 127 | t.Error("SigningMethodPS256 should accept auto salt length to be compatible with previous versions") 128 | } 129 | if !verify(t, ps256SaltLengthAuto, makeToken(jwt.SigningMethodPS256)) { 130 | t.Error("Sign by SigningMethodPS256 should be accepted by previous versions") 131 | } 132 | if verify(t, ps256SaltLengthEqualsHash, makeToken(ps256SaltLengthAuto)) { 133 | t.Error("Auto salt length should be not accepted, when RFC salt length is required") 134 | } 135 | } 136 | 137 | func makeToken(method jwt.SigningMethod) string { 138 | token := jwt.NewWithClaims(method, jwt.RegisteredClaims{ 139 | Issuer: "example", 140 | IssuedAt: jwt.NewNumericDate(time.Now()), 141 | }) 142 | privateKey := test.LoadRSAPrivateKeyFromDisk("test/sample_key") 143 | signed, err := token.SignedString(privateKey) 144 | if err != nil { 145 | panic(err) 146 | } 147 | return signed 148 | } 149 | 150 | func verify(t *testing.T, signingMethod jwt.SigningMethod, token string) bool { 151 | segments := strings.Split(token, ".") 152 | err := signingMethod.Verify(strings.Join(segments[:2], "."), decodeSegment(t, segments[2]), test.LoadRSAPublicKeyFromDisk("test/sample_key.pub")) 153 | return err == nil 154 | } 155 | -------------------------------------------------------------------------------- /rsa_test.go: -------------------------------------------------------------------------------- 1 | package jwt_test 2 | 3 | import ( 4 | "bytes" 5 | "crypto/rand" 6 | "crypto/rsa" 7 | "crypto/x509" 8 | "encoding/pem" 9 | "os" 10 | "reflect" 11 | "strings" 12 | "testing" 13 | 14 | "github.com/golang-jwt/jwt/v5" 15 | ) 16 | 17 | var rsaTestData = []struct { 18 | name string 19 | tokenString string 20 | alg string 21 | valid bool 22 | }{ 23 | { 24 | "Basic RS256", 25 | "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJmb28iOiJiYXIifQ.FhkiHkoESI_cG3NPigFrxEk9Z60_oXrOT2vGm9Pn6RDgYNovYORQmmA0zs1AoAOf09ly2Nx2YAg6ABqAYga1AcMFkJljwxTT5fYphTuqpWdy4BELeSYJx5Ty2gmr8e7RonuUztrdD5WfPqLKMm1Ozp_T6zALpRmwTIW0QPnaBXaQD90FplAg46Iy1UlDKr-Eupy0i5SLch5Q-p2ZpaL_5fnTIUDlxC3pWhJTyx_71qDI-mAA_5lE_VdroOeflG56sSmDxopPEG3bFlSu1eowyBfxtu0_CuVd-M42RU75Zc4Gsj6uV77MBtbMrf4_7M_NUTSgoIF3fRqxrj0NzihIBg", 26 | "RS256", 27 | true, 28 | }, 29 | { 30 | "Basic RS384", 31 | "eyJhbGciOiJSUzM4NCIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIifQ.W-jEzRfBigtCWsinvVVuldiuilzVdU5ty0MvpLaSaqK9PlAWWlDQ1VIQ_qSKzwL5IXaZkvZFJXT3yL3n7OUVu7zCNJzdwznbC8Z-b0z2lYvcklJYi2VOFRcGbJtXUqgjk2oGsiqUMUMOLP70TTefkpsgqDxbRh9CDUfpOJgW-dU7cmgaoswe3wjUAUi6B6G2YEaiuXC0XScQYSYVKIzgKXJV8Zw-7AN_DBUI4GkTpsvQ9fVVjZM9csQiEXhYekyrKu1nu_POpQonGd8yqkIyXPECNmmqH5jH4sFiF67XhD7_JpkvLziBpI-uh86evBUadmHhb9Otqw3uV3NTaXLzJw", 32 | "RS384", 33 | true, 34 | }, 35 | { 36 | "Basic RS512", 37 | "eyJhbGciOiJSUzUxMiIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIifQ.zBlLlmRrUxx4SJPUbV37Q1joRcI9EW13grnKduK3wtYKmDXbgDpF1cZ6B-2Jsm5RB8REmMiLpGms-EjXhgnyh2TSHE-9W2gA_jvshegLWtwRVDX40ODSkTb7OVuaWgiy9y7llvcknFBTIg-FnVPVpXMmeV_pvwQyhaz1SSwSPrDyxEmksz1hq7YONXhXPpGaNbMMeDTNP_1oj8DZaqTIL9TwV8_1wb2Odt_Fy58Ke2RVFijsOLdnyEAjt2n9Mxihu9i3PhNBkkxa2GbnXBfq3kzvZ_xxGGopLdHhJjcGWXO-NiwI9_tiu14NRv4L2xC0ItD9Yz68v2ZIZEp_DuzwRQ", 38 | "RS512", 39 | true, 40 | }, 41 | { 42 | "basic invalid: foo => bar", 43 | "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJmb28iOiJiYXIifQ.EhkiHkoESI_cG3NPigFrxEk9Z60_oXrOT2vGm9Pn6RDgYNovYORQmmA0zs1AoAOf09ly2Nx2YAg6ABqAYga1AcMFkJljwxTT5fYphTuqpWdy4BELeSYJx5Ty2gmr8e7RonuUztrdD5WfPqLKMm1Ozp_T6zALpRmwTIW0QPnaBXaQD90FplAg46Iy1UlDKr-Eupy0i5SLch5Q-p2ZpaL_5fnTIUDlxC3pWhJTyx_71qDI-mAA_5lE_VdroOeflG56sSmDxopPEG3bFlSu1eowyBfxtu0_CuVd-M42RU75Zc4Gsj6uV77MBtbMrf4_7M_NUTSgoIF3fRqxrj0NzihIBg", 44 | "RS256", 45 | false, 46 | }, 47 | } 48 | 49 | func TestRSAVerify(t *testing.T) { 50 | keyData, _ := os.ReadFile("test/sample_key.pub") 51 | key, _ := jwt.ParseRSAPublicKeyFromPEM(keyData) 52 | 53 | for _, data := range rsaTestData { 54 | parts := strings.Split(data.tokenString, ".") 55 | 56 | method := jwt.GetSigningMethod(data.alg) 57 | err := method.Verify(strings.Join(parts[0:2], "."), decodeSegment(t, parts[2]), key) 58 | if data.valid && err != nil { 59 | t.Errorf("[%v] Error while verifying key: %v", data.name, err) 60 | } 61 | if !data.valid && err == nil { 62 | t.Errorf("[%v] Invalid key passed validation", data.name) 63 | } 64 | } 65 | } 66 | 67 | func TestRSASign(t *testing.T) { 68 | keyData, _ := os.ReadFile("test/sample_key") 69 | key, _ := jwt.ParseRSAPrivateKeyFromPEM(keyData) 70 | 71 | for _, data := range rsaTestData { 72 | if data.valid { 73 | parts := strings.Split(data.tokenString, ".") 74 | method := jwt.GetSigningMethod(data.alg) 75 | sig, err := method.Sign(strings.Join(parts[0:2], "."), key) 76 | if err != nil { 77 | t.Errorf("[%v] Error signing token: %v", data.name, err) 78 | } 79 | if !reflect.DeepEqual(sig, decodeSegment(t, parts[2])) { 80 | t.Errorf("[%v] Incorrect signature.\nwas:\n%v\nexpecting:\n%v", data.name, sig, parts[2]) 81 | } 82 | } 83 | } 84 | } 85 | 86 | func TestRSAVerifyWithPreParsedPrivateKey(t *testing.T) { 87 | key, _ := os.ReadFile("test/sample_key.pub") 88 | parsedKey, err := jwt.ParseRSAPublicKeyFromPEM(key) 89 | if err != nil { 90 | t.Fatal(err) 91 | } 92 | testData := rsaTestData[0] 93 | parts := strings.Split(testData.tokenString, ".") 94 | err = jwt.SigningMethodRS256.Verify(strings.Join(parts[0:2], "."), decodeSegment(t, parts[2]), parsedKey) 95 | if err != nil { 96 | t.Errorf("[%v] Error while verifying key: %v", testData.name, err) 97 | } 98 | } 99 | 100 | func TestRSAWithPreParsedPrivateKey(t *testing.T) { 101 | key, _ := os.ReadFile("test/sample_key") 102 | parsedKey, err := jwt.ParseRSAPrivateKeyFromPEM(key) 103 | if err != nil { 104 | t.Fatal(err) 105 | } 106 | testData := rsaTestData[0] 107 | parts := strings.Split(testData.tokenString, ".") 108 | sig, err := jwt.SigningMethodRS256.Sign(strings.Join(parts[0:2], "."), parsedKey) 109 | if err != nil { 110 | t.Errorf("[%v] Error signing token: %v", testData.name, err) 111 | } 112 | if !reflect.DeepEqual(sig, decodeSegment(t, parts[2])) { 113 | t.Errorf("[%v] Incorrect signature.\nwas:\n%v\nexpecting:\n%v", testData.name, sig, parts[2]) 114 | } 115 | } 116 | 117 | func TestRSAKeyParsing(t *testing.T) { 118 | key, _ := os.ReadFile("test/sample_key") 119 | secureKey, _ := os.ReadFile("test/privateSecure.pem") 120 | pubKey, _ := os.ReadFile("test/sample_key.pub") 121 | badKey := []byte("All your base are belong to key") 122 | 123 | randomKey, err := rsa.GenerateKey(rand.Reader, 2048) 124 | if err != nil { 125 | t.Errorf("Failed to generate RSA private key: %v", err) 126 | } 127 | 128 | publicKeyBytes := x509.MarshalPKCS1PublicKey(&randomKey.PublicKey) 129 | pkcs1Buffer := new(bytes.Buffer) 130 | if err = pem.Encode(pkcs1Buffer, &pem.Block{Type: "RSA PUBLIC KEY", Bytes: publicKeyBytes}); err != nil { 131 | t.Errorf("Failed to encode public pem: %v", err) 132 | } 133 | 134 | // Test parsePrivateKey 135 | if _, e := jwt.ParseRSAPrivateKeyFromPEM(key); e != nil { 136 | t.Errorf("Failed to parse valid private key: %v", e) 137 | } 138 | 139 | if k, e := jwt.ParseRSAPrivateKeyFromPEM(pubKey); e == nil { 140 | t.Errorf("Parsed public key as valid private key: %v", k) 141 | } 142 | 143 | if k, e := jwt.ParseRSAPrivateKeyFromPEM(badKey); e == nil { 144 | t.Errorf("Parsed invalid key as valid private key: %v", k) 145 | } 146 | 147 | if _, e := jwt.ParseRSAPrivateKeyFromPEMWithPassword(secureKey, "password"); e != nil { 148 | t.Errorf("Failed to parse valid private key with password: %v", e) 149 | } 150 | 151 | if k, e := jwt.ParseRSAPrivateKeyFromPEMWithPassword(secureKey, "123132"); e == nil { 152 | t.Errorf("Parsed private key with invalid password %v", k) 153 | } 154 | 155 | // Test parsePublicKey 156 | if _, e := jwt.ParseRSAPublicKeyFromPEM(pubKey); e != nil { 157 | t.Errorf("Failed to parse valid public key: %v", e) 158 | } 159 | 160 | if k, e := jwt.ParseRSAPublicKeyFromPEM(key); e == nil { 161 | t.Errorf("Parsed private key as valid public key: %v", k) 162 | } 163 | 164 | if k, e := jwt.ParseRSAPublicKeyFromPEM(badKey); e == nil { 165 | t.Errorf("Parsed invalid key as valid private key: %v", k) 166 | } 167 | 168 | if _, err := jwt.ParseRSAPublicKeyFromPEM(pkcs1Buffer.Bytes()); err != nil { 169 | t.Errorf("failed to parse RSA public key: %v", err) 170 | } 171 | } 172 | 173 | func BenchmarkRSAParsing(b *testing.B) { 174 | key, _ := os.ReadFile("test/sample_key") 175 | 176 | b.ReportAllocs() 177 | b.ResetTimer() 178 | b.RunParallel(func(pb *testing.PB) { 179 | for pb.Next() { 180 | if _, err := jwt.ParseRSAPrivateKeyFromPEM(key); err != nil { 181 | b.Fatalf("Unable to parse RSA private key: %v", err) 182 | } 183 | } 184 | }) 185 | } 186 | 187 | func BenchmarkRS256Signing(b *testing.B) { 188 | key, _ := os.ReadFile("test/sample_key") 189 | parsedKey, err := jwt.ParseRSAPrivateKeyFromPEM(key) 190 | if err != nil { 191 | b.Fatal(err) 192 | } 193 | 194 | benchmarkSigning(b, jwt.SigningMethodRS256, parsedKey) 195 | } 196 | 197 | func BenchmarkRS384Signing(b *testing.B) { 198 | key, _ := os.ReadFile("test/sample_key") 199 | parsedKey, err := jwt.ParseRSAPrivateKeyFromPEM(key) 200 | if err != nil { 201 | b.Fatal(err) 202 | } 203 | 204 | benchmarkSigning(b, jwt.SigningMethodRS384, parsedKey) 205 | } 206 | 207 | func BenchmarkRS512Signing(b *testing.B) { 208 | key, _ := os.ReadFile("test/sample_key") 209 | parsedKey, err := jwt.ParseRSAPrivateKeyFromPEM(key) 210 | if err != nil { 211 | b.Fatal(err) 212 | } 213 | 214 | benchmarkSigning(b, jwt.SigningMethodRS512, parsedKey) 215 | } 216 | -------------------------------------------------------------------------------- /rsa_utils.go: -------------------------------------------------------------------------------- 1 | package jwt 2 | 3 | import ( 4 | "crypto/rsa" 5 | "crypto/x509" 6 | "encoding/pem" 7 | "errors" 8 | ) 9 | 10 | var ( 11 | ErrKeyMustBePEMEncoded = errors.New("invalid key: Key must be a PEM encoded PKCS1 or PKCS8 key") 12 | ErrNotRSAPrivateKey = errors.New("key is not a valid RSA private key") 13 | ErrNotRSAPublicKey = errors.New("key is not a valid RSA public key") 14 | ) 15 | 16 | // ParseRSAPrivateKeyFromPEM parses a PEM encoded PKCS1 or PKCS8 private key 17 | func ParseRSAPrivateKeyFromPEM(key []byte) (*rsa.PrivateKey, error) { 18 | var err error 19 | 20 | // Parse PEM block 21 | var block *pem.Block 22 | if block, _ = pem.Decode(key); block == nil { 23 | return nil, ErrKeyMustBePEMEncoded 24 | } 25 | 26 | var parsedKey interface{} 27 | if parsedKey, err = x509.ParsePKCS1PrivateKey(block.Bytes); err != nil { 28 | if parsedKey, err = x509.ParsePKCS8PrivateKey(block.Bytes); err != nil { 29 | return nil, err 30 | } 31 | } 32 | 33 | var pkey *rsa.PrivateKey 34 | var ok bool 35 | if pkey, ok = parsedKey.(*rsa.PrivateKey); !ok { 36 | return nil, ErrNotRSAPrivateKey 37 | } 38 | 39 | return pkey, nil 40 | } 41 | 42 | // ParseRSAPrivateKeyFromPEMWithPassword parses a PEM encoded PKCS1 or PKCS8 private key protected with password 43 | // 44 | // Deprecated: This function is deprecated and should not be used anymore. It uses the deprecated x509.DecryptPEMBlock 45 | // function, which was deprecated since RFC 1423 is regarded insecure by design. Unfortunately, there is no alternative 46 | // in the Go standard library for now. See https://github.com/golang/go/issues/8860. 47 | func ParseRSAPrivateKeyFromPEMWithPassword(key []byte, password string) (*rsa.PrivateKey, error) { 48 | var err error 49 | 50 | // Parse PEM block 51 | var block *pem.Block 52 | if block, _ = pem.Decode(key); block == nil { 53 | return nil, ErrKeyMustBePEMEncoded 54 | } 55 | 56 | var parsedKey interface{} 57 | 58 | var blockDecrypted []byte 59 | if blockDecrypted, err = x509.DecryptPEMBlock(block, []byte(password)); err != nil { 60 | return nil, err 61 | } 62 | 63 | if parsedKey, err = x509.ParsePKCS1PrivateKey(blockDecrypted); err != nil { 64 | if parsedKey, err = x509.ParsePKCS8PrivateKey(blockDecrypted); err != nil { 65 | return nil, err 66 | } 67 | } 68 | 69 | var pkey *rsa.PrivateKey 70 | var ok bool 71 | if pkey, ok = parsedKey.(*rsa.PrivateKey); !ok { 72 | return nil, ErrNotRSAPrivateKey 73 | } 74 | 75 | return pkey, nil 76 | } 77 | 78 | // ParseRSAPublicKeyFromPEM parses a certificate or a PEM encoded PKCS1 or PKIX public key 79 | func ParseRSAPublicKeyFromPEM(key []byte) (*rsa.PublicKey, error) { 80 | var err error 81 | 82 | // Parse PEM block 83 | var block *pem.Block 84 | if block, _ = pem.Decode(key); block == nil { 85 | return nil, ErrKeyMustBePEMEncoded 86 | } 87 | 88 | // Parse the key 89 | var parsedKey interface{} 90 | if parsedKey, err = x509.ParsePKIXPublicKey(block.Bytes); err != nil { 91 | if cert, err := x509.ParseCertificate(block.Bytes); err == nil { 92 | parsedKey = cert.PublicKey 93 | } else { 94 | if parsedKey, err = x509.ParsePKCS1PublicKey(block.Bytes); err != nil { 95 | return nil, err 96 | } 97 | } 98 | } 99 | 100 | var pkey *rsa.PublicKey 101 | var ok bool 102 | if pkey, ok = parsedKey.(*rsa.PublicKey); !ok { 103 | return nil, ErrNotRSAPublicKey 104 | } 105 | 106 | return pkey, nil 107 | } 108 | -------------------------------------------------------------------------------- /signing_method.go: -------------------------------------------------------------------------------- 1 | package jwt 2 | 3 | import ( 4 | "sync" 5 | ) 6 | 7 | var signingMethods = map[string]func() SigningMethod{} 8 | var signingMethodLock = new(sync.RWMutex) 9 | 10 | // SigningMethod can be used add new methods for signing or verifying tokens. It 11 | // takes a decoded signature as an input in the Verify function and produces a 12 | // signature in Sign. The signature is then usually base64 encoded as part of a 13 | // JWT. 14 | type SigningMethod interface { 15 | Verify(signingString string, sig []byte, key interface{}) error // Returns nil if signature is valid 16 | Sign(signingString string, key interface{}) ([]byte, error) // Returns signature or error 17 | Alg() string // returns the alg identifier for this method (example: 'HS256') 18 | } 19 | 20 | // RegisterSigningMethod registers the "alg" name and a factory function for signing method. 21 | // This is typically done during init() in the method's implementation 22 | func RegisterSigningMethod(alg string, f func() SigningMethod) { 23 | signingMethodLock.Lock() 24 | defer signingMethodLock.Unlock() 25 | 26 | signingMethods[alg] = f 27 | } 28 | 29 | // GetSigningMethod retrieves a signing method from an "alg" string 30 | func GetSigningMethod(alg string) (method SigningMethod) { 31 | signingMethodLock.RLock() 32 | defer signingMethodLock.RUnlock() 33 | 34 | if methodF, ok := signingMethods[alg]; ok { 35 | method = methodF() 36 | } 37 | return 38 | } 39 | 40 | // GetAlgorithms returns a list of registered "alg" names 41 | func GetAlgorithms() (algs []string) { 42 | signingMethodLock.RLock() 43 | defer signingMethodLock.RUnlock() 44 | 45 | for alg := range signingMethods { 46 | algs = append(algs, alg) 47 | } 48 | return 49 | } 50 | -------------------------------------------------------------------------------- /staticcheck.conf: -------------------------------------------------------------------------------- 1 | checks = ["all", "-ST1000", "-ST1003", "-ST1016", "-ST1023"] 2 | -------------------------------------------------------------------------------- /test/ec256-private.pem: -------------------------------------------------------------------------------- 1 | -----BEGIN EC PRIVATE KEY----- 2 | MHcCAQEEIAh5qA3rmqQQuu0vbKV/+zouz/y/Iy2pLpIcWUSyImSwoAoGCCqGSM49 3 | AwEHoUQDQgAEYD54V/vp+54P9DXarYqx4MPcm+HKRIQzNasYSoRQHQ/6S6Ps8tpM 4 | cT+KvIIC8W/e9k0W7Cm72M1P9jU7SLf/vg== 5 | -----END EC PRIVATE KEY----- 6 | -------------------------------------------------------------------------------- /test/ec256-public.pem: -------------------------------------------------------------------------------- 1 | -----BEGIN PUBLIC KEY----- 2 | MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEYD54V/vp+54P9DXarYqx4MPcm+HK 3 | RIQzNasYSoRQHQ/6S6Ps8tpMcT+KvIIC8W/e9k0W7Cm72M1P9jU7SLf/vg== 4 | -----END PUBLIC KEY----- 5 | -------------------------------------------------------------------------------- /test/ec384-private.pem: -------------------------------------------------------------------------------- 1 | -----BEGIN EC PRIVATE KEY----- 2 | MIGkAgEBBDCaCvMHKhcG/qT7xsNLYnDT7sE/D+TtWIol1ROdaK1a564vx5pHbsRy 3 | SEKcIxISi1igBwYFK4EEACKhZANiAATYa7rJaU7feLMqrAx6adZFNQOpaUH/Uylb 4 | ZLriOLON5YFVwtVUpO1FfEXZUIQpptRPtc5ixIPY658yhBSb6irfIJUSP9aYTflJ 5 | GKk/mDkK4t8mWBzhiD5B6jg9cEGhGgA= 6 | -----END EC PRIVATE KEY----- 7 | -------------------------------------------------------------------------------- /test/ec384-public.pem: -------------------------------------------------------------------------------- 1 | -----BEGIN PUBLIC KEY----- 2 | MHYwEAYHKoZIzj0CAQYFK4EEACIDYgAE2Gu6yWlO33izKqwMemnWRTUDqWlB/1Mp 3 | W2S64jizjeWBVcLVVKTtRXxF2VCEKabUT7XOYsSD2OufMoQUm+oq3yCVEj/WmE35 4 | SRipP5g5CuLfJlgc4Yg+Qeo4PXBBoRoA 5 | -----END PUBLIC KEY----- 6 | -------------------------------------------------------------------------------- /test/ec512-private.pem: -------------------------------------------------------------------------------- 1 | -----BEGIN EC PRIVATE KEY----- 2 | MIHcAgEBBEIB0pE4uFaWRx7t03BsYlYvF1YvKaBGyvoakxnodm9ou0R9wC+sJAjH 3 | QZZJikOg4SwNqgQ/hyrOuDK2oAVHhgVGcYmgBwYFK4EEACOhgYkDgYYABAAJXIuw 4 | 12MUzpHggia9POBFYXSxaOGKGbMjIyDI+6q7wi7LMw3HgbaOmgIqFG72o8JBQwYN 5 | 4IbXHf+f86CRY1AA2wHzbHvt6IhkCXTNxBEffa1yMUgu8n9cKKF2iLgyQKcKqW33 6 | 8fGOw/n3Rm2Yd/EB56u2rnD29qS+nOM9eGS+gy39OQ== 7 | -----END EC PRIVATE KEY----- 8 | -------------------------------------------------------------------------------- /test/ec512-public.pem: -------------------------------------------------------------------------------- 1 | -----BEGIN PUBLIC KEY----- 2 | MIGbMBAGByqGSM49AgEGBSuBBAAjA4GGAAQACVyLsNdjFM6R4IImvTzgRWF0sWjh 3 | ihmzIyMgyPuqu8IuyzMNx4G2jpoCKhRu9qPCQUMGDeCG1x3/n/OgkWNQANsB82x7 4 | 7eiIZAl0zcQRH32tcjFILvJ/XCihdoi4MkCnCqlt9/HxjsP590ZtmHfxAeertq5w 5 | 9vakvpzjPXhkvoMt/Tk= 6 | -----END PUBLIC KEY----- 7 | -------------------------------------------------------------------------------- /test/ed25519-private.pem: -------------------------------------------------------------------------------- 1 | -----BEGIN PRIVATE KEY----- 2 | MC4CAQAwBQYDK2VwBCIEIEFMEZrmlYxczXKFxIlNvNGR5JQvDhTkLovJYxwQd3ua 3 | -----END PRIVATE KEY----- 4 | -------------------------------------------------------------------------------- /test/ed25519-public.pem: -------------------------------------------------------------------------------- 1 | -----BEGIN PUBLIC KEY----- 2 | MCowBQYDK2VwAyEAWH7z6hpYqvPns2i4n9yymwvB3APhi4LyQ7iHOT6crtE= 3 | -----END PUBLIC KEY----- 4 | -------------------------------------------------------------------------------- /test/examplePaddedKey-public.pem: -------------------------------------------------------------------------------- 1 | -----BEGIN PUBLIC KEY----- 2 | MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEIcaUjXhC7Mn2OonyfHF+zjblKkns 3 | 4GLbILnHrZr+aQwddiff5urCDAZ177t81Mn39CDs3uhlNDxfRIRheGnK/Q== 4 | -----END PUBLIC KEY----- -------------------------------------------------------------------------------- /test/helpers.go: -------------------------------------------------------------------------------- 1 | package test 2 | 3 | import ( 4 | "crypto" 5 | "crypto/rsa" 6 | "os" 7 | 8 | "github.com/golang-jwt/jwt/v5" 9 | ) 10 | 11 | func LoadRSAPrivateKeyFromDisk(location string) *rsa.PrivateKey { 12 | keyData, e := os.ReadFile(location) 13 | if e != nil { 14 | panic(e.Error()) 15 | } 16 | key, e := jwt.ParseRSAPrivateKeyFromPEM(keyData) 17 | if e != nil { 18 | panic(e.Error()) 19 | } 20 | return key 21 | } 22 | 23 | func LoadRSAPublicKeyFromDisk(location string) *rsa.PublicKey { 24 | keyData, e := os.ReadFile(location) 25 | if e != nil { 26 | panic(e.Error()) 27 | } 28 | key, e := jwt.ParseRSAPublicKeyFromPEM(keyData) 29 | if e != nil { 30 | panic(e.Error()) 31 | } 32 | return key 33 | } 34 | 35 | // MakeSampleToken creates and returns a encoded JWT token that has been signed with the specified cryptographic key. 36 | func MakeSampleToken(c jwt.Claims, method jwt.SigningMethod, key interface{}) string { 37 | token := jwt.NewWithClaims(method, c) 38 | s, e := token.SignedString(key) 39 | 40 | if e != nil { 41 | panic(e.Error()) 42 | } 43 | 44 | return s 45 | } 46 | 47 | func LoadECPrivateKeyFromDisk(location string) crypto.PrivateKey { 48 | keyData, e := os.ReadFile(location) 49 | if e != nil { 50 | panic(e.Error()) 51 | } 52 | key, e := jwt.ParseECPrivateKeyFromPEM(keyData) 53 | if e != nil { 54 | panic(e.Error()) 55 | } 56 | return key 57 | } 58 | 59 | func LoadECPublicKeyFromDisk(location string) crypto.PublicKey { 60 | keyData, e := os.ReadFile(location) 61 | if e != nil { 62 | panic(e.Error()) 63 | } 64 | key, e := jwt.ParseECPublicKeyFromPEM(keyData) 65 | if e != nil { 66 | panic(e.Error()) 67 | } 68 | return key 69 | } 70 | -------------------------------------------------------------------------------- /test/hmacTestKey: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/golang-jwt/jwt/048854f1b0ac96c0a843d52fc09d7878b853683f/test/hmacTestKey -------------------------------------------------------------------------------- /test/privateSecure.pem: -------------------------------------------------------------------------------- 1 | -----BEGIN RSA PRIVATE KEY----- 2 | Proc-Type: 4,ENCRYPTED 3 | DEK-Info: DES-EDE3-CBC,7487BB8910A3741B 4 | 5 | iL7m48mbFSIy1Y5xbXWwPTR07ufxu7o+myGUE+AdDeWWISkd5W6Gl44oX/jgXldS 6 | mL/ntUXoZzQz2WKEYLwssAtSTGF+QgSIMvV5faiP+pLYvWgk0oVr42po00CvADFL 7 | eDAJC7LgagYifS1l4EAK4MY8RGCHyJWEN5JAr0fc/Haa3WfWZ009kOWAp8MDuYxB 8 | hQlCKUmnUpXCp5c6jwbjlyinLj8XwzzjZ/rVRsY+t2Z0Vcd5qzR5BV8IJCqbG5Py 9 | z15/EFgMG2N2eYMsiEKgdXeKW2H5XIoWyun/3pBigWaDnTtiWSt9kz2MplqYfIT7 10 | F+0XE3gdDGalAeN3YwFPHCkxxBmcI+s6lQG9INmf2/gkJQ+MOZBVXKmGLv6Qis3l 11 | 0eyUz1yZvNzf0zlcUBjiPulLF3peThHMEzhSsATfPomyg5NJ0X7ttd0ybnq+sPe4 12 | qg2OJ8qNhYrqnx7Xlvj61+B2NAZVHvIioma1FzqX8DxQYrnR5S6DJExDqvzNxEz6 13 | 5VPQlH2Ig4hTvNzla84WgJ6USc/2SS4ehCReiNvfeNG9sPZKQnr/Ss8KPIYsKGcC 14 | Pz/vEqbWDmJwHb7KixCQKPt1EbD+/uf0YnhskOWM15YiFbYAOZKJ5rcbz2Zu66vg 15 | GAmqcBsHeFR3s/bObEzjxOmMfSr1vzvr4ActNJWVtfNKZNobSehZiMSHL54AXAZW 16 | Yj48pwTbf7b1sbF0FeCuwTFiYxM+yiZVO5ciYOfmo4HUg53PjknKpcKtEFSj02P1 17 | 8JRBSb++V0IeMDyZLl12zgURDsvualbJMMBBR8emIpF13h0qdyah431gDhHGBnnC 18 | J5UDGq21/flFjzz0x/Okjwf7mPK5pcmF+uW7AxtHqws6m93yD5+RFmfZ8cb/8CL8 19 | jmsQslj+OIE64ykkRoJWpNBKyQjL3CnPnLmAB6TQKxegR94C7/hP1FvRW+W0AgZy 20 | g2QczKQU3KBQP18Ui1HTbkOUJT0Lsy4FnmJFCB/STPRo6NlJiATKHq/cqHWQUvZd 21 | d4oTMb1opKfs7AI9wiJBuskpGAECdRnVduml3dT4p//3BiP6K9ImWMSJeFpjFAFs 22 | AbBMKyitMs0Fyn9AJRPl23TKVQ3cYeSTxus4wLmx5ECSsHRV6g06nYjBp4GWEqSX 23 | RVclXF3zmy3b1+O5s2chJN6TrypzYSEYXJb1vvQLK0lNXqwxZAFV7Roi6xSG0fSY 24 | EAtdUifLonu43EkrLh55KEwkXdVV8xneUjh+TF8VgJKMnqDFfeHFdmN53YYh3n3F 25 | kpYSmVLRzQmLbH9dY+7kqvnsQm8y76vjug3p4IbEbHp/fNGf+gv7KDng1HyCl9A+ 26 | Ow/Hlr0NqCAIhminScbRsZ4SgbRTRgGEYZXvyOtQa/uL6I8t2NR4W7ynispMs0QL 27 | RD61i3++bQXuTi4i8dg3yqIfe9S22NHSzZY/lAHAmmc3r5NrQ1TM1hsSxXawT5CU 28 | anWFjbH6YQ/QplkkAqZMpropWn6ZdNDg/+BUjukDs0HZrbdGy846WxQUvE7G2bAw 29 | IFQ1SymBZBtfnZXhfAXOHoWh017p6HsIkb2xmFrigMj7Jh10VVhdWg== 30 | -----END RSA PRIVATE KEY----- 31 | -------------------------------------------------------------------------------- /test/sample_key: -------------------------------------------------------------------------------- 1 | -----BEGIN RSA PRIVATE KEY----- 2 | MIIEowIBAAKCAQEA4f5wg5l2hKsTeNem/V41fGnJm6gOdrj8ym3rFkEU/wT8RDtn 3 | SgFEZOQpHEgQ7JL38xUfU0Y3g6aYw9QT0hJ7mCpz9Er5qLaMXJwZxzHzAahlfA0i 4 | cqabvJOMvQtzD6uQv6wPEyZtDTWiQi9AXwBpHssPnpYGIn20ZZuNlX2BrClciHhC 5 | PUIIZOQn/MmqTD31jSyjoQoV7MhhMTATKJx2XrHhR+1DcKJzQBSTAGnpYVaqpsAR 6 | ap+nwRipr3nUTuxyGohBTSmjJ2usSeQXHI3bODIRe1AuTyHceAbewn8b462yEWKA 7 | Rdpd9AjQW5SIVPfdsz5B6GlYQ5LdYKtznTuy7wIDAQABAoIBAQCwia1k7+2oZ2d3 8 | n6agCAbqIE1QXfCmh41ZqJHbOY3oRQG3X1wpcGH4Gk+O+zDVTV2JszdcOt7E5dAy 9 | MaomETAhRxB7hlIOnEN7WKm+dGNrKRvV0wDU5ReFMRHg31/Lnu8c+5BvGjZX+ky9 10 | POIhFFYJqwCRlopGSUIxmVj5rSgtzk3iWOQXr+ah1bjEXvlxDOWkHN6YfpV5ThdE 11 | KdBIPGEVqa63r9n2h+qazKrtiRqJqGnOrHzOECYbRFYhexsNFz7YT02xdfSHn7gM 12 | IvabDDP/Qp0PjE1jdouiMaFHYnLBbgvlnZW9yuVf/rpXTUq/njxIXMmvmEyyvSDn 13 | FcFikB8pAoGBAPF77hK4m3/rdGT7X8a/gwvZ2R121aBcdPwEaUhvj/36dx596zvY 14 | mEOjrWfZhF083/nYWE2kVquj2wjs+otCLfifEEgXcVPTnEOPO9Zg3uNSL0nNQghj 15 | FuD3iGLTUBCtM66oTe0jLSslHe8gLGEQqyMzHOzYxNqibxcOZIe8Qt0NAoGBAO+U 16 | I5+XWjWEgDmvyC3TrOSf/KCGjtu0TSv30ipv27bDLMrpvPmD/5lpptTFwcxvVhCs 17 | 2b+chCjlghFSWFbBULBrfci2FtliClOVMYrlNBdUSJhf3aYSG2Doe6Bgt1n2CpNn 18 | /iu37Y3NfemZBJA7hNl4dYe+f+uzM87cdQ214+jrAoGAXA0XxX8ll2+ToOLJsaNT 19 | OvNB9h9Uc5qK5X5w+7G7O998BN2PC/MWp8H+2fVqpXgNENpNXttkRm1hk1dych86 20 | EunfdPuqsX+as44oCyJGFHVBnWpm33eWQw9YqANRI+pCJzP08I5WK3osnPiwshd+ 21 | hR54yjgfYhBFNI7B95PmEQkCgYBzFSz7h1+s34Ycr8SvxsOBWxymG5zaCsUbPsL0 22 | 4aCgLScCHb9J+E86aVbbVFdglYa5Id7DPTL61ixhl7WZjujspeXZGSbmq0Kcnckb 23 | mDgqkLECiOJW2NHP/j0McAkDLL4tysF8TLDO8gvuvzNC+WQ6drO2ThrypLVZQ+ry 24 | eBIPmwKBgEZxhqa0gVvHQG/7Od69KWj4eJP28kq13RhKay8JOoN0vPmspXJo1HY3 25 | CKuHRG+AP579dncdUnOMvfXOtkdM4vk0+hWASBQzM9xzVcztCa+koAugjVaLS9A+ 26 | 9uQoqEeVNTckxx0S2bYevRy7hGQmUJTyQm3j1zEUR5jpdbL83Fbq 27 | -----END RSA PRIVATE KEY----- 28 | -------------------------------------------------------------------------------- /test/sample_key.pub: -------------------------------------------------------------------------------- 1 | -----BEGIN PUBLIC KEY----- 2 | MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA4f5wg5l2hKsTeNem/V41 3 | fGnJm6gOdrj8ym3rFkEU/wT8RDtnSgFEZOQpHEgQ7JL38xUfU0Y3g6aYw9QT0hJ7 4 | mCpz9Er5qLaMXJwZxzHzAahlfA0icqabvJOMvQtzD6uQv6wPEyZtDTWiQi9AXwBp 5 | HssPnpYGIn20ZZuNlX2BrClciHhCPUIIZOQn/MmqTD31jSyjoQoV7MhhMTATKJx2 6 | XrHhR+1DcKJzQBSTAGnpYVaqpsARap+nwRipr3nUTuxyGohBTSmjJ2usSeQXHI3b 7 | ODIRe1AuTyHceAbewn8b462yEWKARdpd9AjQW5SIVPfdsz5B6GlYQ5LdYKtznTuy 8 | 7wIDAQAB 9 | -----END PUBLIC KEY----- 10 | -------------------------------------------------------------------------------- /token.go: -------------------------------------------------------------------------------- 1 | package jwt 2 | 3 | import ( 4 | "crypto" 5 | "encoding/base64" 6 | "encoding/json" 7 | ) 8 | 9 | // Keyfunc will be used by the Parse methods as a callback function to supply 10 | // the key for verification. The function receives the parsed, but unverified 11 | // Token. This allows you to use properties in the Header of the token (such as 12 | // `kid`) to identify which key to use. 13 | // 14 | // The returned interface{} may be a single key or a VerificationKeySet containing 15 | // multiple keys. 16 | type Keyfunc func(*Token) (interface{}, error) 17 | 18 | // VerificationKey represents a public or secret key for verifying a token's signature. 19 | type VerificationKey interface { 20 | crypto.PublicKey | []uint8 21 | } 22 | 23 | // VerificationKeySet is a set of public or secret keys. It is used by the parser to verify a token. 24 | type VerificationKeySet struct { 25 | Keys []VerificationKey 26 | } 27 | 28 | // Token represents a JWT Token. Different fields will be used depending on 29 | // whether you're creating or parsing/verifying a token. 30 | type Token struct { 31 | Raw string // Raw contains the raw token. Populated when you [Parse] a token 32 | Method SigningMethod // Method is the signing method used or to be used 33 | Header map[string]interface{} // Header is the first segment of the token in decoded form 34 | Claims Claims // Claims is the second segment of the token in decoded form 35 | Signature []byte // Signature is the third segment of the token in decoded form. Populated when you Parse a token 36 | Valid bool // Valid specifies if the token is valid. Populated when you Parse/Verify a token 37 | } 38 | 39 | // New creates a new [Token] with the specified signing method and an empty map 40 | // of claims. Additional options can be specified, but are currently unused. 41 | func New(method SigningMethod, opts ...TokenOption) *Token { 42 | return NewWithClaims(method, MapClaims{}, opts...) 43 | } 44 | 45 | // NewWithClaims creates a new [Token] with the specified signing method and 46 | // claims. Additional options can be specified, but are currently unused. 47 | func NewWithClaims(method SigningMethod, claims Claims, opts ...TokenOption) *Token { 48 | return &Token{ 49 | Header: map[string]interface{}{ 50 | "typ": "JWT", 51 | "alg": method.Alg(), 52 | }, 53 | Claims: claims, 54 | Method: method, 55 | } 56 | } 57 | 58 | // SignedString creates and returns a complete, signed JWT. The token is signed 59 | // using the SigningMethod specified in the token. Please refer to 60 | // https://golang-jwt.github.io/jwt/usage/signing_methods/#signing-methods-and-key-types 61 | // for an overview of the different signing methods and their respective key 62 | // types. 63 | func (t *Token) SignedString(key interface{}) (string, error) { 64 | sstr, err := t.SigningString() 65 | if err != nil { 66 | return "", err 67 | } 68 | 69 | sig, err := t.Method.Sign(sstr, key) 70 | if err != nil { 71 | return "", err 72 | } 73 | 74 | return sstr + "." + t.EncodeSegment(sig), nil 75 | } 76 | 77 | // SigningString generates the signing string. This is the most expensive part 78 | // of the whole deal. Unless you need this for something special, just go 79 | // straight for the SignedString. 80 | func (t *Token) SigningString() (string, error) { 81 | h, err := json.Marshal(t.Header) 82 | if err != nil { 83 | return "", err 84 | } 85 | 86 | c, err := json.Marshal(t.Claims) 87 | if err != nil { 88 | return "", err 89 | } 90 | 91 | return t.EncodeSegment(h) + "." + t.EncodeSegment(c), nil 92 | } 93 | 94 | // EncodeSegment encodes a JWT specific base64url encoding with padding 95 | // stripped. In the future, this function might take into account a 96 | // [TokenOption]. Therefore, this function exists as a method of [Token], rather 97 | // than a global function. 98 | func (*Token) EncodeSegment(seg []byte) string { 99 | return base64.RawURLEncoding.EncodeToString(seg) 100 | } 101 | -------------------------------------------------------------------------------- /token_option.go: -------------------------------------------------------------------------------- 1 | package jwt 2 | 3 | // TokenOption is a reserved type, which provides some forward compatibility, 4 | // if we ever want to introduce token creation-related options. 5 | type TokenOption func(*Token) 6 | -------------------------------------------------------------------------------- /token_test.go: -------------------------------------------------------------------------------- 1 | package jwt_test 2 | 3 | import ( 4 | "testing" 5 | 6 | "github.com/golang-jwt/jwt/v5" 7 | ) 8 | 9 | func TestToken_SigningString(t1 *testing.T) { 10 | type fields struct { 11 | Raw string 12 | Method jwt.SigningMethod 13 | Header map[string]interface{} 14 | Claims jwt.Claims 15 | Signature []byte 16 | Valid bool 17 | } 18 | tests := []struct { 19 | name string 20 | fields fields 21 | want string 22 | wantErr bool 23 | }{ 24 | { 25 | name: "", 26 | fields: fields{ 27 | Raw: "", 28 | Method: jwt.SigningMethodHS256, 29 | Header: map[string]interface{}{ 30 | "typ": "JWT", 31 | "alg": jwt.SigningMethodHS256.Alg(), 32 | }, 33 | Claims: jwt.RegisteredClaims{}, 34 | Valid: false, 35 | }, 36 | want: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.e30", 37 | wantErr: false, 38 | }, 39 | } 40 | for _, tt := range tests { 41 | t1.Run(tt.name, func(t1 *testing.T) { 42 | t := &jwt.Token{ 43 | Raw: tt.fields.Raw, 44 | Method: tt.fields.Method, 45 | Header: tt.fields.Header, 46 | Claims: tt.fields.Claims, 47 | Signature: tt.fields.Signature, 48 | Valid: tt.fields.Valid, 49 | } 50 | got, err := t.SigningString() 51 | if (err != nil) != tt.wantErr { 52 | t1.Errorf("SigningString() error = %v, wantErr %v", err, tt.wantErr) 53 | return 54 | } 55 | if got != tt.want { 56 | t1.Errorf("SigningString() got = %v, want %v", got, tt.want) 57 | } 58 | }) 59 | } 60 | } 61 | 62 | func BenchmarkToken_SigningString(b *testing.B) { 63 | t := &jwt.Token{ 64 | Method: jwt.SigningMethodHS256, 65 | Header: map[string]interface{}{ 66 | "typ": "JWT", 67 | "alg": jwt.SigningMethodHS256.Alg(), 68 | }, 69 | Claims: jwt.RegisteredClaims{}, 70 | } 71 | b.Run("BenchmarkToken_SigningString", func(b *testing.B) { 72 | b.ResetTimer() 73 | b.ReportAllocs() 74 | for i := 0; i < b.N; i++ { 75 | _, _ = t.SigningString() 76 | } 77 | }) 78 | } 79 | -------------------------------------------------------------------------------- /types.go: -------------------------------------------------------------------------------- 1 | package jwt 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | "math" 7 | "strconv" 8 | "time" 9 | ) 10 | 11 | // TimePrecision sets the precision of times and dates within this library. This 12 | // has an influence on the precision of times when comparing expiry or other 13 | // related time fields. Furthermore, it is also the precision of times when 14 | // serializing. 15 | // 16 | // For backwards compatibility the default precision is set to seconds, so that 17 | // no fractional timestamps are generated. 18 | var TimePrecision = time.Second 19 | 20 | // MarshalSingleStringAsArray modifies the behavior of the ClaimStrings type, 21 | // especially its MarshalJSON function. 22 | // 23 | // If it is set to true (the default), it will always serialize the type as an 24 | // array of strings, even if it just contains one element, defaulting to the 25 | // behavior of the underlying []string. If it is set to false, it will serialize 26 | // to a single string, if it contains one element. Otherwise, it will serialize 27 | // to an array of strings. 28 | var MarshalSingleStringAsArray = true 29 | 30 | // NumericDate represents a JSON numeric date value, as referenced at 31 | // https://datatracker.ietf.org/doc/html/rfc7519#section-2. 32 | type NumericDate struct { 33 | time.Time 34 | } 35 | 36 | // NewNumericDate constructs a new *NumericDate from a standard library time.Time struct. 37 | // It will truncate the timestamp according to the precision specified in TimePrecision. 38 | func NewNumericDate(t time.Time) *NumericDate { 39 | return &NumericDate{t.Truncate(TimePrecision)} 40 | } 41 | 42 | // newNumericDateFromSeconds creates a new *NumericDate out of a float64 representing a 43 | // UNIX epoch with the float fraction representing non-integer seconds. 44 | func newNumericDateFromSeconds(f float64) *NumericDate { 45 | round, frac := math.Modf(f) 46 | return NewNumericDate(time.Unix(int64(round), int64(frac*1e9))) 47 | } 48 | 49 | // MarshalJSON is an implementation of the json.RawMessage interface and serializes the UNIX epoch 50 | // represented in NumericDate to a byte array, using the precision specified in TimePrecision. 51 | func (date NumericDate) MarshalJSON() (b []byte, err error) { 52 | var prec int 53 | if TimePrecision < time.Second { 54 | prec = int(math.Log10(float64(time.Second) / float64(TimePrecision))) 55 | } 56 | truncatedDate := date.Truncate(TimePrecision) 57 | 58 | // For very large timestamps, UnixNano would overflow an int64, but this 59 | // function requires nanosecond level precision, so we have to use the 60 | // following technique to get round the issue: 61 | // 62 | // 1. Take the normal unix timestamp to form the whole number part of the 63 | // output, 64 | // 2. Take the result of the Nanosecond function, which returns the offset 65 | // within the second of the particular unix time instance, to form the 66 | // decimal part of the output 67 | // 3. Concatenate them to produce the final result 68 | seconds := strconv.FormatInt(truncatedDate.Unix(), 10) 69 | nanosecondsOffset := strconv.FormatFloat(float64(truncatedDate.Nanosecond())/float64(time.Second), 'f', prec, 64) 70 | 71 | output := append([]byte(seconds), []byte(nanosecondsOffset)[1:]...) 72 | 73 | return output, nil 74 | } 75 | 76 | // UnmarshalJSON is an implementation of the json.RawMessage interface and 77 | // deserializes a [NumericDate] from a JSON representation, i.e. a 78 | // [json.Number]. This number represents an UNIX epoch with either integer or 79 | // non-integer seconds. 80 | func (date *NumericDate) UnmarshalJSON(b []byte) (err error) { 81 | var ( 82 | number json.Number 83 | f float64 84 | ) 85 | 86 | if err = json.Unmarshal(b, &number); err != nil { 87 | return fmt.Errorf("could not parse NumericData: %w", err) 88 | } 89 | 90 | if f, err = number.Float64(); err != nil { 91 | return fmt.Errorf("could not convert json number value to float: %w", err) 92 | } 93 | 94 | n := newNumericDateFromSeconds(f) 95 | *date = *n 96 | 97 | return nil 98 | } 99 | 100 | // ClaimStrings is basically just a slice of strings, but it can be either 101 | // serialized from a string array or just a string. This type is necessary, 102 | // since the "aud" claim can either be a single string or an array. 103 | type ClaimStrings []string 104 | 105 | func (s *ClaimStrings) UnmarshalJSON(data []byte) (err error) { 106 | var value interface{} 107 | 108 | if err = json.Unmarshal(data, &value); err != nil { 109 | return err 110 | } 111 | 112 | var aud []string 113 | 114 | switch v := value.(type) { 115 | case string: 116 | aud = append(aud, v) 117 | case []string: 118 | aud = ClaimStrings(v) 119 | case []interface{}: 120 | for _, vv := range v { 121 | vs, ok := vv.(string) 122 | if !ok { 123 | return ErrInvalidType 124 | } 125 | aud = append(aud, vs) 126 | } 127 | case nil: 128 | return nil 129 | default: 130 | return ErrInvalidType 131 | } 132 | 133 | *s = aud 134 | 135 | return 136 | } 137 | 138 | func (s ClaimStrings) MarshalJSON() (b []byte, err error) { 139 | // This handles a special case in the JWT RFC. If the string array, e.g. 140 | // used by the "aud" field, only contains one element, it MAY be serialized 141 | // as a single string. This may or may not be desired based on the ecosystem 142 | // of other JWT library used, so we make it configurable by the variable 143 | // MarshalSingleStringAsArray. 144 | if len(s) == 1 && !MarshalSingleStringAsArray { 145 | return json.Marshal(s[0]) 146 | } 147 | 148 | return json.Marshal([]string(s)) 149 | } 150 | -------------------------------------------------------------------------------- /types_test.go: -------------------------------------------------------------------------------- 1 | package jwt_test 2 | 3 | import ( 4 | "encoding/json" 5 | "math" 6 | "testing" 7 | "time" 8 | 9 | "github.com/golang-jwt/jwt/v5" 10 | ) 11 | 12 | func TestNumericDate(t *testing.T) { 13 | var s struct { 14 | Iat jwt.NumericDate `json:"iat"` 15 | Exp jwt.NumericDate `json:"exp"` 16 | } 17 | 18 | oldPrecision := jwt.TimePrecision 19 | 20 | jwt.TimePrecision = time.Microsecond 21 | 22 | raw := `{"iat":1516239022.000000,"exp":1516239022.123450}` 23 | 24 | if err := json.Unmarshal([]byte(raw), &s); err != nil { 25 | t.Fatalf("Unexpected error: %s", err) 26 | } 27 | 28 | b, _ := json.Marshal(s) 29 | 30 | if raw != string(b) { 31 | t.Errorf("Serialized format of numeric date mismatch. Expecting: %s Got: %s", raw, string(b)) 32 | } 33 | 34 | jwt.TimePrecision = oldPrecision 35 | } 36 | 37 | func TestSingleArrayMarshal(t *testing.T) { 38 | jwt.MarshalSingleStringAsArray = false 39 | 40 | s := jwt.ClaimStrings{"test"} 41 | expected := `"test"` 42 | 43 | b, err := json.Marshal(s) 44 | if err != nil { 45 | t.Errorf("Unexpected error: %s", err) 46 | } 47 | 48 | if expected != string(b) { 49 | t.Errorf("Serialized format of string array mismatch. Expecting: %s Got: %s", expected, string(b)) 50 | } 51 | 52 | jwt.MarshalSingleStringAsArray = true 53 | 54 | expected = `["test"]` 55 | 56 | b, err = json.Marshal(s) 57 | 58 | if err != nil { 59 | t.Errorf("Unexpected error: %s", err) 60 | } 61 | 62 | if expected != string(b) { 63 | t.Errorf("Serialized format of string array mismatch. Expecting: %s Got: %s", expected, string(b)) 64 | } 65 | } 66 | 67 | func TestNumericDate_MarshalJSON(t *testing.T) { 68 | // Do not run this test in parallel because it's changing 69 | // global state. 70 | oldPrecision := jwt.TimePrecision 71 | t.Cleanup(func() { 72 | jwt.TimePrecision = oldPrecision 73 | }) 74 | 75 | tt := []struct { 76 | in time.Time 77 | want string 78 | precision time.Duration 79 | }{ 80 | {time.Unix(5243700879, 0), "5243700879", time.Second}, 81 | {time.Unix(5243700879, 0), "5243700879.000", time.Millisecond}, 82 | {time.Unix(5243700879, 0), "5243700879.000000", time.Microsecond}, 83 | {time.Unix(5243700879, 0), "5243700879.000000000", time.Nanosecond}, 84 | // 85 | {time.Unix(4239425898, 0), "4239425898", time.Second}, 86 | {time.Unix(4239425898, 0), "4239425898.000", time.Millisecond}, 87 | {time.Unix(4239425898, 0), "4239425898.000000", time.Microsecond}, 88 | {time.Unix(4239425898, 0), "4239425898.000000000", time.Nanosecond}, 89 | // 90 | {time.Unix(253402271999, 0), "253402271999", time.Second}, 91 | {time.Unix(253402271999, 0), "253402271999.000", time.Millisecond}, 92 | {time.Unix(253402271999, 0), "253402271999.000000", time.Microsecond}, 93 | {time.Unix(253402271999, 0), "253402271999.000000000", time.Nanosecond}, 94 | // 95 | {time.Unix(0, 1644285000210402000), "1644285000", time.Second}, 96 | {time.Unix(0, 1644285000210402000), "1644285000.210", time.Millisecond}, 97 | {time.Unix(0, 1644285000210402000), "1644285000.210402", time.Microsecond}, 98 | {time.Unix(0, 1644285000210402000), "1644285000.210402000", time.Nanosecond}, 99 | // 100 | {time.Unix(0, 1644285315063096000), "1644285315", time.Second}, 101 | {time.Unix(0, 1644285315063096000), "1644285315.063", time.Millisecond}, 102 | {time.Unix(0, 1644285315063096000), "1644285315.063096", time.Microsecond}, 103 | {time.Unix(0, 1644285315063096000), "1644285315.063096000", time.Nanosecond}, 104 | // Maximum time that a go time.Time can represent 105 | {time.Unix(math.MaxInt64, 999999999), "9223372036854775807", time.Second}, 106 | {time.Unix(math.MaxInt64, 999999999), "9223372036854775807.999", time.Millisecond}, 107 | {time.Unix(math.MaxInt64, 999999999), "9223372036854775807.999999", time.Microsecond}, 108 | {time.Unix(math.MaxInt64, 999999999), "9223372036854775807.999999999", time.Nanosecond}, 109 | // Strange precisions 110 | {time.Unix(math.MaxInt64, 999999999), "9223372036854775807", time.Second}, 111 | {time.Unix(math.MaxInt64, 999999999), "9223372036854775756", time.Minute}, 112 | {time.Unix(math.MaxInt64, 999999999), "9223372036854774016", time.Hour}, 113 | {time.Unix(math.MaxInt64, 999999999), "9223372036854745216", 24 * time.Hour}, 114 | } 115 | 116 | for i, tc := range tt { 117 | jwt.TimePrecision = tc.precision 118 | by, err := jwt.NewNumericDate(tc.in).MarshalJSON() 119 | if err != nil { 120 | t.Fatal(err) 121 | } 122 | if got := string(by); got != tc.want { 123 | t.Errorf("[%d]: failed encoding: got %q want %q", i, got, tc.want) 124 | } 125 | } 126 | } 127 | -------------------------------------------------------------------------------- /validator.go: -------------------------------------------------------------------------------- 1 | package jwt 2 | 3 | import ( 4 | "fmt" 5 | "time" 6 | ) 7 | 8 | // ClaimsValidator is an interface that can be implemented by custom claims who 9 | // wish to execute any additional claims validation based on 10 | // application-specific logic. The Validate function is then executed in 11 | // addition to the regular claims validation and any error returned is appended 12 | // to the final validation result. 13 | // 14 | // type MyCustomClaims struct { 15 | // Foo string `json:"foo"` 16 | // jwt.RegisteredClaims 17 | // } 18 | // 19 | // func (m MyCustomClaims) Validate() error { 20 | // if m.Foo != "bar" { 21 | // return errors.New("must be foobar") 22 | // } 23 | // return nil 24 | // } 25 | type ClaimsValidator interface { 26 | Claims 27 | Validate() error 28 | } 29 | 30 | // Validator is the core of the new Validation API. It is automatically used by 31 | // a [Parser] during parsing and can be modified with various parser options. 32 | // 33 | // The [NewValidator] function should be used to create an instance of this 34 | // struct. 35 | type Validator struct { 36 | // leeway is an optional leeway that can be provided to account for clock skew. 37 | leeway time.Duration 38 | 39 | // timeFunc is used to supply the current time that is needed for 40 | // validation. If unspecified, this defaults to time.Now. 41 | timeFunc func() time.Time 42 | 43 | // requireExp specifies whether the exp claim is required 44 | requireExp bool 45 | 46 | // verifyIat specifies whether the iat (Issued At) claim will be verified. 47 | // According to https://www.rfc-editor.org/rfc/rfc7519#section-4.1.6 this 48 | // only specifies the age of the token, but no validation check is 49 | // necessary. However, if wanted, it can be checked if the iat is 50 | // unrealistic, i.e., in the future. 51 | verifyIat bool 52 | 53 | // expectedAud contains the audience this token expects. Supplying an empty 54 | // slice will disable aud checking. 55 | expectedAud []string 56 | 57 | // expectAllAud specifies whether all expected audiences must be present in 58 | // the token. If false, only one of the expected audiences must be present. 59 | expectAllAud bool 60 | 61 | // expectedIss contains the issuer this token expects. Supplying an empty 62 | // string will disable iss checking. 63 | expectedIss string 64 | 65 | // expectedSub contains the subject this token expects. Supplying an empty 66 | // string will disable sub checking. 67 | expectedSub string 68 | } 69 | 70 | // NewValidator can be used to create a stand-alone validator with the supplied 71 | // options. This validator can then be used to validate already parsed claims. 72 | // 73 | // Note: Under normal circumstances, explicitly creating a validator is not 74 | // needed and can potentially be dangerous; instead functions of the [Parser] 75 | // class should be used. 76 | // 77 | // The [Validator] is only checking the *validity* of the claims, such as its 78 | // expiration time, but it does NOT perform *signature verification* of the 79 | // token. 80 | func NewValidator(opts ...ParserOption) *Validator { 81 | p := NewParser(opts...) 82 | return p.validator 83 | } 84 | 85 | // Validate validates the given claims. It will also perform any custom 86 | // validation if claims implements the [ClaimsValidator] interface. 87 | // 88 | // Note: It will NOT perform any *signature verification* on the token that 89 | // contains the claims and expects that the [Claim] was already successfully 90 | // verified. 91 | func (v *Validator) Validate(claims Claims) error { 92 | var ( 93 | now time.Time 94 | errs = make([]error, 0, 6) 95 | err error 96 | ) 97 | 98 | // Check, if we have a time func 99 | if v.timeFunc != nil { 100 | now = v.timeFunc() 101 | } else { 102 | now = time.Now() 103 | } 104 | 105 | // We always need to check the expiration time, but usage of the claim 106 | // itself is OPTIONAL by default. requireExp overrides this behavior 107 | // and makes the exp claim mandatory. 108 | if err = v.verifyExpiresAt(claims, now, v.requireExp); err != nil { 109 | errs = append(errs, err) 110 | } 111 | 112 | // We always need to check not-before, but usage of the claim itself is 113 | // OPTIONAL. 114 | if err = v.verifyNotBefore(claims, now, false); err != nil { 115 | errs = append(errs, err) 116 | } 117 | 118 | // Check issued-at if the option is enabled 119 | if v.verifyIat { 120 | if err = v.verifyIssuedAt(claims, now, false); err != nil { 121 | errs = append(errs, err) 122 | } 123 | } 124 | 125 | // If we have an expected audience, we also require the audience claim 126 | if len(v.expectedAud) > 0 { 127 | if err = v.verifyAudience(claims, v.expectedAud, v.expectAllAud, true); err != nil { 128 | errs = append(errs, err) 129 | } 130 | } 131 | 132 | // If we have an expected issuer, we also require the issuer claim 133 | if v.expectedIss != "" { 134 | if err = v.verifyIssuer(claims, v.expectedIss, true); err != nil { 135 | errs = append(errs, err) 136 | } 137 | } 138 | 139 | // If we have an expected subject, we also require the subject claim 140 | if v.expectedSub != "" { 141 | if err = v.verifySubject(claims, v.expectedSub, true); err != nil { 142 | errs = append(errs, err) 143 | } 144 | } 145 | 146 | // Finally, we want to give the claim itself some possibility to do some 147 | // additional custom validation based on a custom Validate function. 148 | cvt, ok := claims.(ClaimsValidator) 149 | if ok { 150 | if err := cvt.Validate(); err != nil { 151 | errs = append(errs, err) 152 | } 153 | } 154 | 155 | if len(errs) == 0 { 156 | return nil 157 | } 158 | 159 | return joinErrors(errs...) 160 | } 161 | 162 | // verifyExpiresAt compares the exp claim in claims against cmp. This function 163 | // will succeed if cmp < exp. Additional leeway is taken into account. 164 | // 165 | // If exp is not set, it will succeed if the claim is not required, 166 | // otherwise ErrTokenRequiredClaimMissing will be returned. 167 | // 168 | // Additionally, if any error occurs while retrieving the claim, e.g., when its 169 | // the wrong type, an ErrTokenUnverifiable error will be returned. 170 | func (v *Validator) verifyExpiresAt(claims Claims, cmp time.Time, required bool) error { 171 | exp, err := claims.GetExpirationTime() 172 | if err != nil { 173 | return err 174 | } 175 | 176 | if exp == nil { 177 | return errorIfRequired(required, "exp") 178 | } 179 | 180 | return errorIfFalse(cmp.Before((exp.Time).Add(+v.leeway)), ErrTokenExpired) 181 | } 182 | 183 | // verifyIssuedAt compares the iat claim in claims against cmp. This function 184 | // will succeed if cmp >= iat. Additional leeway is taken into account. 185 | // 186 | // If iat is not set, it will succeed if the claim is not required, 187 | // otherwise ErrTokenRequiredClaimMissing will be returned. 188 | // 189 | // Additionally, if any error occurs while retrieving the claim, e.g., when its 190 | // the wrong type, an ErrTokenUnverifiable error will be returned. 191 | func (v *Validator) verifyIssuedAt(claims Claims, cmp time.Time, required bool) error { 192 | iat, err := claims.GetIssuedAt() 193 | if err != nil { 194 | return err 195 | } 196 | 197 | if iat == nil { 198 | return errorIfRequired(required, "iat") 199 | } 200 | 201 | return errorIfFalse(!cmp.Before(iat.Add(-v.leeway)), ErrTokenUsedBeforeIssued) 202 | } 203 | 204 | // verifyNotBefore compares the nbf claim in claims against cmp. This function 205 | // will return true if cmp >= nbf. Additional leeway is taken into account. 206 | // 207 | // If nbf is not set, it will succeed if the claim is not required, 208 | // otherwise ErrTokenRequiredClaimMissing will be returned. 209 | // 210 | // Additionally, if any error occurs while retrieving the claim, e.g., when its 211 | // the wrong type, an ErrTokenUnverifiable error will be returned. 212 | func (v *Validator) verifyNotBefore(claims Claims, cmp time.Time, required bool) error { 213 | nbf, err := claims.GetNotBefore() 214 | if err != nil { 215 | return err 216 | } 217 | 218 | if nbf == nil { 219 | return errorIfRequired(required, "nbf") 220 | } 221 | 222 | return errorIfFalse(!cmp.Before(nbf.Add(-v.leeway)), ErrTokenNotValidYet) 223 | } 224 | 225 | // verifyAudience compares the aud claim against cmp. 226 | // 227 | // If aud is not set or an empty list, it will succeed if the claim is not required, 228 | // otherwise ErrTokenRequiredClaimMissing will be returned. 229 | // 230 | // Additionally, if any error occurs while retrieving the claim, e.g., when its 231 | // the wrong type, an ErrTokenUnverifiable error will be returned. 232 | func (v *Validator) verifyAudience(claims Claims, cmp []string, expectAllAud bool, required bool) error { 233 | aud, err := claims.GetAudience() 234 | if err != nil { 235 | return err 236 | } 237 | 238 | if len(aud) == 0 { 239 | return errorIfRequired(required, "aud") 240 | } 241 | 242 | // use a var here to keep constant time compare when looping over a number of claims 243 | matching := make(map[string]bool, 0) 244 | 245 | // build a matching hashmap out of the expected aud 246 | for _, expected := range cmp { 247 | matching[expected] = false 248 | } 249 | 250 | // compare the expected aud with the actual aud in a constant time manner by looping over all actual values 251 | var stringClaims string 252 | for _, a := range aud { 253 | a := a 254 | _, ok := matching[a] 255 | if ok { 256 | matching[a] = true 257 | } 258 | 259 | stringClaims = stringClaims + a 260 | } 261 | 262 | // check if all expected auds are present 263 | result := true 264 | for _, match := range matching { 265 | if !expectAllAud && match { 266 | break 267 | } else if !match { 268 | result = false 269 | } 270 | } 271 | 272 | // case where "" is sent in one or many aud claims 273 | if stringClaims == "" { 274 | return errorIfRequired(required, "aud") 275 | } 276 | 277 | return errorIfFalse(result, ErrTokenInvalidAudience) 278 | } 279 | 280 | // verifyIssuer compares the iss claim in claims against cmp. 281 | // 282 | // If iss is not set, it will succeed if the claim is not required, 283 | // otherwise ErrTokenRequiredClaimMissing will be returned. 284 | // 285 | // Additionally, if any error occurs while retrieving the claim, e.g., when its 286 | // the wrong type, an ErrTokenUnverifiable error will be returned. 287 | func (v *Validator) verifyIssuer(claims Claims, cmp string, required bool) error { 288 | iss, err := claims.GetIssuer() 289 | if err != nil { 290 | return err 291 | } 292 | 293 | if iss == "" { 294 | return errorIfRequired(required, "iss") 295 | } 296 | 297 | return errorIfFalse(iss == cmp, ErrTokenInvalidIssuer) 298 | } 299 | 300 | // verifySubject compares the sub claim against cmp. 301 | // 302 | // If sub is not set, it will succeed if the claim is not required, 303 | // otherwise ErrTokenRequiredClaimMissing will be returned. 304 | // 305 | // Additionally, if any error occurs while retrieving the claim, e.g., when its 306 | // the wrong type, an ErrTokenUnverifiable error will be returned. 307 | func (v *Validator) verifySubject(claims Claims, cmp string, required bool) error { 308 | sub, err := claims.GetSubject() 309 | if err != nil { 310 | return err 311 | } 312 | 313 | if sub == "" { 314 | return errorIfRequired(required, "sub") 315 | } 316 | 317 | return errorIfFalse(sub == cmp, ErrTokenInvalidSubject) 318 | } 319 | 320 | // errorIfFalse returns the error specified in err, if the value is true. 321 | // Otherwise, nil is returned. 322 | func errorIfFalse(value bool, err error) error { 323 | if value { 324 | return nil 325 | } else { 326 | return err 327 | } 328 | } 329 | 330 | // errorIfRequired returns an ErrTokenRequiredClaimMissing error if required is 331 | // true. Otherwise, nil is returned. 332 | func errorIfRequired(required bool, claim string) error { 333 | if required { 334 | return newError(fmt.Sprintf("%s claim is required", claim), ErrTokenRequiredClaimMissing) 335 | } else { 336 | return nil 337 | } 338 | } 339 | -------------------------------------------------------------------------------- /validator_test.go: -------------------------------------------------------------------------------- 1 | package jwt 2 | 3 | import ( 4 | "errors" 5 | "testing" 6 | "time" 7 | ) 8 | 9 | var ErrFooBar = errors.New("must be foobar") 10 | 11 | type MyCustomClaims struct { 12 | Foo string `json:"foo"` 13 | RegisteredClaims 14 | } 15 | 16 | func (m MyCustomClaims) Validate() error { 17 | if m.Foo != "bar" { 18 | return ErrFooBar 19 | } 20 | return nil 21 | } 22 | 23 | func Test_Validator_Validate(t *testing.T) { 24 | type fields struct { 25 | leeway time.Duration 26 | timeFunc func() time.Time 27 | verifyIat bool 28 | expectedAud []string 29 | expectAllAud bool 30 | expectedIss string 31 | expectedSub string 32 | } 33 | type args struct { 34 | claims Claims 35 | } 36 | tests := []struct { 37 | name string 38 | fields fields 39 | args args 40 | wantErr error 41 | }{ 42 | { 43 | name: "expected iss mismatch", 44 | fields: fields{expectedIss: "me"}, 45 | args: args{RegisteredClaims{Issuer: "not_me"}}, 46 | wantErr: ErrTokenInvalidIssuer, 47 | }, 48 | { 49 | name: "expected iss is missing", 50 | fields: fields{expectedIss: "me"}, 51 | args: args{RegisteredClaims{}}, 52 | wantErr: ErrTokenRequiredClaimMissing, 53 | }, 54 | { 55 | name: "expected sub mismatch", 56 | fields: fields{expectedSub: "me"}, 57 | args: args{RegisteredClaims{Subject: "not-me"}}, 58 | wantErr: ErrTokenInvalidSubject, 59 | }, 60 | { 61 | name: "expected sub is missing", 62 | fields: fields{expectedSub: "me"}, 63 | args: args{RegisteredClaims{}}, 64 | wantErr: ErrTokenRequiredClaimMissing, 65 | }, 66 | { 67 | name: "custom validator", 68 | fields: fields{}, 69 | args: args{MyCustomClaims{Foo: "not-bar"}}, 70 | wantErr: ErrFooBar, 71 | }, 72 | } 73 | for _, tt := range tests { 74 | t.Run(tt.name, func(t *testing.T) { 75 | v := &Validator{ 76 | leeway: tt.fields.leeway, 77 | timeFunc: tt.fields.timeFunc, 78 | verifyIat: tt.fields.verifyIat, 79 | expectedAud: tt.fields.expectedAud, 80 | expectAllAud: tt.fields.expectAllAud, 81 | expectedIss: tt.fields.expectedIss, 82 | expectedSub: tt.fields.expectedSub, 83 | } 84 | if err := v.Validate(tt.args.claims); (err != nil) && !errors.Is(err, tt.wantErr) { 85 | t.Errorf("validator.Validate() error = %v, wantErr %v", err, tt.wantErr) 86 | } 87 | }) 88 | } 89 | } 90 | 91 | func Test_Validator_verifyExpiresAt(t *testing.T) { 92 | type fields struct { 93 | leeway time.Duration 94 | timeFunc func() time.Time 95 | } 96 | type args struct { 97 | claims Claims 98 | cmp time.Time 99 | required bool 100 | } 101 | tests := []struct { 102 | name string 103 | fields fields 104 | args args 105 | wantErr error 106 | }{ 107 | { 108 | name: "good claim", 109 | fields: fields{timeFunc: time.Now}, 110 | args: args{claims: RegisteredClaims{ExpiresAt: NewNumericDate(time.Now().Add(10 * time.Minute))}}, 111 | wantErr: nil, 112 | }, 113 | { 114 | name: "claims with invalid type", 115 | fields: fields{}, 116 | args: args{claims: MapClaims{"exp": "string"}}, 117 | wantErr: ErrInvalidType, 118 | }, 119 | } 120 | for _, tt := range tests { 121 | t.Run(tt.name, func(t *testing.T) { 122 | v := &Validator{ 123 | leeway: tt.fields.leeway, 124 | timeFunc: tt.fields.timeFunc, 125 | } 126 | 127 | err := v.verifyExpiresAt(tt.args.claims, tt.args.cmp, tt.args.required) 128 | if (err != nil) && !errors.Is(err, tt.wantErr) { 129 | t.Errorf("validator.verifyExpiresAt() error = %v, wantErr %v", err, tt.wantErr) 130 | } 131 | }) 132 | } 133 | } 134 | 135 | func Test_Validator_verifyIssuer(t *testing.T) { 136 | type fields struct { 137 | expectedIss string 138 | } 139 | type args struct { 140 | claims Claims 141 | cmp string 142 | required bool 143 | } 144 | tests := []struct { 145 | name string 146 | fields fields 147 | args args 148 | wantErr error 149 | }{ 150 | { 151 | name: "good claim", 152 | fields: fields{expectedIss: "me"}, 153 | args: args{claims: MapClaims{"iss": "me"}, cmp: "me"}, 154 | wantErr: nil, 155 | }, 156 | { 157 | name: "claims with invalid type", 158 | fields: fields{expectedIss: "me"}, 159 | args: args{claims: MapClaims{"iss": 1}, cmp: "me"}, 160 | wantErr: ErrInvalidType, 161 | }, 162 | } 163 | for _, tt := range tests { 164 | t.Run(tt.name, func(t *testing.T) { 165 | v := &Validator{ 166 | expectedIss: tt.fields.expectedIss, 167 | } 168 | err := v.verifyIssuer(tt.args.claims, tt.args.cmp, tt.args.required) 169 | if (err != nil) && !errors.Is(err, tt.wantErr) { 170 | t.Errorf("validator.verifyIssuer() error = %v, wantErr %v", err, tt.wantErr) 171 | } 172 | }) 173 | } 174 | } 175 | 176 | func Test_Validator_verifySubject(t *testing.T) { 177 | type fields struct { 178 | expectedSub string 179 | } 180 | type args struct { 181 | claims Claims 182 | cmp string 183 | required bool 184 | } 185 | tests := []struct { 186 | name string 187 | fields fields 188 | args args 189 | wantErr error 190 | }{ 191 | { 192 | name: "good claim", 193 | fields: fields{expectedSub: "me"}, 194 | args: args{claims: MapClaims{"sub": "me"}, cmp: "me"}, 195 | wantErr: nil, 196 | }, 197 | { 198 | name: "claims with invalid type", 199 | fields: fields{expectedSub: "me"}, 200 | args: args{claims: MapClaims{"sub": 1}, cmp: "me"}, 201 | wantErr: ErrInvalidType, 202 | }, 203 | } 204 | for _, tt := range tests { 205 | t.Run(tt.name, func(t *testing.T) { 206 | v := &Validator{ 207 | expectedSub: tt.fields.expectedSub, 208 | } 209 | err := v.verifySubject(tt.args.claims, tt.args.cmp, tt.args.required) 210 | if (err != nil) && !errors.Is(err, tt.wantErr) { 211 | t.Errorf("validator.verifySubject() error = %v, wantErr %v", err, tt.wantErr) 212 | } 213 | }) 214 | } 215 | } 216 | 217 | func Test_Validator_verifyIssuedAt(t *testing.T) { 218 | type fields struct { 219 | leeway time.Duration 220 | timeFunc func() time.Time 221 | verifyIat bool 222 | } 223 | type args struct { 224 | claims Claims 225 | cmp time.Time 226 | required bool 227 | } 228 | tests := []struct { 229 | name string 230 | fields fields 231 | args args 232 | wantErr error 233 | }{ 234 | { 235 | name: "good claim without iat", 236 | fields: fields{verifyIat: true}, 237 | args: args{claims: MapClaims{}, required: false}, 238 | wantErr: nil, 239 | }, 240 | { 241 | name: "good claim with iat", 242 | fields: fields{verifyIat: true}, 243 | args: args{ 244 | claims: RegisteredClaims{IssuedAt: NewNumericDate(time.Now())}, 245 | cmp: time.Now().Add(10 * time.Minute), 246 | required: false, 247 | }, 248 | wantErr: nil, 249 | }, 250 | } 251 | for _, tt := range tests { 252 | t.Run(tt.name, func(t *testing.T) { 253 | v := &Validator{ 254 | leeway: tt.fields.leeway, 255 | timeFunc: tt.fields.timeFunc, 256 | verifyIat: tt.fields.verifyIat, 257 | } 258 | if err := v.verifyIssuedAt(tt.args.claims, tt.args.cmp, tt.args.required); (err != nil) && !errors.Is(err, tt.wantErr) { 259 | t.Errorf("validator.verifyIssuedAt() error = %v, wantErr %v", err, tt.wantErr) 260 | } 261 | }) 262 | } 263 | } 264 | --------------------------------------------------------------------------------