浏览代码

feat:新增jwt相关包、同步usercneter相关观法

zhangxinlei1996 3 年之前
父节点
当前提交
daaabaf873
共有 65 个文件被更改,包括 5269 次插入0 次删除
  1. 40 0
      src/github.com/golang-jwt/jwt/v4/.github/workflows/build.yml
  2. 71 0
      src/github.com/golang-jwt/jwt/v4/.github/workflows/codeql-analysis.yml
  3. 4 0
      src/github.com/golang-jwt/jwt/v4/.gitignore
  4. 9 0
      src/github.com/golang-jwt/jwt/v4/LICENSE
  5. 22 0
      src/github.com/golang-jwt/jwt/v4/MIGRATION_GUIDE.md
  6. 114 0
      src/github.com/golang-jwt/jwt/v4/README.md
  7. 135 0
      src/github.com/golang-jwt/jwt/v4/VERSION_HISTORY.md
  8. 273 0
      src/github.com/golang-jwt/jwt/v4/claims.go
  9. 19 0
      src/github.com/golang-jwt/jwt/v4/cmd/jwt/README.md
  10. 344 0
      src/github.com/golang-jwt/jwt/v4/cmd/jwt/main.go
  11. 4 0
      src/github.com/golang-jwt/jwt/v4/doc.go
  12. 142 0
      src/github.com/golang-jwt/jwt/v4/ecdsa.go
  13. 164 0
      src/github.com/golang-jwt/jwt/v4/ecdsa_test.go
  14. 69 0
      src/github.com/golang-jwt/jwt/v4/ecdsa_utils.go
  15. 85 0
      src/github.com/golang-jwt/jwt/v4/ed25519.go
  16. 84 0
      src/github.com/golang-jwt/jwt/v4/ed25519_test.go
  17. 64 0
      src/github.com/golang-jwt/jwt/v4/ed25519_utils.go
  18. 64 0
      src/github.com/golang-jwt/jwt/v4/errors.go
  19. 120 0
      src/github.com/golang-jwt/jwt/v4/example_test.go
  20. 3 0
      src/github.com/golang-jwt/jwt/v4/go.mod
  21. 0 0
      src/github.com/golang-jwt/jwt/v4/go.sum
  22. 95 0
      src/github.com/golang-jwt/jwt/v4/hmac.go
  23. 67 0
      src/github.com/golang-jwt/jwt/v4/hmac_example_test.go
  24. 92 0
      src/github.com/golang-jwt/jwt/v4/hmac_test.go
  25. 210 0
      src/github.com/golang-jwt/jwt/v4/http_example_test.go
  26. 148 0
      src/github.com/golang-jwt/jwt/v4/map_claims.go
  27. 123 0
      src/github.com/golang-jwt/jwt/v4/map_claims_test.go
  28. 52 0
      src/github.com/golang-jwt/jwt/v4/none.go
  29. 73 0
      src/github.com/golang-jwt/jwt/v4/none_test.go
  30. 170 0
      src/github.com/golang-jwt/jwt/v4/parser.go
  31. 29 0
      src/github.com/golang-jwt/jwt/v4/parser_option.go
  32. 602 0
      src/github.com/golang-jwt/jwt/v4/parser_test.go
  33. 7 0
      src/github.com/golang-jwt/jwt/v4/request/doc.go
  34. 81 0
      src/github.com/golang-jwt/jwt/v4/request/extractor.go
  35. 32 0
      src/github.com/golang-jwt/jwt/v4/request/extractor_example_test.go
  36. 91 0
      src/github.com/golang-jwt/jwt/v4/request/extractor_test.go
  37. 28 0
      src/github.com/golang-jwt/jwt/v4/request/oauth2.go
  38. 70 0
      src/github.com/golang-jwt/jwt/v4/request/request.go
  39. 104 0
      src/github.com/golang-jwt/jwt/v4/request/request_test.go
  40. 101 0
      src/github.com/golang-jwt/jwt/v4/rsa.go
  41. 142 0
      src/github.com/golang-jwt/jwt/v4/rsa_pss.go
  42. 150 0
      src/github.com/golang-jwt/jwt/v4/rsa_pss_test.go
  43. 200 0
      src/github.com/golang-jwt/jwt/v4/rsa_test.go
  44. 105 0
      src/github.com/golang-jwt/jwt/v4/rsa_utils.go
  45. 46 0
      src/github.com/golang-jwt/jwt/v4/signing_method.go
  46. 1 0
      src/github.com/golang-jwt/jwt/v4/staticcheck.conf
  47. 5 0
      src/github.com/golang-jwt/jwt/v4/test/ec256-private.pem
  48. 4 0
      src/github.com/golang-jwt/jwt/v4/test/ec256-public.pem
  49. 6 0
      src/github.com/golang-jwt/jwt/v4/test/ec384-private.pem
  50. 5 0
      src/github.com/golang-jwt/jwt/v4/test/ec384-public.pem
  51. 7 0
      src/github.com/golang-jwt/jwt/v4/test/ec512-private.pem
  52. 6 0
      src/github.com/golang-jwt/jwt/v4/test/ec512-public.pem
  53. 3 0
      src/github.com/golang-jwt/jwt/v4/test/ed25519-private.pem
  54. 3 0
      src/github.com/golang-jwt/jwt/v4/test/ed25519-public.pem
  55. 4 0
      src/github.com/golang-jwt/jwt/v4/test/examplePaddedKey-public.pem
  56. 69 0
      src/github.com/golang-jwt/jwt/v4/test/helpers.go
  57. 1 0
      src/github.com/golang-jwt/jwt/v4/test/hmacTestKey
  58. 30 0
      src/github.com/golang-jwt/jwt/v4/test/privateSecure.pem
  59. 27 0
      src/github.com/golang-jwt/jwt/v4/test/sample_key
  60. 9 0
      src/github.com/golang-jwt/jwt/v4/test/sample_key.pub
  61. 131 0
      src/github.com/golang-jwt/jwt/v4/token.go
  62. 127 0
      src/github.com/golang-jwt/jwt/v4/types.go
  63. 67 0
      src/github.com/golang-jwt/jwt/v4/types_test.go
  64. 35 0
      src/qfw/util/jwt/jwt.go
  65. 81 0
      src/qfw/util/userCenter.go

+ 40 - 0
src/github.com/golang-jwt/jwt/v4/.github/workflows/build.yml

@@ -0,0 +1,40 @@
+name: build
+
+on:
+  push:
+    branches:
+      - main
+  pull_request:
+    types: [opened, synchronize, reopened]
+
+jobs:
+  check:
+    runs-on: ubuntu-latest
+    steps:
+      - name: Checkout
+        uses: actions/checkout@v2
+      - uses: reviewdog/action-staticcheck@v1
+        with:
+          github_token: ${{ secrets.github_token }}
+          reporter: github-pr-review
+          filter_mode: nofilter
+          fail_on_error: true
+
+  build:
+    runs-on: ubuntu-latest
+    strategy:
+      fail-fast: false
+      matrix:
+        go: [1.15, 1.16, 1.17]
+    steps:
+      - name: Checkout
+        uses: actions/checkout@v2
+      - name: Setup Go
+        uses: actions/setup-go@v2
+        with:
+          go-version: "${{ matrix.go }}"
+      - name: Build
+        run: |
+          go vet ./...
+          go test -v ./...
+          go build ./...

+ 71 - 0
src/github.com/golang-jwt/jwt/v4/.github/workflows/codeql-analysis.yml

@@ -0,0 +1,71 @@
+# 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:
+    # The branches below must be a subset of the branches above
+    # branches: [ main ]
+  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@v2
+
+    # Initializes the CodeQL tools for scanning.
+    - name: Initialize CodeQL
+      uses: github/codeql-action/init@v1
+      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@v1
+
+    # ℹ️ 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@v1

+ 4 - 0
src/github.com/golang-jwt/jwt/v4/.gitignore

@@ -0,0 +1,4 @@
+.DS_Store
+bin
+.idea/
+

+ 9 - 0
src/github.com/golang-jwt/jwt/v4/LICENSE

