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