jwt/token.go

133 lines
5.3 KiB
Go
Raw Permalink Normal View History

2012-04-18 03:49:21 +04:00
package jwt
import (
"encoding/base64"
"encoding/json"
2012-04-18 23:59:37 +04:00
"strings"
"time"
2012-04-18 03:49:21 +04:00
)
// 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
2014-02-11 05:27:59 +04:00
// 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.
2014-02-06 03:07:40 +04:00
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,
2016-05-27 16:22:32 +03:00
// 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
2014-06-16 06:40:38 +04:00
// creating or parsing/verifying a token.
2012-04-18 03:49:21 +04:00
type Token struct {
2014-06-16 06:39:12 +04:00
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
2014-06-16 06:39:12 +04:00
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
2012-04-18 03:49:21 +04:00
}
// New creates a new Token with the specified signing method and an empty map of claims.
2012-07-07 04:02:20 +04:00
func New(method SigningMethod) *Token {
2015-08-18 20:18:57 +03:00
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,
2012-07-07 23:12:49 +04:00
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) {
2012-07-07 03:07:55 +04:00
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
2012-07-07 03:12:33 +04:00
// most expensive part of the whole deal. Unless you
// need this for something special, just go straight for
// the SignedString.
2012-07-07 04:02:20 +04:00
func (t *Token) SigningString() (string, error) {
2012-07-07 03:07:55 +04:00
var err error
var jsonValue []byte
2012-07-07 04:02:20 +04:00
if jsonValue, err = json.Marshal(t.Header); err != nil {
return "", err
2012-07-07 03:07:55 +04:00
}
header := EncodeSegment(jsonValue)
if jsonValue, err = json.Marshal(t.Claims); err != nil {
return "", err
}
claim := EncodeSegment(jsonValue)
return strings.Join([]string{header, claim}, "."), 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)
}
// ParseWithClaims is a shortcut for NewParser().ParseWithClaims().
//
// Note: If you provide a custom claim implementation that embeds one of the standard claims (such as RegisteredClaims),
// make sure that a) you either embed a non-pointer version of the claims or b) if you are using a pointer, allocate the
// proper memory for it before passing in the overall claims, otherwise you might run into a panic.
func ParseWithClaims(tokenString string, claims Claims, keyFunc Keyfunc, options ...ParserOption) (*Token, error) {
return NewParser(options...).ParseWithClaims(tokenString, claims, keyFunc)
}
// 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
2012-07-07 04:02:20 +04:00
func EncodeSegment(seg []byte) string {
Allocation optimization (#33) * Test to ensure ECDSA signature is valid Add assertions to ensure ECDSA signing methods return valid signatures. This is probably covered elsewhere as well, but putting it in ecdsa_test.go makes it more obvious and easier to find. * Benchmark ECDSA signing methods Add benchmark coverage of ECDSA signing methods. Benchmarks are run using the existing helper for comparability with existing benchmarks. Sign method is also tested directly, to avoid the overhead of *Token. Report allocations for all benchmarks. Allocation count for ES384 and ES512 fluctuate across test runs, other signing methods consistently report the same number of allocations. Sample output: ``` $ go test -bench=Bench -run=NONE . 2021/02/26 18:18:30 Listening... goos: darwin goarch: amd64 pkg: github.com/dgrijalva/jwt-go BenchmarkECDSASigning/Basic_ES256-8 190572 6702 ns/op 4249 B/op 65 allocs/op BenchmarkECDSASigning/Basic_ES256/sign-only-8 47383 24650 ns/op 3329 B/op 43 allocs/op BenchmarkECDSASigning/Basic_ES384-8 1113 1252975 ns/op 1750744 B/op 14474 allocs/op BenchmarkECDSASigning/Basic_ES384/sign-only-8 286 3937773 ns/op 1746175 B/op 14423 allocs/op BenchmarkECDSASigning/Basic_ES512-8 662 1949937 ns/op 3028386 B/op 19608 allocs/op BenchmarkECDSASigning/Basic_ES512/sign-only-8 170 6856189 ns/op 3025471 B/op 19571 allocs/op BenchmarkECDSASigning/basic_ES256_invalid:_foo_=>_bar-8 190638 6665 ns/op 4249 B/op 65 allocs/op BenchmarkHS256Signing-8 1000000 1024 ns/op 1584 B/op 32 allocs/op BenchmarkHS384Signing-8 917286 1447 ns/op 1969 B/op 32 allocs/op BenchmarkHS512Signing-8 827744 1470 ns/op 2065 B/op 32 allocs/op BenchmarkRS256Signing-8 3037 390077 ns/op 32576 B/op 136 allocs/op BenchmarkRS384Signing-8 2976 379155 ns/op 32684 B/op 136 allocs/op BenchmarkRS512Signing-8 3205 388628 ns/op 32704 B/op 136 allocs/op ``` * Reduce allocations during ECDSA signing Reduce the number of byte arrays allocated by using big.Int.FillBytes when calculating ECDSA signature. After this change, Benchmarks of ES256 signing method consistently report 4 fewer allocations. Before: ``` BenchmarkECDSASigning/Basic_ES256-8 190572 6702 ns/op 4249 B/op 65 allocs/op BenchmarkECDSASigning/Basic_ES256/sign-only-8 47383 24650 ns/op 3329 B/op 43 allocs/op ``` After: ``` BenchmarkECDSASigning/Basic_ES256-8 187682 6725 ns/op 4121 B/op 61 allocs/op BenchmarkECDSASigning/Basic_ES256/sign-only-8 48656 24446 ns/op 3201 B/op 39 allocs/op ``` * Use base64.RawURLEncoding to avoid padding JWT uses a non-padded base64 encoding. Current code uses base64.URLEncoding to generate a padded string and then removes the padding. Likewise, current code adds padding before decoding. Instead, use base64.RawURLEncoding which does not add or require the padding in the first place. In addition to making the code cleaner, this reduces memory allocations as reported by benchmarks. Before: ``` BenchmarkECDSASigning/Basic_ES256-8 191396 6917 ns/op 4121 B/op 61 allocs/op BenchmarkECDSASigning/Basic_ES256/sign-only-8 49347 25039 ns/op 3201 B/op 39 allocs/op BenchmarkECDSASigning/basic_ES256_invalid:_foo_=>_bar-8 190668 6586 ns/op 4121 B/op 61 allocs/op BenchmarkHS256Signing-8 1260060 1131 ns/op 1585 B/op 32 allocs/op BenchmarkHS384Signing-8 861378 1387 ns/op 1969 B/op 32 allocs/op BenchmarkHS512Signing-8 896745 1463 ns/op 2065 B/op 32 allocs/op BenchmarkRS256Signing-8 3086 355769 ns/op 32576 B/op 136 allocs/op BenchmarkRS384Signing-8 3414 353570 ns/op 32694 B/op 136 allocs/op BenchmarkRS512Signing-8 3235 349394 ns/op 32706 B/op 136 allocs/op ``` After: ``` BenchmarkECDSASigning/Basic_ES256-8 176617 6827 ns/op 4021 B/op 58 allocs/op BenchmarkECDSASigning/Basic_ES256/sign-only-8 48038 24213 ns/op 3169 B/op 38 allocs/op BenchmarkECDSASigning/basic_ES256_invalid:_foo_=>_bar-8 194352 6928 ns/op 4021 B/op 58 allocs/op BenchmarkHS256Signing-8 1000000 1127 ns/op 1488 B/op 29 allocs/op BenchmarkHS384Signing-8 972552 1369 ns/op 1873 B/op 29 allocs/op BenchmarkHS512Signing-8 780751 1368 ns/op 1969 B/op 29 allocs/op BenchmarkRS256Signing-8 3014 387326 ns/op 32475 B/op 133 allocs/op BenchmarkRS384Signing-8 3044 361411 ns/op 32591 B/op 133 allocs/op BenchmarkRS512Signing-8 3273 355504 ns/op 32607 B/op 133 allocs/op ``` Benchmarks of signing methods ES384 and ES512 are omitted because their allocations are not consistent.
2021-07-13 09:31:42 +03:00
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
2012-04-18 23:59:37 +04:00
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)
}
Allocation optimization (#33) * Test to ensure ECDSA signature is valid Add assertions to ensure ECDSA signing methods return valid signatures. This is probably covered elsewhere as well, but putting it in ecdsa_test.go makes it more obvious and easier to find. * Benchmark ECDSA signing methods Add benchmark coverage of ECDSA signing methods. Benchmarks are run using the existing helper for comparability with existing benchmarks. Sign method is also tested directly, to avoid the overhead of *Token. Report allocations for all benchmarks. Allocation count for ES384 and ES512 fluctuate across test runs, other signing methods consistently report the same number of allocations. Sample output: ``` $ go test -bench=Bench -run=NONE . 2021/02/26 18:18:30 Listening... goos: darwin goarch: amd64 pkg: github.com/dgrijalva/jwt-go BenchmarkECDSASigning/Basic_ES256-8 190572 6702 ns/op 4249 B/op 65 allocs/op BenchmarkECDSASigning/Basic_ES256/sign-only-8 47383 24650 ns/op 3329 B/op 43 allocs/op BenchmarkECDSASigning/Basic_ES384-8 1113 1252975 ns/op 1750744 B/op 14474 allocs/op BenchmarkECDSASigning/Basic_ES384/sign-only-8 286 3937773 ns/op 1746175 B/op 14423 allocs/op BenchmarkECDSASigning/Basic_ES512-8 662 1949937 ns/op 3028386 B/op 19608 allocs/op BenchmarkECDSASigning/Basic_ES512/sign-only-8 170 6856189 ns/op 3025471 B/op 19571 allocs/op BenchmarkECDSASigning/basic_ES256_invalid:_foo_=>_bar-8 190638 6665 ns/op 4249 B/op 65 allocs/op BenchmarkHS256Signing-8 1000000 1024 ns/op 1584 B/op 32 allocs/op BenchmarkHS384Signing-8 917286 1447 ns/op 1969 B/op 32 allocs/op BenchmarkHS512Signing-8 827744 1470 ns/op 2065 B/op 32 allocs/op BenchmarkRS256Signing-8 3037 390077 ns/op 32576 B/op 136 allocs/op BenchmarkRS384Signing-8 2976 379155 ns/op 32684 B/op 136 allocs/op BenchmarkRS512Signing-8 3205 388628 ns/op 32704 B/op 136 allocs/op ``` * Reduce allocations during ECDSA signing Reduce the number of byte arrays allocated by using big.Int.FillBytes when calculating ECDSA signature. After this change, Benchmarks of ES256 signing method consistently report 4 fewer allocations. Before: ``` BenchmarkECDSASigning/Basic_ES256-8 190572 6702 ns/op 4249 B/op 65 allocs/op BenchmarkECDSASigning/Basic_ES256/sign-only-8 47383 24650 ns/op 3329 B/op 43 allocs/op ``` After: ``` BenchmarkECDSASigning/Basic_ES256-8 187682 6725 ns/op 4121 B/op 61 allocs/op BenchmarkECDSASigning/Basic_ES256/sign-only-8 48656 24446 ns/op 3201 B/op 39 allocs/op ``` * Use base64.RawURLEncoding to avoid padding JWT uses a non-padded base64 encoding. Current code uses base64.URLEncoding to generate a padded string and then removes the padding. Likewise, current code adds padding before decoding. Instead, use base64.RawURLEncoding which does not add or require the padding in the first place. In addition to making the code cleaner, this reduces memory allocations as reported by benchmarks. Before: ``` BenchmarkECDSASigning/Basic_ES256-8 191396 6917 ns/op 4121 B/op 61 allocs/op BenchmarkECDSASigning/Basic_ES256/sign-only-8 49347 25039 ns/op 3201 B/op 39 allocs/op BenchmarkECDSASigning/basic_ES256_invalid:_foo_=>_bar-8 190668 6586 ns/op 4121 B/op 61 allocs/op BenchmarkHS256Signing-8 1260060 1131 ns/op 1585 B/op 32 allocs/op BenchmarkHS384Signing-8 861378 1387 ns/op 1969 B/op 32 allocs/op BenchmarkHS512Signing-8 896745 1463 ns/op 2065 B/op 32 allocs/op BenchmarkRS256Signing-8 3086 355769 ns/op 32576 B/op 136 allocs/op BenchmarkRS384Signing-8 3414 353570 ns/op 32694 B/op 136 allocs/op BenchmarkRS512Signing-8 3235 349394 ns/op 32706 B/op 136 allocs/op ``` After: ``` BenchmarkECDSASigning/Basic_ES256-8 176617 6827 ns/op 4021 B/op 58 allocs/op BenchmarkECDSASigning/Basic_ES256/sign-only-8 48038 24213 ns/op 3169 B/op 38 allocs/op BenchmarkECDSASigning/basic_ES256_invalid:_foo_=>_bar-8 194352 6928 ns/op 4021 B/op 58 allocs/op BenchmarkHS256Signing-8 1000000 1127 ns/op 1488 B/op 29 allocs/op BenchmarkHS384Signing-8 972552 1369 ns/op 1873 B/op 29 allocs/op BenchmarkHS512Signing-8 780751 1368 ns/op 1969 B/op 29 allocs/op BenchmarkRS256Signing-8 3014 387326 ns/op 32475 B/op 133 allocs/op BenchmarkRS384Signing-8 3044 361411 ns/op 32591 B/op 133 allocs/op BenchmarkRS512Signing-8 3273 355504 ns/op 32607 B/op 133 allocs/op ``` Benchmarks of signing methods ES384 and ES512 are omitted because their allocations are not consistent.
2021-07-13 09:31:42 +03:00
return base64.RawURLEncoding.DecodeString(seg)
2012-04-18 23:59:37 +04:00
}