@@ -0,0 +1,9 @@
+Copyright (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.
+

+ 22 - 0
src/github.com/golang-jwt/jwt/v4/MIGRATION_GUIDE.md

@@ -0,0 +1,22 @@
+## 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.

+ 114 - 0
src/github.com/golang-jwt/jwt/v4/README.md

@@ -0,0 +1,114 @@
+# 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/v4.svg)](https://pkg.go.dev/github.com/golang-jwt/jwt/v4)
+
+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 backwards 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.
+
+> 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. 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 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
+which 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.
+
+## Examples
+
+See [the project documentation](https://pkg.go.dev/github.com/golang-jwt/jwt) for examples of usage:
+
+* [Simple example of parsing and validating a token](https://pkg.go.dev/github.com/golang-jwt/jwt#example-Parse-Hmac)
+* [Simple example of building and signing a token](https://pkg.go.dev/github.com/golang-jwt/jwt#example-New-Hmac)
+* [Directory of Examples](https://pkg.go.dev/github.com/golang-jwt/jwt#pkg-examples)
+
+## Extensions
+
+This library publishes all the necessary components for adding your own signing methods.  Simply implement the `SigningMethod` interface and register a factory method using `RegisterSigningMethod`.  
+
+Here's an example of an extension that integrates with multiple Google Cloud Platform signing tools (AppEngine, IAM API, Cloud KMS): https://github.com/someone1/gcp-jwt-go
+
+## Compliance
+
+This library was last reviewed to comply with [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 backwards-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` for more information on updating your code.
+
+## Usage Tips
+
+### Signing vs Encryption
+
+A token is simply a JSON object that is signed by its author. this tells you exactly two things about the data:
+
+* The author of the token was in the possession of the signing secret
+* The data has not been modified since it was signed
+
+It's important to know that JWT does not provide encryption, which means anyone who has access to the token can read its contents. If you need to protect (encrypt) the data, there is a companion spec, `JWE`, that provides this functionality. JWE is currently outside the scope of this library.
+
+### Choosing a Signing Method
+
+There are several signing methods available, and you should probably take the time to learn about the various options before choosing one.  The principal design decision is most likely going to be symmetric vs asymmetric.
+
+Symmetric signing methods, such as HSA, use only a single secret. This is probably the simplest signing method to use since any `[]byte` can be used as a valid secret. They are also slightly computationally faster to use, though this rarely is enough to matter. Symmetric signing methods work the best when both producers and consumers of tokens are trusted, or even the same system. Since the same secret is used to both sign and validate tokens, you can't easily distribute the key for validation.
+
+Asymmetric signing methods, such as RSA, use different keys for signing and verifying tokens. This makes it possible to produce tokens with a private key, and allow any consumer to access the public key for verification.
+
+### Signing Methods and Key Types
+
+Each signing method expects a different object type for its signing keys. See the package documentation for details. Here are the most common ones:
+
+* The [HMAC signing method](https://pkg.go.dev/github.com/golang-jwt/jwt#SigningMethodHMAC) (`HS256`,`HS384`,`HS512`) expect `[]byte` values for signing and validation
+* The [RSA signing method](https://pkg.go.dev/github.com/golang-jwt/jwt#SigningMethodRSA) (`RS256`,`RS384`,`RS512`) expect `*rsa.PrivateKey` for signing and `*rsa.PublicKey` for validation
+* The [ECDSA signing method](https://pkg.go.dev/github.com/golang-jwt/jwt#SigningMethodECDSA) (`ES256`,`ES384`,`ES512`) expect `*ecdsa.PrivateKey` for signing and `*ecdsa.PublicKey` for validation
+* The [EdDSA signing method](https://pkg.go.dev/github.com/golang-jwt/jwt#SigningMethodEd25519) (`Ed25519`) expect `ed25519.PrivateKey` for signing and `ed25519.PublicKey` for validation
+
+### JWT and OAuth
+
+It's worth mentioning that OAuth and JWT are not the same thing. A JWT token is simply a signed JSON object. It can be used anywhere such a thing is useful. There is some confusion, though, as JWT is the most common type of bearer token used in OAuth2 authentication.
+
+Without going too far down the rabbit hole, here's a description of the interaction of these technologies:
+
+* OAuth is a protocol for allowing an identity provider to be separate from the service a user is logging in to. For example, whenever you use Facebook to log into a different service (Yelp, Spotify, etc), you are using OAuth.
+* OAuth defines several options for passing around authentication data. One popular method is called a "bearer token". A bearer token is simply a string that _should_ only be held by an authenticated user. Thus, simply presenting this token proves your identity. You can probably derive from here why a JWT might make a good bearer token.
+* Because bearer tokens are used for authentication, it's important they're kept secret. This is why transactions that use bearer tokens typically happen over SSL.
+
+### Troubleshooting
+
+This library uses descriptive error messages whenever possible. If you are not getting the expected result, have a look at the errors. The most common place people get stuck is providing the correct type of key to the parser. See the above section on signing methods and key types.
+
+## More
+
+Documentation can be found [on pkg.go.dev](https://pkg.go.dev/github.com/golang-jwt/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.

+ 135 - 0
src/github.com/golang-jwt/jwt/v4/VERSION_HISTORY.md

@@ -0,0 +1,135 @@
+## `jwt-go` Version History
+
+#### 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

+ 273 - 0
src/github.com/golang-jwt/jwt/v4/claims.go

@@ -0,0 +1,273 @@
+package jwt
+
+import (
+	"crypto/subtle"
+	"fmt"
+	"time"
+)
+
+// Claims must just have a Valid method that determines
+// if the token is invalid for any supported reason
+type Claims interface {
+	Valid() error
+}
+
+// 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 usecase
+// 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"`
+}
+
+// Valid validates time based claims "exp, iat, nbf".
+// There is no accounting for clock skew.
+// As well, if any of the above claims are not in the token, it will still
+// be considered a valid claim.
+func (c RegisteredClaims) Valid() error {
+	vErr := new(ValidationError)
+	now := TimeFunc()
+
+	// The claims below are optional, by default, so if they are set to the
+	// default value in Go, let's not fail the verification for them.
+	if !c.VerifyExpiresAt(now, false) {
+		delta := now.Sub(c.ExpiresAt.Time)
+		vErr.Inner = fmt.Errorf("token is expired by %v", delta)
+		vErr.Errors |= ValidationErrorExpired
+	}
+
+	if !c.VerifyIssuedAt(now, false) {
+		vErr.Inner = fmt.Errorf("token used before issued")
+		vErr.Errors |= ValidationErrorIssuedAt
+	}
+
+	if !c.VerifyNotBefore(now, false) {
+		vErr.Inner = fmt.Errorf("token is not valid yet")
+		vErr.Errors |= ValidationErrorNotValidYet
+	}
+
+	if vErr.valid() {
+		return nil
+	}
+
+	return vErr
+}
+
+// VerifyAudience compares the aud claim against cmp.
+// If required is false, this method will return true if the value matches or is unset
+func (c *RegisteredClaims) VerifyAudience(cmp string, req bool) bool {
+	return verifyAud(c.Audience, cmp, req)
+}
+
+// VerifyExpiresAt compares the exp claim against cmp (cmp < exp).
+// If req is false, it will return true, if exp is unset.
+func (c *RegisteredClaims) VerifyExpiresAt(cmp time.Time, req bool) bool {
+	if c.ExpiresAt == nil {
+		return verifyExp(nil, cmp, req)
+	}
+
+	return verifyExp(&c.ExpiresAt.Time, cmp, req)
+}
+
+// VerifyIssuedAt compares the iat claim against cmp (cmp >= iat).
+// If req is false, it will return true, if iat is unset.
+func (c *RegisteredClaims) VerifyIssuedAt(cmp time.Time, req bool) bool {
+	if c.IssuedAt == nil {
+		return verifyIat(nil, cmp, req)
+	}
+
+	return verifyIat(&c.IssuedAt.Time, cmp, req)
+}
+
+// VerifyNotBefore compares the nbf claim against cmp (cmp >= nbf).
+// If req is false, it will return true, if nbf is unset.
+func (c *RegisteredClaims) VerifyNotBefore(cmp time.Time, req bool) bool {
+	if c.NotBefore == nil {
+		return verifyNbf(nil, cmp, req)
+	}
+
+	return verifyNbf(&c.NotBefore.Time, cmp, req)
+}
+
+// VerifyIssuer compares the iss claim against cmp.
+// If required is false, this method will return true if the value matches or is unset
+func (c *RegisteredClaims) VerifyIssuer(cmp string, req bool) bool {
+	return verifyIss(c.Issuer, cmp, req)
+}
+
+// StandardClaims are a structured version of the JWT Claims Set, as referenced at
+// https://datatracker.ietf.org/doc/html/rfc7519#section-4. They do not follow the
+// specification exactly, since they were based on an earlier draft of the
+// specification and not updated. The main difference is that they only
+// support integer-based date fields and singular audiences. This might lead to
+// incompatibilities with other JWT implementations. The use of this is discouraged, instead
+// the newer RegisteredClaims struct should be used.
+//
+// Deprecated: Use RegisteredClaims instead for a forward-compatible way to access registered claims in a struct.
+type StandardClaims struct {
+	Audience  string `json:"aud,omitempty"`
+	ExpiresAt int64  `json:"exp,omitempty"`
+	Id        string `json:"jti,omitempty"`
+	IssuedAt  int64  `json:"iat,omitempty"`
+	Issuer    string `json:"iss,omitempty"`
+	NotBefore int64  `json:"nbf,omitempty"`
+	Subject   string `json:"sub,omitempty"`
+}
+
+// Valid validates time based claims "exp, iat, nbf". There is no accounting for clock skew.
+// As well, if any of the above claims are not in the token, it will still
+// be considered a valid claim.
+func (c StandardClaims) Valid() error {
+	vErr := new(ValidationError)
+	now := TimeFunc().Unix()
+
+	// The claims below are optional, by default, so if they are set to the
+	// default value in Go, let's not fail the verification for them.
+	if !c.VerifyExpiresAt(now, false) {
+		delta := time.Unix(now, 0).Sub(time.Unix(c.ExpiresAt, 0))
+		vErr.Inner = fmt.Errorf("token is expired by %v", delta)
+		vErr.Errors |= ValidationErrorExpired
+	}
+
+	if !c.VerifyIssuedAt(now, false) {
+		vErr.Inner = fmt.Errorf("token used before issued")
+		vErr.Errors |= ValidationErrorIssuedAt
+	}
+
+	if !c.VerifyNotBefore(now, false) {
+		vErr.Inner = fmt.Errorf("token is not valid yet")
+		vErr.Errors |= ValidationErrorNotValidYet
+	}
+
+	if vErr.valid() {
+		return nil
+	}
+
+	return vErr
+}
+
+// VerifyAudience compares the aud claim against cmp.
+// If required is false, this method will return true if the value matches or is unset
+func (c *StandardClaims) VerifyAudience(cmp string, req bool) bool {
+	return verifyAud([]string{c.Audience}, cmp, req)
+}
+
+// VerifyExpiresAt compares the exp claim against cmp (cmp < exp).
+// If req is false, it will return true, if exp is unset.
+func (c *StandardClaims) VerifyExpiresAt(cmp int64, req bool) bool {
+	if c.ExpiresAt == 0 {
+		return verifyExp(nil, time.Unix(cmp, 0), req)
+	}
+
+	t := time.Unix(c.ExpiresAt, 0)
+	return verifyExp(&t, time.Unix(cmp, 0), req)
+}
+
+// VerifyIssuedAt compares the iat claim against cmp (cmp >= iat).
+// If req is false, it will return true, if iat is unset.
+func (c *StandardClaims) VerifyIssuedAt(cmp int64, req bool) bool {
+	if c.IssuedAt == 0 {
+		return verifyIat(nil, time.Unix(cmp, 0), req)
+	}
+
+	t := time.Unix(c.IssuedAt, 0)
+	return verifyIat(&t, time.Unix(cmp, 0), req)
+}
+
+// VerifyNotBefore compares the nbf claim against cmp (cmp >= nbf).
+// If req is false, it will return true, if nbf is unset.
+func (c *StandardClaims) VerifyNotBefore(cmp int64, req bool) bool {
+	if c.NotBefore == 0 {
+		return verifyNbf(nil, time.Unix(cmp, 0), req)
+	}
+
+	t := time.Unix(c.NotBefore, 0)
+	return verifyNbf(&t, time.Unix(cmp, 0), req)
+}
+
+// VerifyIssuer compares the iss claim against cmp.
+// If required is false, this method will return true if the value matches or is unset
+func (c *StandardClaims) VerifyIssuer(cmp string, req bool) bool {
+	return verifyIss(c.Issuer, cmp, req)
+}
+
+// ----- helpers
+
+func verifyAud(aud []string, cmp string, required bool) bool {
+	if len(aud) == 0 {
+		return !required
+	}
+	// 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 len(stringClaims) == 0 {
+		return !required
+	}
+
+	return result
+}
+
+func verifyExp(exp *time.Time, now time.Time, required bool) bool {
+	if exp == nil {
+		return !required
+	}
+	return now.Before(*exp)
+}
+
+func verifyIat(iat *time.Time, now time.Time, required bool) bool {
+	if iat == nil {
+		return !required
+	}
+	return now.After(*iat) || now.Equal(*iat)
+}
+
+func verifyNbf(nbf *time.Time, now time.Time, required bool) bool {
+	if nbf == nil {
+		return !required
+	}
+	return now.After(*nbf) || now.Equal(*nbf)
+}
+
+func verifyIss(iss string, cmp string, required bool) bool {
+	if iss == "" {
+		return !required
+	}
+	if subtle.ConstantTimeCompare([]byte(iss), []byte(cmp)) != 0 {
+		return true
+	} else {
+		return false
+	}
+}

+ 19 - 0
src/github.com/golang-jwt/jwt/v4/cmd/jwt/README.md

@@ -0,0 +1,19 @@
+`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/v4/cmd/jwt

+ 344 - 0
src/github.com/golang-jwt/jwt/v4/cmd/jwt/main.go

@@ -0,0 +1,344 @@
+// 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"
+	"io/ioutil"
+	"os"
+	"regexp"
+	"sort"
+	"strings"
+
+	"github.com/golang-jwt/jwt/v4"
+)
+
+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 object to sign, '-' to read from stdin, or '+' to use only -claim args")
+	flagVerify = flag.String("verify", "", "path to JWT token to verify or '-' to read from stdin")
+	flagShow   = flag.String("show", "", "path to JWT file 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\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 {
+	if *flagSign != "" {
+		return signToken()
+	} else if *flagVerify != "" {
+		return verifyToken()
+	} else if *flagShow != "" {
+		return showToken()
+	} else {
+		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
+	if p == "-" {
+		rdr = os.Stdin
+	} else if p == "+" {
+		return []byte("{}"), nil
+	} else {
+		if f, err := os.Open(p); err == nil {
+			rdr = f
+			defer f.Close()
+		} else {
+			return nil, err
+		}
+	}
+	return ioutil.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
+		}
+		if isEs() {
+			return jwt.ParseECPublicKeyFromPEM(data)
+		} else if isRs() {
+			return jwt.ParseRSAPublicKeyFromPEM(data)
+		} else if isEd() {
+			return jwt.ParseEdPublicKeyFromPEM(data)
+		}
+		return data, nil
+	})
+
+	// Print some debug data
+	if *flagDebug && token != nil {
+		fmt.Fprintf(os.Stderr, "Header:\n%v\n", token.Header)
+		fmt.Fprintf(os.Stderr, "Claims:\n%v\n", token.Claims)
+	}
+
+	// Print an error if we can't parse for some reason
+	if err != nil {
+		return fmt.Errorf("couldn't parse token: %w", err)
+	}
+
+	// Is token invalid?
+	if !token.Valid {
+		return fmt.Errorf("token is invalid")
+	}
+
+	// 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
+		}
+	}
+
+	if isEs() {
+		if k, ok := key.([]byte); !ok {
+			return fmt.Errorf("couldn't convert key data to key")
+		} else {
+			key, err = jwt.ParseECPrivateKeyFromPEM(k)
+			if err != nil {
+				return err
+			}
+		}
+	} else if isRs() {
+		if k, ok := key.([]byte); !ok {
+			return fmt.Errorf("couldn't convert key data to key")
+		} else {
+			key, err = jwt.ParseRSAPrivateKeyFromPEM(k)
+			if err != nil {
+				return err
+			}
+		}
+	} else if isEd() {
+		if k, ok := key.([]byte); !ok {
+			return fmt.Errorf("couldn't convert key data to key")
+		} else {
+			key, err = jwt.ParseEdPrivateKeyFromPEM(k)
+			if err != nil {
+				return err
+			}
+		}
+	}
+
+	if out, err := token.SignedString(key); err == nil {
+		fmt.Println(out)
+	} else {
+		return fmt.Errorf("error signing token: %w", err)
+	}
+
+	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.Parse(string(tokData), nil)
+	if token == 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
+}

+ 4 - 0
src/github.com/golang-jwt/jwt/v4/doc.go

@@ -0,0 +1,4 @@
+// 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

+ 142 - 0
src/github.com/golang-jwt/jwt/v4/ecdsa.go

@@ -0,0 +1,142 @@
+package 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, signature string, key interface{}) error {
+	var err error
+
+	// Decode the signature
+	var sig []byte
+	if sig, err = DecodeSegment(signature); err != nil {
+		return err
+	}
+
+	// Get the key
+	var ecdsaKey *ecdsa.PublicKey
+	switch k := key.(type) {
+	case *ecdsa.PublicKey:
+		ecdsaKey = k
+	default:
+		return 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{}) (string, error) {
+	// Get the key
+	var ecdsaKey *ecdsa.PrivateKey
+	switch k := key.(type) {
+	case *ecdsa.PrivateKey:
+		ecdsaKey = k
+	default:
+		return "", ErrInvalidKeyType
+	}
+
+	// Create the hasher
+	if !m.Hash.Available() {
+		return "", 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 "", 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 EncodeSegment(out), nil
+	} else {
+		return "", err
+	}
+}

+ 164 - 0
src/github.com/golang-jwt/jwt/v4/ecdsa_test.go

@@ -0,0 +1,164 @@
+package jwt_test
+
+import (
+	"crypto/ecdsa"
+	"io/ioutil"
+	"strings"
+	"testing"
+
+	"github.com/golang-jwt/jwt/v4"
+)
+
+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, _ := ioutil.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], "."), 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, _ := ioutil.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)
+			}
+			if sig == parts[2] {
+				t.Errorf("[%v] Identical signatures\nbefore:\n%v\nafter:\n%v", data.name, parts[2], sig)
+			}
+
+			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, _ := ioutil.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, _ := ioutil.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 sig == parts[2] {
+					b.Fatalf("[%v] Identical signatures\nbefore:\n%v\nafter:\n%v", data.name, parts[2], sig)
+				}
+			}
+		})
+	}
+}

+ 69 - 0
src/github.com/golang-jwt/jwt/v4/ecdsa_utils.go

@@ -0,0 +1,69 @@
+package 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
+}

+ 85 - 0
src/github.com/golang-jwt/jwt/v4/ed25519.go

@@ -0,0 +1,85 @@
+package jwt
+
+import (
+	"errors"
+
+	"crypto"
+	"crypto/ed25519"
+	"crypto/rand"
+)
+
+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, signature string, key interface{}) error {
+	var err error
+	var ed25519Key ed25519.PublicKey
+	var ok bool
+
+	if ed25519Key, ok = key.(ed25519.PublicKey); !ok {
+		return ErrInvalidKeyType
+	}
+
+	if len(ed25519Key) != ed25519.PublicKeySize {
+		return ErrInvalidKey
+	}
+
+	// Decode the signature
+	var sig []byte
+	if sig, err = DecodeSegment(signature); err != nil {
+		return err
+	}
+
+	// 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{}) (string, error) {
+	var ed25519Key crypto.Signer
+	var ok bool
+
+	if ed25519Key, ok = key.(crypto.Signer); !ok {
+		return "", ErrInvalidKeyType
+	}
+
+	if _, ok := ed25519Key.Public().(ed25519.PublicKey); !ok {
+		return "", ErrInvalidKey
+	}
+
+	// Sign the string and return the encoded 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 "", err
+	}
+	return EncodeSegment(sig), nil
+}

+ 84 - 0
src/github.com/golang-jwt/jwt/v4/ed25519_test.go

@@ -0,0 +1,84 @@
+package jwt_test
+
+import (
+	"io/ioutil"
+	"strings"
+	"testing"
+
+	"github.com/golang-jwt/jwt/v4"
+)
+
+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, _ := ioutil.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], "."), 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, _ := ioutil.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)
+		}
+		if sig == parts[2] && !data.valid {
+			t.Errorf("[%v] Identical signatures\nbefore:\n%v\nafter:\n%v", data.name, parts[2], sig)
+		}
+	}
+}

+ 64 - 0
src/github.com/golang-jwt/jwt/v4/ed25519_utils.go

@@ -0,0 +1,64 @@
+package 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
+}

+ 64 - 0
src/github.com/golang-jwt/jwt/v4/errors.go

@@ -0,0 +1,64 @@
+package jwt
+
+import (
+	"errors"
+)
+
+// Error constants
+var (
+	ErrInvalidKey      = errors.New("key is invalid")
+	ErrInvalidKeyType  = errors.New("key is of invalid type")
+	ErrHashUnavailable = errors.New("the requested hash function is unavailable")
+)
+
+// The errors that might occur when parsing and validating a token
+const (
+	ValidationErrorMalformed        uint32 = 1 << iota // Token is malformed
+	ValidationErrorUnverifiable                        // Token could not be verified because of signing problems
+	ValidationErrorSignatureInvalid                    // Signature validation failed
+
+	// Standard Claim validation errors
+	ValidationErrorAudience      // AUD validation failed
+	ValidationErrorExpired       // EXP validation failed
+	ValidationErrorIssuedAt      // IAT validation failed
+	ValidationErrorIssuer        // ISS validation failed
+	ValidationErrorNotValidYet   // NBF validation failed
+	ValidationErrorId            // JTI validation failed
+	ValidationErrorClaimsInvalid // Generic claims validation error
+)
+
+// NewValidationError is a helper for constructing a ValidationError with a string error message
+func NewValidationError(errorText string, errorFlags uint32) *ValidationError {
+	return &ValidationError{
+		text:   errorText,
+		Errors: errorFlags,
+	}
+}
+
+// ValidationError represents an error from Parse if token is not valid
+type ValidationError struct {
+	Inner  error  // stores the error returned by external dependencies, i.e.: KeyFunc
+	Errors uint32 // bitfield.  see ValidationError... constants
+	text   string // errors that do not have a valid error just have text
+}
+
+// Error is the implementation of the err interface.
+func (e ValidationError) Error() string {
+	if e.Inner != nil {
+		return e.Inner.Error()
+	} else if e.text != "" {
+		return e.text
+	} else {
+		return "token is invalid"
+	}
+}
+
+// Unwrap gives errors.Is and errors.As access to the inner error.
+func (e *ValidationError) Unwrap() error {
+	return e.Inner
+}
+
+// No errors
+func (e *ValidationError) valid() bool {
+	return e.Errors == 0
+}

+ 120 - 0
src/github.com/golang-jwt/jwt/v4/example_test.go

@@ -0,0 +1,120 @@
+package jwt_test
+
+import (
+	"fmt"
+	"time"
+
+	"github.com/golang-jwt/jwt/v4"
+)
+
+// 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.Printf("%v %v", ss, err)
+	//Output: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJ0ZXN0IiwiZXhwIjoxNTE2MjM5MDIyfQ.0XN_1Tpp9FszFOonIBpwha0c_SfnNI22DhTnjMshPg8 <nil>
+}
+
+// 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 the claims
+	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"},
+		},
+	}
+
+	// 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.Printf("%v %v", ss, err)
+
+	//Output: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIiLCJpc3MiOiJ0ZXN0IiwiZXhwIjoxNTE2MjM5MDIyfQ.xVuY2FZ_MRXMIEgVQ7J-TFtaucVFRXUzHm9LmV41goM <nil>
+}
+
+// Example creating a token using a custom claims type.  The StandardClaim 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 claims, ok := token.Claims.(*MyCustomClaims); ok && token.Valid {
+		fmt.Printf("%v %v", claims.Foo, claims.RegisteredClaims.Issuer)
+	} else {
+		fmt.Println(err)
+	}
+
+	// Output: bar test
+}
+
+// An example of parsing the error types using bitfield checks
+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
+	})
+
+	if token.Valid {
+		fmt.Println("You look nice today")
+	} else if ve, ok := err.(*jwt.ValidationError); ok {
+		if ve.Errors&jwt.ValidationErrorMalformed != 0 {
+			fmt.Println("That's not even a token")
+		} else if ve.Errors&(jwt.ValidationErrorExpired|jwt.ValidationErrorNotValidYet) != 0 {
+			// Token is either expired or not active yet
+			fmt.Println("Timing is everything")
+		} else {
+			fmt.Println("Couldn't handle this token:", err)
+		}
+	} else {
+		fmt.Println("Couldn't handle this token:", err)
+	}
+
+	// Output: Timing is everything
+}

+ 3 - 0
src/github.com/golang-jwt/jwt/v4/go.mod

@@ -0,0 +1,3 @@
+module github.com/golang-jwt/jwt/v4
+
+go 1.15

+ 0 - 0
src/github.com/golang-jwt/jwt/v4/go.sum


+ 95 - 0
src/github.com/golang-jwt/jwt/v4/hmac.go

@@ -0,0 +1,95 @@
+package 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.
+func (m *SigningMethodHMAC) Verify(signingString, signature string, key interface{}) error {
+	// Verify the key is the right type
+	keyBytes, ok := key.([]byte)
+	if !ok {
+		return ErrInvalidKeyType
+	}
+
+	// Decode signature, for comparison
+	sig, err := DecodeSegment(signature)
+	if err != nil {
+		return err
+	}
+
+	// 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
+func (m *SigningMethodHMAC) Sign(signingString string, key interface{}) (string, error) {
+	if keyBytes, ok := key.([]byte); ok {
+		if !m.Hash.Available() {
+			return "", ErrHashUnavailable
+		}
+
+		hasher := hmac.New(m.Hash.New, keyBytes)
+		hasher.Write([]byte(signingString))
+
+		return EncodeSegment(hasher.Sum(nil)), nil
+	}
+
+	return "", ErrInvalidKeyType
+}

+ 67 - 0
src/github.com/golang-jwt/jwt/v4/hmac_example_test.go

@@ -0,0 +1,67 @@
+package jwt_test
+
+import (
+	"fmt"
+	"io/ioutil"
+	"time"
+
+	"github.com/golang-jwt/jwt/v4"
+)
+
+// 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 := ioutil.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 <nil>
+}
+
+// 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) {
+		// Don't forget to validate the alg is what you expect:
+		if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
+			return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
+		}
+
+		// hmacSampleSecret is a []byte containing your secret, e.g. []byte("my_secret_key")
+		return hmacSampleSecret, nil
+	})
+
+	if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
+		fmt.Println(claims["foo"], claims["nbf"])
+	} else {
+		fmt.Println(err)
+	}
+
+	// Output: bar 1.4444784e+09
+}

+ 92 - 0
src/github.com/golang-jwt/jwt/v4/hmac_test.go

@@ -0,0 +1,92 @@
+package jwt_test
+
+import (
+	"io/ioutil"
+	"strings"
+	"testing"
+
+	"github.com/golang-jwt/jwt/v4"
+)
+
+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, _ = ioutil.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], "."), 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 {
+			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 sig != 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)
+}

+ 210 - 0
src/github.com/golang-jwt/jwt/v4/http_example_test.go

@@ -0,0 +1,210 @@
+package 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 (
+	"bytes"
+	"crypto/rsa"
+	"fmt"
+	"io"
+	"io/ioutil"
+	"log"
+	"net"
+	"net/http"
+	"net/url"
+	"strings"
+	"time"
+
+	"github.com/golang-jwt/jwt/v4"
+	"github.com/golang-jwt/jwt/v4/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 := ioutil.ReadFile(privKeyPath)
+	fatal(err)
+
+	signKey, err = jwt.ParseRSAPrivateKeyFromPEM(signBytes)
+	fatal(err)
+
+	verifyBytes, err := ioutil.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"},
+	})
+	if err != nil {
+		fatal(err)
+	}
+
+	if res.StatusCode != 200 {
+		fmt.Println("Unexpected status code", res.StatusCode)
+	}
+
+	// Read the token out of the response body
+	buf := new(bytes.Buffer)
+	io.Copy(buf, res.Body)
+	res.Body.Close()
+	tokenString := strings.TrimSpace(buf.String())
+
+	// 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 := new(bytes.Buffer)
+	io.Copy(buf, res.Body)
+	res.Body.Close()
+	fmt.Println(buf.String())
+
+	// 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)
+}

+ 148 - 0
src/github.com/golang-jwt/jwt/v4/map_claims.go

@@ -0,0 +1,148 @@
+package jwt
+
+import (
+	"encoding/json"
+	"errors"
+	"time"
+	// "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{}
+
+// VerifyAudience Compares the aud claim against cmp.
+// If required is false, this method will return true if the value matches or is unset
+func (m MapClaims) VerifyAudience(cmp string, req bool) bool {
+	var aud []string
+	switch v := m["aud"].(type) {
+	case string:
+		aud = append(aud, v)
+	case []string:
+		aud = v
+	case []interface{}:
+		for _, a := range v {
+			vs, ok := a.(string)
+			if !ok {
+				return false
+			}
+			aud = append(aud, vs)
+		}
+	}
+	return verifyAud(aud, cmp, req)
+}
+
+// VerifyExpiresAt compares the exp claim against cmp (cmp <= exp).
+// If req is false, it will return true, if exp is unset.
+func (m MapClaims) VerifyExpiresAt(cmp int64, req bool) bool {
+	cmpTime := time.Unix(cmp, 0)
+
+	v, ok := m["exp"]
+	if !ok {
+		return !req
+	}
+
+	switch exp := v.(type) {
+	case float64:
+		if exp == 0 {
+			return verifyExp(nil, cmpTime, req)
+		}
+
+		return verifyExp(&newNumericDateFromSeconds(exp).Time, cmpTime, req)
+	case json.Number:
+		v, _ := exp.Float64()
+
+		return verifyExp(&newNumericDateFromSeconds(v).Time, cmpTime, req)
+	}
+
+	return false
+}
+
+// VerifyIssuedAt compares the exp claim against cmp (cmp >= iat).
+// If req is false, it will return true, if iat is unset.
+func (m MapClaims) VerifyIssuedAt(cmp int64, req bool) bool {
+	cmpTime := time.Unix(cmp, 0)
+
+	v, ok := m["iat"]
+	if !ok {
+		return !req
+	}
+
+	switch iat := v.(type) {
+	case float64:
+		if iat == 0 {
+			return verifyIat(nil, cmpTime, req)
+		}
+
+		return verifyIat(&newNumericDateFromSeconds(iat).Time, cmpTime, req)
+	case json.Number:
+		v, _ := iat.Float64()
+
+		return verifyIat(&newNumericDateFromSeconds(v).Time, cmpTime, req)
+	}
+
+	return false
+}
+
+// VerifyNotBefore compares the nbf claim against cmp (cmp >= nbf).
+// If req is false, it will return true, if nbf is unset.
+func (m MapClaims) VerifyNotBefore(cmp int64, req bool) bool {
+	cmpTime := time.Unix(cmp, 0)
+
+	v, ok := m["nbf"]
+	if !ok {
+		return !req
+	}
+
+	switch nbf := v.(type) {
+	case float64:
+		if nbf == 0 {
+			return verifyNbf(nil, cmpTime, req)
+		}
+
+		return verifyNbf(&newNumericDateFromSeconds(nbf).Time, cmpTime, req)
+	case json.Number:
+		v, _ := nbf.Float64()
+
+		return verifyNbf(&newNumericDateFromSeconds(v).Time, cmpTime, req)
+	}
+
+	return false
+}
+
+// VerifyIssuer compares the iss claim against cmp.
+// If required is false, this method will return true if the value matches or is unset
+func (m MapClaims) VerifyIssuer(cmp string, req bool) bool {
+	iss, _ := m["iss"].(string)
+	return verifyIss(iss, cmp, req)
+}
+
+// Valid validates time based claims "exp, iat, nbf".
+// There is no accounting for clock skew.
+// As well, if any of the above claims are not in the token, it will still
+// be considered a valid claim.
+func (m MapClaims) Valid() error {
+	vErr := new(ValidationError)
+	now := TimeFunc().Unix()
+
+	if !m.VerifyExpiresAt(now, false) {
+		vErr.Inner = errors.New("Token is expired")
+		vErr.Errors |= ValidationErrorExpired
+	}
+
+	if !m.VerifyIssuedAt(now, false) {
+		vErr.Inner = errors.New("Token used before issued")
+		vErr.Errors |= ValidationErrorIssuedAt
+	}
+
+	if !m.VerifyNotBefore(now, false) {
+		vErr.Inner = errors.New("Token is not valid yet")
+		vErr.Errors |= ValidationErrorNotValidYet
+	}
+
+	if vErr.valid() {
+		return nil
+	}
+
+	return vErr
+}

+ 123 - 0
src/github.com/golang-jwt/jwt/v4/map_claims_test.go

@@ -0,0 +1,123 @@
+package 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: false, Required: true, 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 wit match required", MapClaims: MapClaims{"aud": []interface{}{"a", "foo", "example.com"}}, Expected: true, Required: true, Comparison: "example.com"},
+		{Name: "[]interface{} Aud wit match but invalid types", MapClaims: MapClaims{"aud": []interface{}{"a", 5, "example.com"}}, Expected: false, Required: true, Comparison: "example.com"},
+		{Name: "[]interface{} Aud int wit 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) {
+			got := test.MapClaims.VerifyAudience(test.Comparison, test.Required)
+
+			if got != test.Expected {
+				t.Errorf("Expected %v, got %v", test.Expected, got)
+			}
+		})
+	}
+}
+
+func TestMapclaimsVerifyIssuedAtInvalidTypeString(t *testing.T) {
+	mapClaims := MapClaims{
+		"iat": "foo",
+	}
+	want := false
+	got := mapClaims.VerifyIssuedAt(0, false)
+	if want != got {
+		t.Fatalf("Failed to verify claims, wanted: %v got %v", want, got)
+	}
+}
+
+func TestMapclaimsVerifyNotBeforeInvalidTypeString(t *testing.T) {
+	mapClaims := MapClaims{
+		"nbf": "foo",
+	}
+	want := false
+	got := mapClaims.VerifyNotBefore(0, false)
+	if want != got {
+		t.Fatalf("Failed to verify claims, wanted: %v got %v", want, got)
+	}
+}
+
+func TestMapclaimsVerifyExpiresAtInvalidTypeString(t *testing.T) {
+	mapClaims := MapClaims{
+		"exp": "foo",
+	}
+	want := false
+	got := mapClaims.VerifyExpiresAt(0, false)
+
+	if want != got {
+		t.Fatalf("Failed to verify claims, wanted: %v got %v", want, got)
+	}
+}
+
+func TestMapClaimsVerifyExpiresAtExpire(t *testing.T) {
+	exp := time.Now().Unix()
+	mapClaims := MapClaims{
+		"exp": float64(exp),
+	}
+	want := false
+	got := mapClaims.VerifyExpiresAt(exp, true)
+	if want != got {
+		t.Fatalf("Failed to verify claims, wanted: %v got %v", want, got)
+	}
+
+	got = mapClaims.VerifyExpiresAt(exp + 1, true)
+	if want != got {
+		t.Fatalf("Failed to verify claims, wanted: %v got %v", want, got)
+	}
+
+	want = true
+	got = mapClaims.VerifyExpiresAt(exp - 1, true)
+	if want != got {
+		t.Fatalf("Failed to verify claims, wanted: %v got %v", want, got)
+	}
+}

+ 52 - 0
src/github.com/golang-jwt/jwt/v4/none.go

@@ -0,0 +1,52 @@
+package 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 = NewValidationError("'none' signature type is not allowed", ValidationErrorSignatureInvalid)
+
+	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, signature string, 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 signature != "" {
+		return NewValidationError(
+			"'none' signing method with non-empty signature",
+			ValidationErrorSignatureInvalid,
+		)
+	}
+
+	// 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{}) (string, error) {
+	if _, ok := key.(unsafeNoneMagicConstant); ok {
+		return "", nil
+	}
+	return "", NoneSignatureTypeDisallowedError
+}

+ 73 - 0
src/github.com/golang-jwt/jwt/v4/none_test.go

@@ -0,0 +1,73 @@
+package jwt_test
+
+import (
+	"strings"
+	"testing"
+
+	"github.com/golang-jwt/jwt/v4"
+)
+
+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], "."), 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 {
+			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 sig != parts[2] {
+				t.Errorf("[%v] Incorrect signature.\nwas:\n%v\nexpecting:\n%v", data.name, sig, parts[2])
+			}
+		}
+	}
+}

+ 170 - 0
src/github.com/golang-jwt/jwt/v4/parser.go

@@ -0,0 +1,170 @@
+package jwt
+
+import (
+	"bytes"
+	"encoding/json"
+	"fmt"
+	"strings"
+)
+
+type Parser struct {
+	// If populated, only these methods will be considered valid.
+	//
+	// Deprecated: In future releases, this field will not be exported anymore and should be set with an option to NewParser instead.
+	ValidMethods []string
+
+	// Use JSON Number format in JSON decoder.
+	//
+	// Deprecated: In future releases, this field will not be exported anymore and should be set with an option to NewParser instead.
+	UseJSONNumber bool
+
+	// Skip claims validation during token parsing.
+	//
+	// Deprecated: In future releases, this field will not be exported anymore and should be set with an option to NewParser instead.
+	SkipClaimsValidation bool
+}
+
+// NewParser creates a new Parser with the specified options
+func NewParser(options ...ParserOption) *Parser {
+	p := &Parser{}
+
+	// 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)
+}
+
+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, NewValidationError(fmt.Sprintf("signing method %v is invalid", alg), ValidationErrorSignatureInvalid)
+		}
+	}
+
+	// Lookup key
+	var key interface{}
+	if keyFunc == nil {
+		// keyFunc was not provided.  short circuiting validation
+		return token, NewValidationError("no Keyfunc was provided.", ValidationErrorUnverifiable)
+	}
+	if key, err = keyFunc(token); err != nil {
+		// keyFunc returned an error
+		if ve, ok := err.(*ValidationError); ok {
+			return token, ve
+		}
+		return token, &ValidationError{Inner: err, Errors: ValidationErrorUnverifiable}
+	}
+
+	vErr := &ValidationError{}
+
+	// Validate Claims
+	if !p.SkipClaimsValidation {
+		if err := token.Claims.Valid(); err != nil {
+
+			// If the Claims Valid returned an error, check if it is a validation error,
+			// If it was another error type, create a ValidationError with a generic ClaimsInvalid flag set
+			if e, ok := err.(*ValidationError); !ok {
+				vErr = &ValidationError{Inner: err, Errors: ValidationErrorClaimsInvalid}
+			} else {
+				vErr = e
+			}
+		}
+	}
+
+	// Perform validation
+	token.Signature = parts[2]
+	if err = token.Method.Verify(strings.Join(parts[0:2], "."), token.Signature, key); err != nil {
+		vErr.Inner = err
+		vErr.Errors |= ValidationErrorSignatureInvalid
+	}
+
+	if vErr.valid() {
+		token.Valid = true
+		return token, nil
+	}
+
+	return token, vErr
+}
+
+// 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 (because it has
+// been checked previously 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) {
+	parts = strings.Split(tokenString, ".")
+	if len(parts) != 3 {
+		return nil, parts, NewValidationError("token contains an invalid number of segments", ValidationErrorMalformed)
+	}
+
+	token = &Token{Raw: tokenString}
+
+	// parse Header
+	var headerBytes []byte
+	if headerBytes, err = DecodeSegment(parts[0]); err != nil {
+		if strings.HasPrefix(strings.ToLower(tokenString), "bearer ") {
+			return token, parts, NewValidationError("tokenstring should not contain 'bearer '", ValidationErrorMalformed)
+		}
+		return token, parts, &ValidationError{Inner: err, Errors: ValidationErrorMalformed}
+	}
+	if err = json.Unmarshal(headerBytes, &token.Header); err != nil {
+		return token, parts, &ValidationError{Inner: err, Errors: ValidationErrorMalformed}
+	}
+
+	// parse Claims
+	var claimBytes []byte
+	token.Claims = claims
+
+	if claimBytes, err = DecodeSegment(parts[1]); err != nil {
+		return token, parts, &ValidationError{Inner: err, Errors: ValidationErrorMalformed}
+	}
+	dec := json.NewDecoder(bytes.NewBuffer(claimBytes))
+	if p.UseJSONNumber {
+		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)
+	}
+	// Handle decode error
+	if err != nil {
+		return token, parts, &ValidationError{Inner: err, Errors: ValidationErrorMalformed}
+	}
+
+	// Lookup signature method
+	if method, ok := token.Header["alg"].(string); ok {
+		if token.Method = GetSigningMethod(method); token.Method == nil {
+			return token, parts, NewValidationError("signing method (alg) is unavailable.", ValidationErrorUnverifiable)
+		}
+	} else {
+		return token, parts, NewValidationError("signing method (alg) is unspecified.", ValidationErrorUnverifiable)
+	}
+
+	return token, parts, nil
+}

+ 29 - 0
src/github.com/golang-jwt/jwt/v4/parser_option.go

@@ -0,0 +1,29 @@
+package jwt
+
+// ParserOption is used to implement functional-style options that modify the behaviour 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 underyling 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
+	}
+}

+ 602 - 0
src/github.com/golang-jwt/jwt/v4/parser_test.go

@@ -0,0 +1,602 @@
+package jwt_test
+
+import (
+	"crypto"
+	"crypto/rsa"
+	"encoding/json"
+	"fmt"
+	"reflect"
+	"testing"
+	"time"
+
+	"github.com/golang-jwt/jwt/v4"
+	"github.com/golang-jwt/jwt/v4/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
+)
+
+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
+	errors        uint32
+	parser        *jwt.Parser
+	signingMethod jwt.SigningMethod // The method to sign the JWT token for test purpose
+}{
+	{
+		"basic",
+		"eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJmb28iOiJiYXIifQ.FhkiHkoESI_cG3NPigFrxEk9Z60_oXrOT2vGm9Pn6RDgYNovYORQmmA0zs1AoAOf09ly2Nx2YAg6ABqAYga1AcMFkJljwxTT5fYphTuqpWdy4BELeSYJx5Ty2gmr8e7RonuUztrdD5WfPqLKMm1Ozp_T6zALpRmwTIW0QPnaBXaQD90FplAg46Iy1UlDKr-Eupy0i5SLch5Q-p2ZpaL_5fnTIUDlxC3pWhJTyx_71qDI-mAA_5lE_VdroOeflG56sSmDxopPEG3bFlSu1eowyBfxtu0_CuVd-M42RU75Zc4Gsj6uV77MBtbMrf4_7M_NUTSgoIF3fRqxrj0NzihIBg",
+		defaultKeyFunc,
+		jwt.MapClaims{"foo": "bar"},
+		true,
+		0,
+		nil,
+		jwt.SigningMethodRS256,
+	},
+	{
+		"basic expired",
+		"", // autogen
+		defaultKeyFunc,
+		jwt.MapClaims{"foo": "bar", "exp": float64(time.Now().Unix() - 100)},
+		false,
+		jwt.ValidationErrorExpired,
+		nil,
+		jwt.SigningMethodRS256,
+	},
+	{
+		"basic nbf",
+		"", // autogen
+		defaultKeyFunc,
+		jwt.MapClaims{"foo": "bar", "nbf": float64(time.Now().Unix() + 100)},
+		false,
+		jwt.ValidationErrorNotValidYet,
+		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,
+		jwt.ValidationErrorNotValidYet | jwt.ValidationErrorExpired,
+		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,
+		jwt.ValidationErrorSignatureInvalid,
+		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,
+		jwt.ValidationErrorUnverifiable,
+		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,
+		jwt.ValidationErrorSignatureInvalid,
+		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,
+		jwt.ValidationErrorUnverifiable,
+		nil,
+		jwt.SigningMethodRS256,
+	},
+	{
+		"invalid signing method",
+		"",
+		defaultKeyFunc,
+		jwt.MapClaims{"foo": "bar"},
+		false,
+		jwt.ValidationErrorSignatureInvalid,
+		&jwt.Parser{ValidMethods: []string{"HS256"}},
+		jwt.SigningMethodRS256,
+	},
+	{
+		"valid RSA signing method",
+		"",
+		defaultKeyFunc,
+		jwt.MapClaims{"foo": "bar"},
+		true,
+		0,
+		&jwt.Parser{ValidMethods: []string{"RS256", "HS256"}},
+		jwt.SigningMethodRS256,
+	},
+	{
+		"ECDSA signing method not accepted",
+		"",
+		ecdsaKeyFunc,
+		jwt.MapClaims{"foo": "bar"},
+		false,
+		jwt.ValidationErrorSignatureInvalid,
+		&jwt.Parser{ValidMethods: []string{"RS256", "HS256"}},
+		jwt.SigningMethodES256,
+	},
+	{
+		"valid ECDSA signing method",
+		"",
+		ecdsaKeyFunc,
+		jwt.MapClaims{"foo": "bar"},
+		true,
+		0,
+		&jwt.Parser{ValidMethods: []string{"HS256", "ES256"}},
+		jwt.SigningMethodES256,
+	},
+	{
+		"JSON Number",
+		"",
+		defaultKeyFunc,
+		jwt.MapClaims{"foo": json.Number("123.4")},
+		true,
+		0,
+		&jwt.Parser{UseJSONNumber: true},
+		jwt.SigningMethodRS256,
+	},
+	{
+		"Standard Claims",
+		"",
+		defaultKeyFunc,
+		&jwt.StandardClaims{
+			ExpiresAt: time.Now().Add(time.Second * 10).Unix(),
+		},
+		true,
+		0,
+		&jwt.Parser{UseJSONNumber: true},
+		jwt.SigningMethodRS256,
+	},
+	{
+		"JSON Number - basic expired",
+		"", // autogen
+		defaultKeyFunc,
+		jwt.MapClaims{"foo": "bar", "exp": json.Number(fmt.Sprintf("%v", time.Now().Unix()-100))},
+		false,
+		jwt.ValidationErrorExpired,
+		&jwt.Parser{UseJSONNumber: true},
+		jwt.SigningMethodRS256,
+	},
+	{
+		"JSON Number - basic nbf",
+		"", // autogen
+		defaultKeyFunc,
+		jwt.MapClaims{"foo": "bar", "nbf": json.Number(fmt.Sprintf("%v", time.Now().Unix()+100))},
+		false,
+		jwt.ValidationErrorNotValidYet,
+		&jwt.Parser{UseJSONNumber: true},
+		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,
+		jwt.ValidationErrorNotValidYet | jwt.ValidationErrorExpired,
+		&jwt.Parser{UseJSONNumber: true},
+		jwt.SigningMethodRS256,
+	},
+	{
+		"SkipClaimsValidation during token parsing",
+		"", // autogen
+		defaultKeyFunc,
+		jwt.MapClaims{"foo": "bar", "nbf": json.Number(fmt.Sprintf("%v", time.Now().Unix()+100))},
+		true,
+		0,
+		&jwt.Parser{UseJSONNumber: true, SkipClaimsValidation: true},
+		jwt.SigningMethodRS256,
+	},
+	{
+		"RFC7519 Claims",
+		"",
+		defaultKeyFunc,
+		&jwt.RegisteredClaims{
+			ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Second * 10)),
+		},
+		true,
+		0,
+		&jwt.Parser{UseJSONNumber: true},
+		jwt.SigningMethodRS256,
+	},
+	{
+		"RFC7519 Claims - single aud",
+		"",
+		defaultKeyFunc,
+		&jwt.RegisteredClaims{
+			Audience: jwt.ClaimStrings{"test"},
+		},
+		true,
+		0,
+		&jwt.Parser{UseJSONNumber: true},
+		jwt.SigningMethodRS256,
+	},
+	{
+		"RFC7519 Claims - multiple aud",
+		"",
+		defaultKeyFunc,
+		&jwt.RegisteredClaims{
+			Audience: jwt.ClaimStrings{"test", "test"},
+		},
+		true,
+		0,
+		&jwt.Parser{UseJSONNumber: true},
+		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,
+		jwt.ValidationErrorMalformed,
+		&jwt.Parser{UseJSONNumber: true},
+		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,
+		jwt.ValidationErrorMalformed,
+		&jwt.Parser{UseJSONNumber: true},
+		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 = new(jwt.Parser)
+			}
+			// Figure out correct claims type
+			switch data.claims.(type) {
+			case jwt.MapClaims:
+				token, err = parser.ParseWithClaims(data.tokenString, jwt.MapClaims{}, data.keyfunc)
+			case *jwt.StandardClaims:
+				token, err = parser.ParseWithClaims(data.tokenString, &jwt.StandardClaims{}, data.keyfunc)
+			case *jwt.RegisteredClaims:
+				token, err = parser.ParseWithClaims(data.tokenString, &jwt.RegisteredClaims{}, data.keyfunc)
+			}
+
+			// 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 !data.valid && err == nil {
+				t.Errorf("[%v] Invalid token passed validation", data.name)
+			}
+
+			if (err == nil && !token.Valid) || (err != nil && token.Valid) {
+				t.Errorf("[%v] Inconsistent behavior between returned error and token.Valid", data.name)
+			}
+
+			if data.errors != 0 {
+				if err == nil {
+					t.Errorf("[%v] Expecting error. Didn't get one.", data.name)
+				} else {
+
+					ve := err.(*jwt.ValidationError)
+					// compare the bitfield part of the error
+					if e := ve.Errors; e != data.errors {
+						t.Errorf("[%v] Errors don't match expectation.  %v != %v", data.name, e, data.errors)
+					}
+
+					if err.Error() == errKeyFuncError.Error() && ve.Inner != errKeyFuncError {
+						t.Errorf("[%v] Inner error does not match expectation.  %v != %v", data.name, ve.Inner, errKeyFuncError)
+					}
+				}
+			}
+			if data.valid {
+				if token.Signature == "" {
+					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 data.errors&jwt.ValidationErrorMalformed != 0 {
+			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.StandardClaims:
+				token, _, err = parser.ParseUnverified(data.tokenString, &jwt.StandardClaims{})
+			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 token.Signature != "" {
+				// 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
+	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,
+	},
+}
+
+// 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
+			jwt.DecodePaddingAllowed = data.paddedDecode
+
+			if data.tokenString == "" {
+				data.tokenString = signToken(data.claims, data.signingMethod)
+
+			}
+
+			// Parse the token
+			var token *jwt.Token
+			var err error
+			parser := new(jwt.Parser)
+			parser.SkipClaimsValidation = true
+
+			// 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,
+				)
+			}
+
+		})
+		jwt.DecodePaddingAllowed = false
+
+	}
+}
+
+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.StandardClaims:
+			b.Run("standard_claims", func(b *testing.B) {
+				benchmarkParsing(b, parser, data.tokenString, &jwt.StandardClaims{})
+			})
+		}
+	}
+}
+
+// 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)
+			}
+		}
+	})
+}

+ 7 - 0
src/github.com/golang-jwt/jwt/v4/request/doc.go

@@ -0,0 +1,7 @@
+// 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

+ 81 - 0
src/github.com/golang-jwt/jwt/v4/request/extractor.go

@@ -0,0 +1,81 @@
+package request
+
+import (
+	"errors"
+	"net/http"
+)
+
+// 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
+	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 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
+	}
+}

+ 32 - 0
src/github.com/golang-jwt/jwt/v4/request/extractor_example_test.go

@@ -0,0 +1,32 @@
+package 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
+}

+ 91 - 0
src/github.com/golang-jwt/jwt/v4/request/extractor_test.go

@@ -0,0 +1,91 @@
+package 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
+}

+ 28 - 0
src/github.com/golang-jwt/jwt/v4/request/oauth2.go

@@ -0,0 +1,28 @@
+package 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.ToUpper(tok[0: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"},
+}

+ 70 - 0
src/github.com/golang-jwt/jwt/v4/request/request.go

@@ -0,0 +1,70 @@
+package request
+
+import (
+	"net/http"
+
+	"github.com/golang-jwt/jwt/v4"
+)
+
+// 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
+	}
+}

+ 104 - 0
src/github.com/golang-jwt/jwt/v4/request/request_test.go

@@ -0,0 +1,104 @@
+package request
+
+import (
+	"fmt"
+	"net/http"
+	"net/url"
+	"reflect"
+	"strings"
+	"testing"
+
+	"github.com/golang-jwt/jwt/v4"
+	"github.com/golang-jwt/jwt/v4/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)
+		}
+	}
+}

+ 101 - 0
src/github.com/golang-jwt/jwt/v4/rsa.go

@@ -0,0 +1,101 @@
+package 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, signature string, key interface{}) error {
+	var err error
+
+	// Decode the signature
+	var sig []byte
+	if sig, err = DecodeSegment(signature); err != nil {
+		return err
+	}
+
+	var rsaKey *rsa.PublicKey
+	var ok bool
+
+	if rsaKey, ok = key.(*rsa.PublicKey); !ok {
+		return 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{}) (string, error) {
+	var rsaKey *rsa.PrivateKey
+	var ok bool
+
+	// Validate type of key
+	if rsaKey, ok = key.(*rsa.PrivateKey); !ok {
+		return "", ErrInvalidKey
+	}
+
+	// Create the hasher
+	if !m.Hash.Available() {
+		return "", 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 EncodeSegment(sigBytes), nil
+	} else {
+		return "", err
+	}
+}

+ 142 - 0
src/github.com/golang-jwt/jwt/v4/rsa_pss.go

@@ -0,0 +1,142 @@
+// +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, signature string, key interface{}) error {
+	var err error
+
+	// Decode the signature
+	var sig []byte
+	if sig, err = DecodeSegment(signature); err != nil {
+		return err
+	}
+
+	var rsaKey *rsa.PublicKey
+	switch k := key.(type) {
+	case *rsa.PublicKey:
+		rsaKey = k
+	default:
+		return ErrInvalidKey
+	}
+
+	// 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{}) (string, error) {
+	var rsaKey *rsa.PrivateKey
+
+	switch k := key.(type) {
+	case *rsa.PrivateKey:
+		rsaKey = k
+	default:
+		return "", ErrInvalidKeyType
+	}
+
+	// Create the hasher
+	if !m.Hash.Available() {
+		return "", 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 EncodeSegment(sigBytes), nil
+	} else {
+		return "", err
+	}
+}

+ 150 - 0
src/github.com/golang-jwt/jwt/v4/rsa_pss_test.go

@@ -0,0 +1,150 @@
+// +build go1.4
+
+package jwt_test
+
+import (
+	"crypto/rsa"
+	"io/ioutil"
+	"strings"
+	"testing"
+	"time"
+
+	"github.com/golang-jwt/jwt/v4"
+	"github.com/golang-jwt/jwt/v4/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, _ := ioutil.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], "."), 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, _ := ioutil.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 {
+			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)
+			}
+			if sig == parts[2] {
+				t.Errorf("[%v] Signatures shouldn't match\nnew:\n%v\noriginal:\n%v", data.name, sig, 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(jwt.SigningMethodPS256, makeToken(ps256SaltLengthEqualsHash)) {
+		t.Error("SigningMethodPS256 should accept salt length that is defined in RFC")
+	}
+	if !verify(ps256SaltLengthEqualsHash, makeToken(jwt.SigningMethodPS256)) {
+		t.Error("Sign by SigningMethodPS256 should have salt length that is defined in RFC")
+	}
+	if !verify(jwt.SigningMethodPS256, makeToken(ps256SaltLengthAuto)) {
+		t.Error("SigningMethodPS256 should accept auto salt length to be compatible with previous versions")
+	}
+	if !verify(ps256SaltLengthAuto, makeToken(jwt.SigningMethodPS256)) {
+		t.Error("Sign by SigningMethodPS256 should be accepted by previous versions")
+	}
+	if verify(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(signingMethod jwt.SigningMethod, token string) bool {
+	segments := strings.Split(token, ".")
+	err := signingMethod.Verify(strings.Join(segments[:2], "."), segments[2], test.LoadRSAPublicKeyFromDisk("test/sample_key.pub"))
+	return err == nil
+}

+ 200 - 0
src/github.com/golang-jwt/jwt/v4/rsa_test.go

@@ -0,0 +1,200 @@
+package jwt_test
+
+import (
+	"io/ioutil"
+	"strings"
+	"testing"
+
+	"github.com/golang-jwt/jwt/v4"
+)
+
+var rsaTestData = []struct {
+	name        string
+	tokenString string
+	alg         string
+	claims      map[string]interface{}
+	valid       bool
+}{
+	{
+		"Basic RS256",
+		"eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJmb28iOiJiYXIifQ.FhkiHkoESI_cG3NPigFrxEk9Z60_oXrOT2vGm9Pn6RDgYNovYORQmmA0zs1AoAOf09ly2Nx2YAg6ABqAYga1AcMFkJljwxTT5fYphTuqpWdy4BELeSYJx5Ty2gmr8e7RonuUztrdD5WfPqLKMm1Ozp_T6zALpRmwTIW0QPnaBXaQD90FplAg46Iy1UlDKr-Eupy0i5SLch5Q-p2ZpaL_5fnTIUDlxC3pWhJTyx_71qDI-mAA_5lE_VdroOeflG56sSmDxopPEG3bFlSu1eowyBfxtu0_CuVd-M42RU75Zc4Gsj6uV77MBtbMrf4_7M_NUTSgoIF3fRqxrj0NzihIBg",
+		"RS256",
+		map[string]interface{}{"foo": "bar"},
+		true,
+	},
+	{
+		"Basic RS384",
+		"eyJhbGciOiJSUzM4NCIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIifQ.W-jEzRfBigtCWsinvVVuldiuilzVdU5ty0MvpLaSaqK9PlAWWlDQ1VIQ_qSKzwL5IXaZkvZFJXT3yL3n7OUVu7zCNJzdwznbC8Z-b0z2lYvcklJYi2VOFRcGbJtXUqgjk2oGsiqUMUMOLP70TTefkpsgqDxbRh9CDUfpOJgW-dU7cmgaoswe3wjUAUi6B6G2YEaiuXC0XScQYSYVKIzgKXJV8Zw-7AN_DBUI4GkTpsvQ9fVVjZM9csQiEXhYekyrKu1nu_POpQonGd8yqkIyXPECNmmqH5jH4sFiF67XhD7_JpkvLziBpI-uh86evBUadmHhb9Otqw3uV3NTaXLzJw",
+		"RS384",
+		map[string]interface{}{"foo": "bar"},
+		true,
+	},
+	{
+		"Basic RS512",
+		"eyJhbGciOiJSUzUxMiIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIifQ.zBlLlmRrUxx4SJPUbV37Q1joRcI9EW13grnKduK3wtYKmDXbgDpF1cZ6B-2Jsm5RB8REmMiLpGms-EjXhgnyh2TSHE-9W2gA_jvshegLWtwRVDX40ODSkTb7OVuaWgiy9y7llvcknFBTIg-FnVPVpXMmeV_pvwQyhaz1SSwSPrDyxEmksz1hq7YONXhXPpGaNbMMeDTNP_1oj8DZaqTIL9TwV8_1wb2Odt_Fy58Ke2RVFijsOLdnyEAjt2n9Mxihu9i3PhNBkkxa2GbnXBfq3kzvZ_xxGGopLdHhJjcGWXO-NiwI9_tiu14NRv4L2xC0ItD9Yz68v2ZIZEp_DuzwRQ",
+		"RS512",
+		map[string]interface{}{"foo": "bar"},
+		true,
+	},
+	{
+		"basic invalid: foo => bar",
+		"eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJmb28iOiJiYXIifQ.EhkiHkoESI_cG3NPigFrxEk9Z60_oXrOT2vGm9Pn6RDgYNovYORQmmA0zs1AoAOf09ly2Nx2YAg6ABqAYga1AcMFkJljwxTT5fYphTuqpWdy4BELeSYJx5Ty2gmr8e7RonuUztrdD5WfPqLKMm1Ozp_T6zALpRmwTIW0QPnaBXaQD90FplAg46Iy1UlDKr-Eupy0i5SLch5Q-p2ZpaL_5fnTIUDlxC3pWhJTyx_71qDI-mAA_5lE_VdroOeflG56sSmDxopPEG3bFlSu1eowyBfxtu0_CuVd-M42RU75Zc4Gsj6uV77MBtbMrf4_7M_NUTSgoIF3fRqxrj0NzihIBg",
+		"RS256",
+		map[string]interface{}{"foo": "bar"},
+		false,
+	},
+}
+
+func TestRSAVerify(t *testing.T) {
+	keyData, _ := ioutil.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], "."), 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, _ := ioutil.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 sig != parts[2] {
+				t.Errorf("[%v] Incorrect signature.\nwas:\n%v\nexpecting:\n%v", data.name, sig, parts[2])
+			}
+		}
+	}
+}
+
+func TestRSAVerifyWithPreParsedPrivateKey(t *testing.T) {
+	key, _ := ioutil.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], "."), parts[2], parsedKey)
+	if err != nil {
+		t.Errorf("[%v] Error while verifying key: %v", testData.name, err)
+	}
+}
+
+func TestRSAWithPreParsedPrivateKey(t *testing.T) {
+	key, _ := ioutil.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 sig != parts[2] {
+		t.Errorf("[%v] Incorrect signature.\nwas:\n%v\nexpecting:\n%v", testData.name, sig, parts[2])
+	}
+}
+
+func TestRSAKeyParsing(t *testing.T) {
+	key, _ := ioutil.ReadFile("test/sample_key")
+	secureKey, _ := ioutil.ReadFile("test/privateSecure.pem")
+	pubKey, _ := ioutil.ReadFile("test/sample_key.pub")
+	badKey := []byte("All your base are belong to key")
+
+	// 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)
+	}
+
+}
+
+func BenchmarkRSAParsing(b *testing.B) {
+	key, _ := ioutil.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, _ := ioutil.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, _ := ioutil.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, _ := ioutil.ReadFile("test/sample_key")
+	parsedKey, err := jwt.ParseRSAPrivateKeyFromPEM(key)
+	if err != nil {
+		b.Fatal(err)
+	}
+
+	benchmarkSigning(b, jwt.SigningMethodRS512, parsedKey)
+}

+ 105 - 0
src/github.com/golang-jwt/jwt/v4/rsa_utils.go

@@ -0,0 +1,105 @@
+package 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 PEM encoded PKCS1 or PKCS8 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 {
+			return nil, err
+		}
+	}
+
+	var pkey *rsa.PublicKey
+	var ok bool
+	if pkey, ok = parsedKey.(*rsa.PublicKey); !ok {
+		return nil, ErrNotRSAPublicKey
+	}
+
+	return pkey, nil
+}

+ 46 - 0
src/github.com/golang-jwt/jwt/v4/signing_method.go

@@ -0,0 +1,46 @@
+package 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.
+type SigningMethod interface {
+	Verify(signingString, signature string, key interface{}) error // Returns nil if signature is valid
+	Sign(signingString string, key interface{}) (string, error)    // Returns encoded 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
+}

+ 1 - 0
src/github.com/golang-jwt/jwt/v4/staticcheck.conf

@@ -0,0 +1 @@
+checks = ["all", "-ST1000", "-ST1003", "-ST1016", "-ST1023"]

+ 5 - 0
src/github.com/golang-jwt/jwt/v4/test/ec256-private.pem

@@ -0,0 +1,5 @@
+-----BEGIN EC PRIVATE KEY-----
+MHcCAQEEIAh5qA3rmqQQuu0vbKV/+zouz/y/Iy2pLpIcWUSyImSwoAoGCCqGSM49
+AwEHoUQDQgAEYD54V/vp+54P9DXarYqx4MPcm+HKRIQzNasYSoRQHQ/6S6Ps8tpM
+cT+KvIIC8W/e9k0W7Cm72M1P9jU7SLf/vg==
+-----END EC PRIVATE KEY-----

+ 4 - 0
src/github.com/golang-jwt/jwt/v4/test/ec256-public.pem

@@ -0,0 +1,4 @@
+-----BEGIN PUBLIC KEY-----
+MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEYD54V/vp+54P9DXarYqx4MPcm+HK
+RIQzNasYSoRQHQ/6S6Ps8tpMcT+KvIIC8W/e9k0W7Cm72M1P9jU7SLf/vg==
+-----END PUBLIC KEY-----

+ 6 - 0
src/github.com/golang-jwt/jwt/v4/test/ec384-private.pem

@@ -0,0 +1,6 @@
+-----BEGIN EC PRIVATE KEY-----
+MIGkAgEBBDCaCvMHKhcG/qT7xsNLYnDT7sE/D+TtWIol1ROdaK1a564vx5pHbsRy
+SEKcIxISi1igBwYFK4EEACKhZANiAATYa7rJaU7feLMqrAx6adZFNQOpaUH/Uylb
+ZLriOLON5YFVwtVUpO1FfEXZUIQpptRPtc5ixIPY658yhBSb6irfIJUSP9aYTflJ
+GKk/mDkK4t8mWBzhiD5B6jg9cEGhGgA=
+-----END EC PRIVATE KEY-----

+ 5 - 0
src/github.com/golang-jwt/jwt/v4/test/ec384-public.pem

@@ -0,0 +1,5 @@
+-----BEGIN PUBLIC KEY-----
+MHYwEAYHKoZIzj0CAQYFK4EEACIDYgAE2Gu6yWlO33izKqwMemnWRTUDqWlB/1Mp
+W2S64jizjeWBVcLVVKTtRXxF2VCEKabUT7XOYsSD2OufMoQUm+oq3yCVEj/WmE35
+SRipP5g5CuLfJlgc4Yg+Qeo4PXBBoRoA
+-----END PUBLIC KEY-----

+ 7 - 0
src/github.com/golang-jwt/jwt/v4/test/ec512-private.pem

@@ -0,0 +1,7 @@
+-----BEGIN EC PRIVATE KEY-----
+MIHcAgEBBEIB0pE4uFaWRx7t03BsYlYvF1YvKaBGyvoakxnodm9ou0R9wC+sJAjH
+QZZJikOg4SwNqgQ/hyrOuDK2oAVHhgVGcYmgBwYFK4EEACOhgYkDgYYABAAJXIuw
+12MUzpHggia9POBFYXSxaOGKGbMjIyDI+6q7wi7LMw3HgbaOmgIqFG72o8JBQwYN
+4IbXHf+f86CRY1AA2wHzbHvt6IhkCXTNxBEffa1yMUgu8n9cKKF2iLgyQKcKqW33
+8fGOw/n3Rm2Yd/EB56u2rnD29qS+nOM9eGS+gy39OQ==
+-----END EC PRIVATE KEY-----

+ 6 - 0
src/github.com/golang-jwt/jwt/v4/test/ec512-public.pem

@@ -0,0 +1,6 @@
+-----BEGIN PUBLIC KEY-----
+MIGbMBAGByqGSM49AgEGBSuBBAAjA4GGAAQACVyLsNdjFM6R4IImvTzgRWF0sWjh
+ihmzIyMgyPuqu8IuyzMNx4G2jpoCKhRu9qPCQUMGDeCG1x3/n/OgkWNQANsB82x7
+7eiIZAl0zcQRH32tcjFILvJ/XCihdoi4MkCnCqlt9/HxjsP590ZtmHfxAeertq5w
+9vakvpzjPXhkvoMt/Tk=
+-----END PUBLIC KEY-----

+ 3 - 0
src/github.com/golang-jwt/jwt/v4/test/ed25519-private.pem

@@ -0,0 +1,3 @@
+-----BEGIN PRIVATE KEY-----
+MC4CAQAwBQYDK2VwBCIEIEFMEZrmlYxczXKFxIlNvNGR5JQvDhTkLovJYxwQd3ua
+-----END PRIVATE KEY-----

+ 3 - 0
src/github.com/golang-jwt/jwt/v4/test/ed25519-public.pem

@@ -0,0 +1,3 @@
+-----BEGIN PUBLIC KEY-----
+MCowBQYDK2VwAyEAWH7z6hpYqvPns2i4n9yymwvB3APhi4LyQ7iHOT6crtE=
+-----END PUBLIC KEY-----

+ 4 - 0
src/github.com/golang-jwt/jwt/v4/test/examplePaddedKey-public.pem

@@ -0,0 +1,4 @@
+-----BEGIN PUBLIC KEY-----
+MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEIcaUjXhC7Mn2OonyfHF+zjblKkns
+4GLbILnHrZr+aQwddiff5urCDAZ177t81Mn39CDs3uhlNDxfRIRheGnK/Q==
+-----END PUBLIC KEY-----

+ 69 - 0
src/github.com/golang-jwt/jwt/v4/test/helpers.go

@@ -0,0 +1,69 @@
+package test
+
+import (
+	"crypto"
+	"crypto/rsa"
+	"io/ioutil"
+
+	"github.com/golang-jwt/jwt/v4"
+)
+
+func LoadRSAPrivateKeyFromDisk(location string) *rsa.PrivateKey {
+	keyData, e := ioutil.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 := ioutil.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 := ioutil.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 := ioutil.ReadFile(location)
+	if e != nil {
+		panic(e.Error())
+	}
+	key, e := jwt.ParseECPublicKeyFromPEM(keyData)
+	if e != nil {
+		panic(e.Error())
+	}
+	return key
+}

+ 1 - 0
src/github.com/golang-jwt/jwt/v4/test/hmacTestKey

@@ -0,0 +1 @@
+#5K+・シミew{ヲ住ウ(跼Tノ(ゥ┫メP.ソモ燾辻G�感テwb="=.!r.Oタヘ奎gミ€」

+ 30 - 0
src/github.com/golang-jwt/jwt/v4/test/privateSecure.pem

@@ -0,0 +1,30 @@
+-----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-----

+ 27 - 0
src/github.com/golang-jwt/jwt/v4/test/sample_key

@@ -0,0 +1,27 @@
+-----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-----

+ 9 - 0
src/github.com/golang-jwt/jwt/v4/test/sample_key.pub

@@ -0,0 +1,9 @@
+-----BEGIN PUBLIC KEY-----
+MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA4f5wg5l2hKsTeNem/V41
+fGnJm6gOdrj8ym3rFkEU/wT8RDtnSgFEZOQpHEgQ7JL38xUfU0Y3g6aYw9QT0hJ7
+mCpz9Er5qLaMXJwZxzHzAahlfA0icqabvJOMvQtzD6uQv6wPEyZtDTWiQi9AXwBp
+HssPnpYGIn20ZZuNlX2BrClciHhCPUIIZOQn/MmqTD31jSyjoQoV7MhhMTATKJx2
+XrHhR+1DcKJzQBSTAGnpYVaqpsARap+nwRipr3nUTuxyGohBTSmjJ2usSeQXHI3b
+ODIRe1AuTyHceAbewn8b462yEWKARdpd9AjQW5SIVPfdsz5B6GlYQ5LdYKtznTuy
+7wIDAQAB
+-----END PUBLIC KEY-----

+ 131 - 0
src/github.com/golang-jwt/jwt/v4/token.go

@@ -0,0 +1,131 @@
+package jwt
+
+import (
+	"encoding/base64"
+	"encoding/json"
+	"strings"
+	"time"
+)
+
+
+// DecodePaddingAllowed will switch the codec used for decoding JWTs respectively. 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. Note that this is a global
+// variable, and updating it will change the behavior on a package level, and is also NOT go-routine safe.
+// To use the non-recommended decoding, set this boolean to `true` prior to using this package.
+var DecodePaddingAllowed bool
+
+// TimeFunc provides the current time when parsing token to validate "exp" claim (expiration time).
+// You can override it to use another time value.  This is useful for testing or if your
+// server uses a different time zone than your tokens.
+var TimeFunc = time.Now
+
+// 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.
+type Keyfunc func(*Token) (interface{}, error)
+
+// 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                 // The raw token.  Populated when you Parse a token
+	Method    SigningMethod          // The signing method used or to be used
+	Header    map[string]interface{} // The first segment of the token
+	Claims    Claims                 // The second segment of the token
+	Signature string                 // The third segment of the token.  Populated when you Parse a token
+	Valid     bool                   // Is the token valid?  Populated when you Parse/Verify a token
+}
+
+// New creates a new Token with the specified signing method and an empty map of claims.
+func New(method SigningMethod) *Token {
+	return NewWithClaims(method, MapClaims{})
+}
+
+// NewWithClaims creates a new Token with the specified signing method and claims.
+func NewWithClaims(method SigningMethod, claims Claims) *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.
+func (t *Token) SignedString(key interface{}) (string, error) {
+	var sig, sstr string
+	var err error
+	if sstr, err = t.SigningString(); err != nil {
+		return "", err
+	}
+	if sig, err = t.Method.Sign(sstr, key); err != nil {
+		return "", err
+	}
+	return strings.Join([]string{sstr, 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) {
+	var err error
+	parts := make([]string, 2)
+	for i := range parts {
+		var jsonValue []byte
+		if i == 0 {
+			if jsonValue, err = json.Marshal(t.Header); err != nil {
+				return "", err
+			}
+		} else {
+			if jsonValue, err = json.Marshal(t.Claims); err != nil {
+				return "", err
+			}
+		}
+
+		parts[i] = EncodeSegment(jsonValue)
+	}
+	return strings.Join(parts, "."), nil
+}
+
+// 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)
+}
+
+func ParseWithClaims(tokenString string, claims Claims, keyFunc Keyfunc, options ...ParserOption) (*Token, error) {
+	return NewParser(options...).ParseWithClaims(tokenString, claims, keyFunc)
+}
+
+// EncodeSegment encodes a JWT specific base64url encoding with padding stripped
+//
+// Deprecated: In a future release, we will demote this function to a non-exported function, since it
+// should only be used internally
+func EncodeSegment(seg []byte) string {
+	return base64.RawURLEncoding.EncodeToString(seg)
+}
+
+// DecodeSegment decodes a JWT specific base64url encoding with padding stripped
+//
+// Deprecated: In a future release, we will demote this function to a non-exported function, since it
+// should only be used internally
+func DecodeSegment(seg string) ([]byte, error) {
+	if DecodePaddingAllowed {
+		if l := len(seg) % 4; l > 0 {
+			seg += strings.Repeat("=", 4-l)
+		}
+		return base64.URLEncoding.DecodeString(seg)
+	}
+
+	return base64.RawURLEncoding.DecodeString(seg)
+}

+ 127 - 0
src/github.com/golang-jwt/jwt/v4/types.go

@@ -0,0 +1,127 @@
+package jwt
+
+import (
+	"encoding/json"
+	"fmt"
+	"math"
+	"reflect"
+	"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 behaviour 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 behaviour
+// 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) {
+	f := float64(date.Truncate(TimePrecision).UnixNano()) / float64(time.Second)
+
+	return []byte(strconv.FormatFloat(f, 'f', -1, 64)), nil
+}
+
+// UnmarshalJSON is an implementation of the json.RawMessage interface and deserializses 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 &json.UnsupportedTypeError{Type: reflect.TypeOf(vv)}
+			}
+			aud = append(aud, vs)
+		}
+	case nil:
+		return nil
+	default:
+		return &json.UnsupportedTypeError{Type: reflect.TypeOf(v)}
+	}
+
+	*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))
+}

+ 67 - 0
src/github.com/golang-jwt/jwt/v4/types_test.go

@@ -0,0 +1,67 @@
+package jwt_test
+
+import (
+	"encoding/json"
+	"testing"
+	"time"
+
+	"github.com/golang-jwt/jwt/v4"
+)
+
+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,"exp":1516239022.12345}`
+
+	err := json.Unmarshal([]byte(raw), &s)
+
+	if err != nil {
+		t.Errorf("Unexpected error: %s", err)
+	}
+
+	b, _ := json.Marshal(s)
+
+	if raw != string(b) {
+		t.Errorf("Serialized format of numeric date mismatch. Expecting: %s  Got: %s", string(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", string(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", string(expected), string(b))
+	}
+}

+ 35 - 0
src/qfw/util/jwt/jwt.go

@@ -0,0 +1,35 @@
+/*
+ *  用户鉴权
+ */
+
+package jwt
+
+import (
+	"time"
+
+	"github.com/golang-jwt/jwt/v4"
+)
+
+type JwtStruct struct {
+	SecretKey string
+	TimeOut   int64
+}
+
+var UserJwt = &JwtStruct{
+	SecretKey: "jianyuservice", //保持一致
+	TimeOut:   600,
+}
+
+func (this *JwtStruct) GetToken(payloads map[string]interface{}) (string, error) {
+	now := time.Now().Add(-10 * time.Second).Unix() //当前时间往前10s  iat时间要在相应服务器时间之前 否则会报错Token used before issued
+	claims := make(jwt.MapClaims)
+	claims["exp"] = now + this.TimeOut
+	claims["iat"] = now
+	for k, v := range payloads {
+		claims[k] = v
+	}
+
+	token := jwt.New(jwt.SigningMethodHS256)
+	token.Claims = claims
+	return token.SignedString([]byte(this.SecretKey))
+}

+ 81 - 0
src/qfw/util/userCenter.go

@@ -0,0 +1,81 @@
+package util
+
+import (
+	"encoding/json"
+	"io/ioutil"
+	"log"
+	"net/http"
+	"qfw/util/jwt"
+	"strings"
+)
+
+var ContentType_Json = "application/json"
+
+// var UserCenterAdd = "http://192.168.21.47:9999/userCenter/user/add"
+// var UserCenterAdd = "http://192.168.3.240:9999/userCenter/user/add"
+var UserCenterAdd = "/userCenter/user/add"
+var UserCenterUpdate = "/userCenter/user/updateById"
+var UserCenterDelete = "/userCenter/user/deleteById"
+
+/*
+ 修改header 的post请求
+*/
+func PostHeader(url, value string, headers map[string]string, ck *http.Cookie) (string, error) {
+	client := &http.Client{}
+	req, err := http.NewRequest("POST", url, strings.NewReader(value))
+	req.AddCookie(ck)
+	if err != nil {
+		return "", err
+	}
+	for key, header := range headers {
+		req.Header.Set(key, header)
+	}
+	resp, err := client.Do(req)
+	if err != nil {
+		return "", err
+	}
+	defer resp.Body.Close()
+	body, err := ioutil.ReadAll(resp.Body)
+	if err != nil {
+		return "", err
+	}
+	return string(body), nil
+}
+
+//调用用户中台相关-api接口
+func PostUserCenter(url, contentTpe, userid string, data map[string]interface{}, ck *http.Cookie) (*map[string]interface{}, bool) {
+	token, err := jwt.UserJwt.GetToken(map[string]interface{}{
+		"userid": userid,
+	})
+	if err != nil {
+		log.Printf("%s获取token失败", userid)
+		return nil, false
+	}
+	log.Println("token jwt:", token)
+	data_str, err := json.Marshal(data)
+	if err != nil {
+		log.Printf("%s序列化失败%+v", userid, data)
+		return nil, false
+	}
+	ret, err := PostHeader(url, string(data_str), map[string]string{
+		"Content-Type":  contentTpe,
+		"Authorization": token,
+	}, ck)
+	if err != nil {
+		log.Printf("%s调用%s接口失败%+v", userid, url, data)
+		return nil, false
+	}
+	log.Println("ret:", ret)
+	m := ObjToMap(ret)
+	if m == nil || len(*m) == 0 {
+		return nil, false
+	}
+	errmsg := ObjToString((*m)["error_msg"])
+	dataM := ObjToMap((*m)["data"])
+	status := IntAllDef((*dataM)["status"], 0)
+	if errmsg != "" || status != 1 {
+		log.Printf("%s调用%s接口返回结果失败:%s", userid, url, errmsg)
+		return nil, false
+	}
+	return dataM, true
+}