...

Text file src/github.com/golang-jwt/jwt/v5/MIGRATION_GUIDE.md

Documentation: github.com/golang-jwt/jwt/v5

     1# Migration Guide (v5.0.0)
     2
     3Version `v5` contains a major rework of core functionalities in the `jwt-go`
     4library. This includes support for several validation options as well as a
     5re-design of the `Claims` interface. Lastly, we reworked how errors work under
     6the hood, which should provide a better overall developer experience.
     7
     8Starting from [v5.0.0](https://github.com/golang-jwt/jwt/releases/tag/v5.0.0),
     9the import path will be:
    10
    11    "github.com/golang-jwt/jwt/v5"
    12
    13For most users, changing the import path *should* suffice. However, since we
    14intentionally changed and cleaned some of the public API, existing programs
    15might need to be updated. The following sections describe significant changes
    16and corresponding updates for existing programs.
    17
    18## Parsing and Validation Options
    19
    20Under the hood, a new `Validator` struct takes care of validating the claims. A
    21long awaited feature has been the option to fine-tune the validation of tokens.
    22This is now possible with several `ParserOption` functions that can be appended
    23to most `Parse` functions, such as `ParseWithClaims`. The most important options
    24and changes are:
    25  * Added `WithLeeway` to support specifying the leeway that is allowed when
    26    validating time-based claims, such as `exp` or `nbf`.
    27  * Changed default behavior to not check the `iat` claim. Usage of this claim
    28    is OPTIONAL according to the JWT RFC. The claim itself is also purely
    29    informational according to the RFC, so a strict validation failure is not
    30    recommended. If you want to check for sensible values in these claims,
    31    please use the `WithIssuedAt` parser option.
    32  * Added `WithAudience`, `WithSubject` and `WithIssuer` to support checking for
    33    expected `aud`, `sub` and `iss`.
    34  * Added `WithStrictDecoding` and `WithPaddingAllowed` options to allow
    35    previously global settings to enable base64 strict encoding and the parsing
    36    of base64 strings with padding. The latter is strictly speaking against the
    37    standard, but unfortunately some of the major identity providers issue some
    38    of these incorrect tokens. Both options are disabled by default.
    39
    40## Changes to the `Claims` interface
    41
    42### Complete Restructuring
    43
    44Previously, the claims interface was satisfied with an implementation of a
    45`Valid() error` function. This had several issues:
    46  * The different claim types (struct claims, map claims, etc.) then contained
    47    similar (but not 100 % identical) code of how this validation was done. This
    48    lead to a lot of (almost) duplicate code and was hard to maintain
    49  * It was not really semantically close to what a "claim" (or a set of claims)
    50    really is; which is a list of defined key/value pairs with a certain
    51    semantic meaning.
    52
    53Since all the validation functionality is now extracted into the validator, all
    54`VerifyXXX` and `Valid` functions have been removed from the `Claims` interface.
    55Instead, the interface now represents a list of getters to retrieve values with
    56a specific meaning. This allows us to completely decouple the validation logic
    57with the underlying storage representation of the claim, which could be a
    58struct, a map or even something stored in a database.
    59
    60```go
    61type Claims interface {
    62	GetExpirationTime() (*NumericDate, error)
    63	GetIssuedAt() (*NumericDate, error)
    64	GetNotBefore() (*NumericDate, error)
    65	GetIssuer() (string, error)
    66	GetSubject() (string, error)
    67	GetAudience() (ClaimStrings, error)
    68}
    69```
    70
    71Users that previously directly called the `Valid` function on their claims,
    72e.g., to perform validation independently of parsing/verifying a token, can now
    73use the `jwt.NewValidator` function to create a `Validator` independently of the
    74`Parser`.
    75
    76```go
    77var v = jwt.NewValidator(jwt.WithLeeway(5*time.Second))
    78v.Validate(myClaims)
    79```
    80
    81### Supported Claim Types and Removal of `StandardClaims`
    82
    83The two standard claim types supported by this library, `MapClaims` and
    84`RegisteredClaims` both implement the necessary functions of this interface. The
    85old `StandardClaims` struct, which has already been deprecated in `v4` is now
    86removed.
    87
    88Users using custom claims, in most cases, will not experience any changes in the
    89behavior as long as they embedded `RegisteredClaims`. If they created a new
    90claim type from scratch, they now need to implemented the proper getter
    91functions.
    92
    93### Migrating Application Specific Logic of the old `Valid`
    94
    95Previously, users could override the `Valid` method in a custom claim, for
    96example to extend the validation with application-specific claims. However, this
    97was always very dangerous, since once could easily disable the standard
    98validation and signature checking.
    99
   100In order to avoid that, while still supporting the use-case, a new
   101`ClaimsValidator` interface has been introduced. This interface consists of the
   102`Validate() error` function. If the validator sees, that a `Claims` struct
   103implements this interface, the errors returned to the `Validate` function will
   104be *appended* to the regular standard validation. It is not possible to disable
   105the standard validation anymore (even only by accident).
   106
   107Usage examples can be found in [example_test.go](./example_test.go), to build
   108claims structs like the following.
   109
   110```go
   111// MyCustomClaims includes all registered claims, plus Foo.
   112type MyCustomClaims struct {
   113	Foo string `json:"foo"`
   114	jwt.RegisteredClaims
   115}
   116
   117// Validate can be used to execute additional application-specific claims
   118// validation.
   119func (m MyCustomClaims) Validate() error {
   120	if m.Foo != "bar" {
   121		return errors.New("must be foobar")
   122	}
   123
   124	return nil
   125}
   126```
   127
   128## Changes to the `Token` and `Parser` struct
   129
   130The previously global functions `DecodeSegment` and `EncodeSegment` were moved
   131to the `Parser` and `Token` struct respectively. This will allow us in the
   132future to configure the behavior of these two based on options supplied on the
   133parser or the token (creation). This also removes two previously global
   134variables and moves them to parser options `WithStrictDecoding` and
   135`WithPaddingAllowed`.
   136
   137In order to do that, we had to adjust the way signing methods work. Previously
   138they were given a base64 encoded signature in `Verify` and were expected to
   139return a base64 encoded version of the signature in `Sign`, both as a `string`.
   140However, this made it necessary to have `DecodeSegment` and `EncodeSegment`
   141global and was a less than perfect design because we were repeating
   142encoding/decoding steps for all signing methods. Now, `Sign` and `Verify`
   143operate on a decoded signature as a `[]byte`, which feels more natural for a
   144cryptographic operation anyway. Lastly, `Parse` and `SignedString` take care of
   145the final encoding/decoding part.
   146
   147In addition to that, we also changed the `Signature` field on `Token` from a
   148`string` to `[]byte` and this is also now populated with the decoded form. This
   149is also more consistent, because the other parts of the JWT, mainly `Header` and
   150`Claims` were already stored in decoded form in `Token`. Only the signature was
   151stored in base64 encoded form, which was redundant with the information in the
   152`Raw` field, which contains the complete token as base64.
   153
   154```go
   155type Token struct {
   156	Raw       string                 // Raw contains the raw token
   157	Method    SigningMethod          // Method is the signing method used or to be used
   158	Header    map[string]interface{} // Header is the first segment of the token in decoded form
   159	Claims    Claims                 // Claims is the second segment of the token in decoded form
   160	Signature []byte                 // Signature is the third segment of the token in decoded form
   161	Valid     bool                   // Valid specifies if the token is valid
   162}
   163```
   164
   165Most (if not all) of these changes should not impact the normal usage of this
   166library. Only users directly accessing the `Signature` field as well as
   167developers of custom signing methods should be affected.
   168
   169# Migration Guide (v4.0.0)
   170
   171Starting from [v4.0.0](https://github.com/golang-jwt/jwt/releases/tag/v4.0.0),
   172the import path will be:
   173
   174    "github.com/golang-jwt/jwt/v4"
   175
   176The `/v4` version will be backwards compatible with existing `v3.x.y` tags in
   177this repo, as well as `github.com/dgrijalva/jwt-go`. For most users this should
   178be a drop-in replacement, if you're having troubles migrating, please open an
   179issue.
   180
   181You can replace all occurrences of `github.com/dgrijalva/jwt-go` or
   182`github.com/golang-jwt/jwt` with `github.com/golang-jwt/jwt/v4`, either manually
   183or by using tools such as `sed` or `gofmt`.
   184
   185And then you'd typically run:
   186
   187```
   188go get github.com/golang-jwt/jwt/v4
   189go mod tidy
   190```
   191
   192# Older releases (before v3.2.0)
   193
   194The original migration guide for older releases can be found at
   195https://github.com/dgrijalva/jwt-go/blob/master/MIGRATION_GUIDE.md.

View as plain text