├── .gitignore ├── .travis.yml ├── LICENSE ├── MIGRATION_GUIDE.md ├── README.md ├── VERSION_HISTORY.md ├── claims.go ├── cmd └── jwt │ ├── README.md │ ├── app.go │ └── args.go ├── doc.go ├── ecdsa.go ├── ecdsa_test.go ├── ecdsa_utils.go ├── errors.go ├── example_test.go ├── hmac.go ├── hmac_example_test.go ├── hmac_test.go ├── http_example_test.go ├── map_claims.go ├── map_claims_test.go ├── none.go ├── none_test.go ├── parser.go ├── parser_test.go ├── request ├── doc.go ├── extractor.go ├── extractor_example_test.go ├── extractor_test.go ├── oauth2.go ├── request.go └── request_test.go ├── rsa.go ├── rsa_pss.go ├── rsa_pss_test.go ├── rsa_test.go ├── rsa_utils.go ├── signing_method.go ├── test ├── ec256-private.pem ├── ec256-public.pem ├── ec384-private.pem ├── ec384-public.pem ├── ec512-private.pem ├── ec512-public.pem ├── helpers.go ├── hmacTestKey ├── privateSecure.pem ├── sample_key └── sample_key.pub └── token.go /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | bin 3 | .idea/ 4 | 5 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: go 2 | 3 | script: 4 | - go vet ./... 5 | - go test -v ./... 6 | 7 | go: 8 | - 1.3 9 | - 1.4 10 | - 1.5 11 | - 1.6 12 | - 1.7 13 | - tip 14 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2012 Dave Grijalva 2 | 3 | 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: 4 | 5 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 6 | 7 | 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. 8 | 9 | -------------------------------------------------------------------------------- /MIGRATION_GUIDE.md: -------------------------------------------------------------------------------- 1 | ## Migration Guide from v2 -> v3 2 | 3 | Version 3 adds several new, frequently requested features. To do so, it introduces a few breaking changes. We've worked to keep these as minimal as possible. This guide explains the breaking changes and how you can quickly update your code. 4 | 5 | ### `Token.Claims` is now an interface type 6 | 7 | The most requested feature from the 2.0 verison of this library was the ability to provide a custom type to the JSON parser for claims. This was implemented by introducing a new interface, `Claims`, to replace `map[string]interface{}`. We also included two concrete implementations of `Claims`: `MapClaims` and `StandardClaims`. 8 | 9 | `MapClaims` is an alias for `map[string]interface{}` with built in validation behavior. It is the default claims type when using `Parse`. The usage is unchanged except you must type cast the claims property. 10 | 11 | The old example for parsing a token looked like this.. 12 | 13 | ```go 14 | if token, err := jwt.Parse(tokenString, keyLookupFunc); err == nil { 15 | fmt.Printf("Token for user %v expires %v", token.Claims["user"], token.Claims["exp"]) 16 | } 17 | ``` 18 | 19 | is now directly mapped to... 20 | 21 | ```go 22 | if token, err := jwt.Parse(tokenString, keyLookupFunc); err == nil { 23 | claims := token.Claims.(jwt.MapClaims) 24 | fmt.Printf("Token for user %v expires %v", claims["user"], claims["exp"]) 25 | } 26 | ``` 27 | 28 | `StandardClaims` is designed to be embedded in your custom type. You can supply a custom claims type with the new `ParseWithClaims` function. Here's an example of using a custom claims type. 29 | 30 | ```go 31 | type MyCustomClaims struct { 32 | User string 33 | *StandardClaims 34 | } 35 | 36 | if token, err := jwt.ParseWithClaims(tokenString, &MyCustomClaims{}, keyLookupFunc); err == nil { 37 | claims := token.Claims.(*MyCustomClaims) 38 | fmt.Printf("Token for user %v expires %v", claims.User, claims.StandardClaims.ExpiresAt) 39 | } 40 | ``` 41 | 42 | ### `ParseFromRequest` has been moved 43 | 44 | To keep this library focused on the tokens without becoming overburdened with complex request processing logic, `ParseFromRequest` and its new companion `ParseFromRequestWithClaims` have been moved to a subpackage, `request`. The method signatues have also been augmented to receive a new argument: `Extractor`. 45 | 46 | `Extractors` do the work of picking the token string out of a request. The interface is simple and composable. 47 | 48 | This simple parsing example: 49 | 50 | ```go 51 | if token, err := jwt.ParseFromRequest(tokenString, req, keyLookupFunc); err == nil { 52 | fmt.Printf("Token for user %v expires %v", token.Claims["user"], token.Claims["exp"]) 53 | } 54 | ``` 55 | 56 | is directly mapped to: 57 | 58 | ```go 59 | if token, err := request.ParseFromRequest(req, request.OAuth2Extractor, keyLookupFunc); err == nil { 60 | claims := token.Claims.(jwt.MapClaims) 61 | fmt.Printf("Token for user %v expires %v", claims["user"], claims["exp"]) 62 | } 63 | ``` 64 | 65 | There are several concrete `Extractor` types provided for your convenience: 66 | 67 | * `HeaderExtractor` will search a list of headers until one contains content. 68 | * `ArgumentExtractor` will search a list of keys in request query and form arguments until one contains content. 69 | * `MultiExtractor` will try a list of `Extractors` in order until one returns content. 70 | * `AuthorizationHeaderExtractor` will look in the `Authorization` header for a `Bearer` token. 71 | * `OAuth2Extractor` searches the places an OAuth2 token would be specified (per the spec): `Authorization` header and `access_token` argument 72 | * `PostExtractionFilter` wraps an `Extractor`, allowing you to process the content before it's parsed. A simple example is stripping the `Bearer ` text from a header 73 | 74 | 75 | ### RSA signing methods no longer accept `[]byte` keys 76 | 77 | Due to a [critical vulnerability](https://auth0.com/blog/2015/03/31/critical-vulnerabilities-in-json-web-token-libraries/), we've decided the convenience of accepting `[]byte` instead of `rsa.PublicKey` or `rsa.PrivateKey` isn't worth the risk of misuse. 78 | 79 | To replace this behavior, we've added two helper methods: `ParseRSAPrivateKeyFromPEM(key []byte) (*rsa.PrivateKey, error)` and `ParseRSAPublicKeyFromPEM(key []byte) (*rsa.PublicKey, error)`. These are just simple helpers for unpacking PEM encoded PKCS1 and PKCS8 keys. If your keys are encoded any other way, all you need to do is convert them to the `crypto/rsa` package's types. 80 | 81 | ```go 82 | func keyLookupFunc(*Token) (interface{}, error) { 83 | // Don't forget to validate the alg is what you expect: 84 | if _, ok := token.Method.(*jwt.SigningMethodRSA); !ok { 85 | return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"]) 86 | } 87 | 88 | // Look up key 89 | key, err := lookupPublicKey(token.Header["kid"]) 90 | if err != nil { 91 | return nil, err 92 | } 93 | 94 | // Unpack key from PEM encoded PKCS8 95 | return jwt.ParseRSAPublicKeyFromPEM(key) 96 | } 97 | ``` 98 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # THIS REPOSITORY IS NO LONGER MAINTANED 2 | 3 | The new repository can be found at: https://github.com/golang-jwt/jwt 4 | 5 | For more information, see issue [#462](https://github.com/dgrijalva/jwt-go/issues/462). 6 | 7 | # jwt-go 8 | 9 | [![Build Status](https://travis-ci.org/dgrijalva/jwt-go.svg?branch=master)](https://travis-ci.org/dgrijalva/jwt-go) 10 | [![GoDoc](https://godoc.org/github.com/dgrijalva/jwt-go?status.svg)](https://godoc.org/github.com/dgrijalva/jwt-go) 11 | 12 | A [go](http://www.golang.org) (or 'golang' for search engine friendliness) implementation of [JSON Web Tokens](http://self-issued.info/docs/draft-ietf-oauth-json-web-token.html) 13 | 14 | **NEW VERSION COMING:** There have been a lot of improvements suggested since the version 3.0.0 released in 2016. I'm working now on cutting two different releases: 3.2.0 will contain any non-breaking changes or enhancements. 4.0.0 will follow shortly which will include breaking changes. See the 4.0.0 milestone to get an idea of what's coming. If you have other ideas, or would like to participate in 4.0.0, now's the time. If you depend on this library and don't want to be interrupted, I recommend you use your dependency mangement tool to pin to version 3. 15 | 16 | **SECURITY NOTICE:** Some older versions of Go have a security issue in the cryotp/elliptic. Recommendation is to upgrade to at least 1.8.3. See issue #216 for more detail. 17 | 18 | **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. 19 | 20 | ## What the heck is a JWT? 21 | 22 | JWT.io has [a great introduction](https://jwt.io/introduction) to JSON Web Tokens. 23 | 24 | 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](http://tools.ietf.org/html/rfc4648) encoded. The last part is the signature, encoded the same way. 25 | 26 | 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. 27 | 28 | The part in the middle is the interesting bit. It's called the Claims and contains the actual stuff you care about. Refer to [the RFC](http://self-issued.info/docs/draft-ietf-oauth-json-web-token.html) for information about reserved keys and the proper way to add your own. 29 | 30 | ## What's in the box? 31 | 32 | 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. 33 | 34 | ## Examples 35 | 36 | See [the project documentation](https://godoc.org/github.com/dgrijalva/jwt-go) for examples of usage: 37 | 38 | * [Simple example of parsing and validating a token](https://godoc.org/github.com/dgrijalva/jwt-go#example-Parse--Hmac) 39 | * [Simple example of building and signing a token](https://godoc.org/github.com/dgrijalva/jwt-go#example-New--Hmac) 40 | * [Directory of Examples](https://godoc.org/github.com/dgrijalva/jwt-go#pkg-examples) 41 | 42 | ## Extensions 43 | 44 | 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`. 45 | 46 | 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 47 | 48 | ## Compliance 49 | 50 | This library was last reviewed to comply with [RTF 7519](http://www.rfc-editor.org/info/rfc7519) dated May 2015 with a few notable differences: 51 | 52 | * In order to protect against accidental use of [Unsecured JWTs](http://self-issued.info/docs/draft-ietf-oauth-json-web-token.html#UnsecuredJWT), tokens using `alg=none` will only be accepted if the constant `jwt.UnsafeAllowNoneSignatureType` is provided as the key. 53 | 54 | ## Project Status & Versioning 55 | 56 | 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). 57 | 58 | This project uses [Semantic Versioning 2.0.0](http://semver.org). Accepted pull requests will land on `master`. Periodically, versions will be tagged from `master`. You can find all the releases on [the project releases page](https://github.com/dgrijalva/jwt-go/releases). 59 | 60 | While we try to make it obvious when we make breaking changes, there isn't a great mechanism for pushing announcements out to users. You may want to use this alternative package include: `gopkg.in/dgrijalva/jwt-go.v3`. It will do the right thing WRT semantic versioning. 61 | 62 | **BREAKING CHANGES:*** 63 | * Version 3.0.0 includes _a lot_ of changes from the 2.x line, including a few that break the API. We've tried to break as few things as possible, so there should just be a few type signature changes. A full list of breaking changes is available in `VERSION_HISTORY.md`. See `MIGRATION_GUIDE.md` for more information on updating your code. 64 | 65 | ## Usage Tips 66 | 67 | ### Signing vs Encryption 68 | 69 | A token is simply a JSON object that is signed by its author. this tells you exactly two things about the data: 70 | 71 | * The author of the token was in the possession of the signing secret 72 | * The data has not been modified since it was signed 73 | 74 | 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. 75 | 76 | ### Choosing a Signing Method 77 | 78 | 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. 79 | 80 | 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. 81 | 82 | 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. 83 | 84 | ### Signing Methods and Key Types 85 | 86 | Each signing method expects a different object type for its signing keys. See the package documentation for details. Here are the most common ones: 87 | 88 | * The [HMAC signing method](https://godoc.org/github.com/dgrijalva/jwt-go#SigningMethodHMAC) (`HS256`,`HS384`,`HS512`) expect `[]byte` values for signing and validation 89 | * The [RSA signing method](https://godoc.org/github.com/dgrijalva/jwt-go#SigningMethodRSA) (`RS256`,`RS384`,`RS512`) expect `*rsa.PrivateKey` for signing and `*rsa.PublicKey` for validation 90 | * The [ECDSA signing method](https://godoc.org/github.com/dgrijalva/jwt-go#SigningMethodECDSA) (`ES256`,`ES384`,`ES512`) expect `*ecdsa.PrivateKey` for signing and `*ecdsa.PublicKey` for validation 91 | 92 | ### JWT and OAuth 93 | 94 | 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. 95 | 96 | Without going too far down the rabbit hole, here's a description of the interaction of these technologies: 97 | 98 | * 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. 99 | * 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. 100 | * 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. 101 | 102 | ### Troubleshooting 103 | 104 | 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. 105 | 106 | ## More 107 | 108 | Documentation can be found [on godoc.org](http://godoc.org/github.com/dgrijalva/jwt-go). 109 | 110 | 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. 111 | -------------------------------------------------------------------------------- /VERSION_HISTORY.md: -------------------------------------------------------------------------------- 1 | ## `jwt-go` Version History 2 | 3 | #### 3.2.0 4 | 5 | * Added method `ParseUnverified` to allow users to split up the tasks of parsing and validation 6 | * HMAC signing method returns `ErrInvalidKeyType` instead of `ErrInvalidKey` where appropriate 7 | * 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. 8 | * Deprecated `ParseFromRequestWithClaims` to simplify API in the future. 9 | 10 | #### 3.1.0 11 | 12 | * Improvements to `jwt` command line tool 13 | * Added `SkipClaimsValidation` option to `Parser` 14 | * Documentation updates 15 | 16 | #### 3.0.0 17 | 18 | * **Compatibility Breaking Changes**: See MIGRATION_GUIDE.md for tips on updating your code 19 | * 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. 20 | * `ParseFromRequest` has been moved to `request` subpackage and usage has changed 21 | * 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. 22 | * Other Additions and Changes 23 | * Added `Claims` interface type to allow users to decode the claims into a custom type 24 | * 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. 25 | * Dramatically improved the functionality and flexibility of `ParseFromRequest`, which is now in the `request` subpackage 26 | * Added `ParseFromRequestWithClaims` which is the `FromRequest` equivalent of `ParseWithClaims` 27 | * Added new interface type `Extractor`, which is used for extracting JWT strings from http requests. Used with `ParseFromRequest` and `ParseFromRequestWithClaims`. 28 | * Added several new, more specific, validation errors to error type bitmask 29 | * Moved examples from README to executable example files 30 | * Signing method registry is now thread safe 31 | * 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) 32 | 33 | #### 2.7.0 34 | 35 | This will likely be the last backwards compatible release before 3.0.0, excluding essential bug fixes. 36 | 37 | * Added new option `-show` to the `jwt` command that will just output the decoded token without verifying 38 | * Error text for expired tokens includes how long it's been expired 39 | * Fixed incorrect error returned from `ParseRSAPublicKeyFromPEM` 40 | * Documentation updates 41 | 42 | #### 2.6.0 43 | 44 | * Exposed inner error within ValidationError 45 | * Fixed validation errors when using UseJSONNumber flag 46 | * Added several unit tests 47 | 48 | #### 2.5.0 49 | 50 | * Added support for signing method none. You shouldn't use this. The API tries to make this clear. 51 | * Updated/fixed some documentation 52 | * Added more helpful error message when trying to parse tokens that begin with `BEARER ` 53 | 54 | #### 2.4.0 55 | 56 | * Added new type, Parser, to allow for configuration of various parsing parameters 57 | * You can now specify a list of valid signing methods. Anything outside this set will be rejected. 58 | * You can now opt to use the `json.Number` type instead of `float64` when parsing token JSON 59 | * Added support for [Travis CI](https://travis-ci.org/dgrijalva/jwt-go) 60 | * Fixed some bugs with ECDSA parsing 61 | 62 | #### 2.3.0 63 | 64 | * Added support for ECDSA signing methods 65 | * Added support for RSA PSS signing methods (requires go v1.4) 66 | 67 | #### 2.2.0 68 | 69 | * Gracefully handle a `nil` `Keyfunc` being passed to `Parse`. Result will now be the parsed token and an error, instead of a panic. 70 | 71 | #### 2.1.0 72 | 73 | Backwards compatible API change that was missed in 2.0.0. 74 | 75 | * The `SignedString` method on `Token` now takes `interface{}` instead of `[]byte` 76 | 77 | #### 2.0.0 78 | 79 | 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. 80 | 81 | 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`. 82 | 83 | 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`. 84 | 85 | * **Compatibility Breaking Changes** 86 | * `SigningMethodHS256` is now `*SigningMethodHMAC` instead of `type struct` 87 | * `SigningMethodRS256` is now `*SigningMethodRSA` instead of `type struct` 88 | * `KeyFunc` now returns `interface{}` instead of `[]byte` 89 | * `SigningMethod.Sign` now takes `interface{}` instead of `[]byte` for the key 90 | * `SigningMethod.Verify` now takes `interface{}` instead of `[]byte` for the key 91 | * Renamed type `SigningMethodHS256` to `SigningMethodHMAC`. Specific sizes are now just instances of this type. 92 | * Added public package global `SigningMethodHS256` 93 | * Added public package global `SigningMethodHS384` 94 | * Added public package global `SigningMethodHS512` 95 | * Renamed type `SigningMethodRS256` to `SigningMethodRSA`. Specific sizes are now just instances of this type. 96 | * Added public package global `SigningMethodRS256` 97 | * Added public package global `SigningMethodRS384` 98 | * Added public package global `SigningMethodRS512` 99 | * Moved sample private key for HMAC tests from an inline value to a file on disk. Value is unchanged. 100 | * Refactored the RSA implementation to be easier to read 101 | * Exposed helper methods `ParseRSAPrivateKeyFromPEM` and `ParseRSAPublicKeyFromPEM` 102 | 103 | #### 1.0.2 104 | 105 | * Fixed bug in parsing public keys from certificates 106 | * Added more tests around the parsing of keys for RS256 107 | * Code refactoring in RS256 implementation. No functional changes 108 | 109 | #### 1.0.1 110 | 111 | * Fixed panic if RS256 signing method was passed an invalid key 112 | 113 | #### 1.0.0 114 | 115 | * First versioned release 116 | * API stabilized 117 | * Supports creating, signing, parsing, and validating JWT tokens 118 | * Supports RS256 and HS256 signing methods -------------------------------------------------------------------------------- /claims.go: -------------------------------------------------------------------------------- 1 | package jwt 2 | 3 | import ( 4 | "crypto/subtle" 5 | "fmt" 6 | "time" 7 | ) 8 | 9 | // For a type to be a Claims object, it must just have a Valid method that determines 10 | // if the token is invalid for any supported reason 11 | type Claims interface { 12 | Valid() error 13 | } 14 | 15 | // Structured version of Claims Section, as referenced at 16 | // https://tools.ietf.org/html/rfc7519#section-4.1 17 | // See examples for how to use this with your own claim types 18 | type StandardClaims struct { 19 | Audience string `json:"aud,omitempty"` 20 | ExpiresAt int64 `json:"exp,omitempty"` 21 | Id string `json:"jti,omitempty"` 22 | IssuedAt int64 `json:"iat,omitempty"` 23 | Issuer string `json:"iss,omitempty"` 24 | NotBefore int64 `json:"nbf,omitempty"` 25 | Subject string `json:"sub,omitempty"` 26 | } 27 | 28 | // Validates time based claims "exp, iat, nbf". 29 | // There is no accounting for clock skew. 30 | // As well, if any of the above claims are not in the token, it will still 31 | // be considered a valid claim. 32 | func (c StandardClaims) Valid() error { 33 | vErr := new(ValidationError) 34 | now := TimeFunc().Unix() 35 | 36 | // The claims below are optional, by default, so if they are set to the 37 | // default value in Go, let's not fail the verification for them. 38 | if c.VerifyExpiresAt(now, false) == false { 39 | delta := time.Unix(now, 0).Sub(time.Unix(c.ExpiresAt, 0)) 40 | vErr.Inner = fmt.Errorf("token is expired by %v", delta) 41 | vErr.Errors |= ValidationErrorExpired 42 | } 43 | 44 | if c.VerifyIssuedAt(now, false) == false { 45 | vErr.Inner = fmt.Errorf("Token used before issued") 46 | vErr.Errors |= ValidationErrorIssuedAt 47 | } 48 | 49 | if c.VerifyNotBefore(now, false) == false { 50 | vErr.Inner = fmt.Errorf("token is not valid yet") 51 | vErr.Errors |= ValidationErrorNotValidYet 52 | } 53 | 54 | if vErr.valid() { 55 | return nil 56 | } 57 | 58 | return vErr 59 | } 60 | 61 | // Compares the aud claim against cmp. 62 | // If required is false, this method will return true if the value matches or is unset 63 | func (c *StandardClaims) VerifyAudience(cmp string, req bool) bool { 64 | return verifyAud([]string{c.Audience}, cmp, req) 65 | } 66 | 67 | // Compares the exp claim against cmp. 68 | // If required is false, this method will return true if the value matches or is unset 69 | func (c *StandardClaims) VerifyExpiresAt(cmp int64, req bool) bool { 70 | return verifyExp(c.ExpiresAt, cmp, req) 71 | } 72 | 73 | // Compares the iat claim against cmp. 74 | // If required is false, this method will return true if the value matches or is unset 75 | func (c *StandardClaims) VerifyIssuedAt(cmp int64, req bool) bool { 76 | return verifyIat(c.IssuedAt, cmp, req) 77 | } 78 | 79 | // Compares the iss claim against cmp. 80 | // If required is false, this method will return true if the value matches or is unset 81 | func (c *StandardClaims) VerifyIssuer(cmp string, req bool) bool { 82 | return verifyIss(c.Issuer, cmp, req) 83 | } 84 | 85 | // Compares the nbf claim against cmp. 86 | // If required is false, this method will return true if the value matches or is unset 87 | func (c *StandardClaims) VerifyNotBefore(cmp int64, req bool) bool { 88 | return verifyNbf(c.NotBefore, cmp, req) 89 | } 90 | 91 | // ----- helpers 92 | 93 | func verifyAud(aud []string, cmp string, required bool) bool { 94 | if len(aud) == 0 { 95 | return !required 96 | } 97 | // use a var here to keep constant time compare when looping over a number of claims 98 | result := false 99 | 100 | var stringClaims string 101 | for _, a := range aud { 102 | if subtle.ConstantTimeCompare([]byte(a), []byte(cmp)) != 0 { 103 | result = true 104 | } 105 | stringClaims = stringClaims + a 106 | } 107 | 108 | // case where "" is sent in one or many aud claims 109 | if len(stringClaims) == 0 { 110 | return !required 111 | } 112 | 113 | return result 114 | } 115 | 116 | func verifyExp(exp int64, now int64, required bool) bool { 117 | if exp == 0 { 118 | return !required 119 | } 120 | return now <= exp 121 | } 122 | 123 | func verifyIat(iat int64, now int64, required bool) bool { 124 | if iat == 0 { 125 | return !required 126 | } 127 | return now >= iat 128 | } 129 | 130 | func verifyIss(iss string, cmp string, required bool) bool { 131 | if iss == "" { 132 | return !required 133 | } 134 | if subtle.ConstantTimeCompare([]byte(iss), []byte(cmp)) != 0 { 135 | return true 136 | } else { 137 | return false 138 | } 139 | } 140 | 141 | func verifyNbf(nbf int64, now int64, required bool) bool { 142 | if nbf == 0 { 143 | return !required 144 | } 145 | return now >= nbf 146 | } 147 | -------------------------------------------------------------------------------- /cmd/jwt/README.md: -------------------------------------------------------------------------------- 1 | `jwt` command-line tool 2 | ======================= 3 | 4 | This is a simple tool to sign, verify and show JSON Web Tokens from 5 | the command line. 6 | 7 | The following will create and sign a token, then verify it and output the original claims: 8 | 9 | echo {\"foo\":\"bar\"} | ./jwt -key ../../test/sample_key -alg RS256 -sign - | ./jwt -key ../../test/sample_key.pub -alg RS256 -verify - 10 | 11 | Key files should be in PEM format. Other formats are not supported by this tool. 12 | 13 | To simply display a token, use: 14 | 15 | echo $JWT | ./jwt -show - 16 | 17 | You can install this tool with the following command: 18 | 19 | go install github.com/dgrijalva/jwt-go/cmd/jwt 20 | 21 | -------------------------------------------------------------------------------- /cmd/jwt/app.go: -------------------------------------------------------------------------------- 1 | // A useful example app. You can use this to debug your tokens on the command line. 2 | // This is also a great place to look at how you might use this library. 3 | // 4 | // Example usage: 5 | // The following will create and sign a token, then verify it and output the original claims. 6 | // echo {\"foo\":\"bar\"} | bin/jwt -key test/sample_key -alg RS256 -sign - | bin/jwt -key test/sample_key.pub -verify - 7 | package main 8 | 9 | import ( 10 | "encoding/json" 11 | "flag" 12 | "fmt" 13 | "io" 14 | "io/ioutil" 15 | "os" 16 | "regexp" 17 | "strings" 18 | 19 | jwt "github.com/dgrijalva/jwt-go" 20 | ) 21 | 22 | var ( 23 | // Options 24 | flagAlg = flag.String("alg", "", "signing algorithm identifier") 25 | flagKey = flag.String("key", "", "path to key file or '-' to read from stdin") 26 | flagCompact = flag.Bool("compact", false, "output compact JSON") 27 | flagDebug = flag.Bool("debug", false, "print out all kinds of debug data") 28 | flagClaims = make(ArgList) 29 | flagHead = make(ArgList) 30 | 31 | // Modes - exactly one of these is required 32 | flagSign = flag.String("sign", "", "path to claims object to sign, '-' to read from stdin, or '+' to use only -claim args") 33 | flagVerify = flag.String("verify", "", "path to JWT token to verify or '-' to read from stdin") 34 | flagShow = flag.String("show", "", "path to JWT file or '-' to read from stdin") 35 | ) 36 | 37 | func main() { 38 | // Plug in Var flags 39 | flag.Var(flagClaims, "claim", "add additional claims. may be used more than once") 40 | flag.Var(flagHead, "header", "add additional header params. may be used more than once") 41 | 42 | // Usage message if you ask for -help or if you mess up inputs. 43 | flag.Usage = func() { 44 | fmt.Fprintf(os.Stderr, "Usage of %s:\n", os.Args[0]) 45 | fmt.Fprintf(os.Stderr, " One of the following flags is required: sign, verify\n") 46 | flag.PrintDefaults() 47 | } 48 | 49 | // Parse command line options 50 | flag.Parse() 51 | 52 | // Do the thing. If something goes wrong, print error to stderr 53 | // and exit with a non-zero status code 54 | if err := start(); err != nil { 55 | fmt.Fprintf(os.Stderr, "Error: %v\n", err) 56 | os.Exit(1) 57 | } 58 | } 59 | 60 | // Figure out which thing to do and then do that 61 | func start() error { 62 | if *flagSign != "" { 63 | return signToken() 64 | } else if *flagVerify != "" { 65 | return verifyToken() 66 | } else if *flagShow != "" { 67 | return showToken() 68 | } else { 69 | flag.Usage() 70 | return fmt.Errorf("None of the required flags are present. What do you want me to do?") 71 | } 72 | } 73 | 74 | // Helper func: Read input from specified file or stdin 75 | func loadData(p string) ([]byte, error) { 76 | if p == "" { 77 | return nil, fmt.Errorf("No path specified") 78 | } 79 | 80 | var rdr io.Reader 81 | if p == "-" { 82 | rdr = os.Stdin 83 | } else if p == "+" { 84 | return []byte("{}"), nil 85 | } else { 86 | if f, err := os.Open(p); err == nil { 87 | rdr = f 88 | defer f.Close() 89 | } else { 90 | return nil, err 91 | } 92 | } 93 | return ioutil.ReadAll(rdr) 94 | } 95 | 96 | // Print a json object in accordance with the prophecy (or the command line options) 97 | func printJSON(j interface{}) error { 98 | var out []byte 99 | var err error 100 | 101 | if *flagCompact == false { 102 | out, err = json.MarshalIndent(j, "", " ") 103 | } else { 104 | out, err = json.Marshal(j) 105 | } 106 | 107 | if err == nil { 108 | fmt.Println(string(out)) 109 | } 110 | 111 | return err 112 | } 113 | 114 | // Verify a token and output the claims. This is a great example 115 | // of how to verify and view a token. 116 | func verifyToken() error { 117 | // get the token 118 | tokData, err := loadData(*flagVerify) 119 | if err != nil { 120 | return fmt.Errorf("Couldn't read token: %v", err) 121 | } 122 | 123 | // trim possible whitespace from token 124 | tokData = regexp.MustCompile(`\s*$`).ReplaceAll(tokData, []byte{}) 125 | if *flagDebug { 126 | fmt.Fprintf(os.Stderr, "Token len: %v bytes\n", len(tokData)) 127 | } 128 | 129 | // Parse the token. Load the key from command line option 130 | token, err := jwt.Parse(string(tokData), func(t *jwt.Token) (interface{}, error) { 131 | data, err := loadData(*flagKey) 132 | if err != nil { 133 | return nil, err 134 | } 135 | if isEs() { 136 | return jwt.ParseECPublicKeyFromPEM(data) 137 | } else if isRs() { 138 | return jwt.ParseRSAPublicKeyFromPEM(data) 139 | } 140 | return data, nil 141 | }) 142 | 143 | // Print some debug data 144 | if *flagDebug && token != nil { 145 | fmt.Fprintf(os.Stderr, "Header:\n%v\n", token.Header) 146 | fmt.Fprintf(os.Stderr, "Claims:\n%v\n", token.Claims) 147 | } 148 | 149 | // Print an error if we can't parse for some reason 150 | if err != nil { 151 | return fmt.Errorf("Couldn't parse token: %v", err) 152 | } 153 | 154 | // Is token invalid? 155 | if !token.Valid { 156 | return fmt.Errorf("Token is invalid") 157 | } 158 | 159 | // Print the token details 160 | if err := printJSON(token.Claims); err != nil { 161 | return fmt.Errorf("Failed to output claims: %v", err) 162 | } 163 | 164 | return nil 165 | } 166 | 167 | // Create, sign, and output a token. This is a great, simple example of 168 | // how to use this library to create and sign a token. 169 | func signToken() error { 170 | // get the token data from command line arguments 171 | tokData, err := loadData(*flagSign) 172 | if err != nil { 173 | return fmt.Errorf("Couldn't read token: %v", err) 174 | } else if *flagDebug { 175 | fmt.Fprintf(os.Stderr, "Token: %v bytes", len(tokData)) 176 | } 177 | 178 | // parse the JSON of the claims 179 | var claims jwt.MapClaims 180 | if err := json.Unmarshal(tokData, &claims); err != nil { 181 | return fmt.Errorf("Couldn't parse claims JSON: %v", err) 182 | } 183 | 184 | // add command line claims 185 | if len(flagClaims) > 0 { 186 | for k, v := range flagClaims { 187 | claims[k] = v 188 | } 189 | } 190 | 191 | // get the key 192 | var key interface{} 193 | key, err = loadData(*flagKey) 194 | if err != nil { 195 | return fmt.Errorf("Couldn't read key: %v", err) 196 | } 197 | 198 | // get the signing alg 199 | alg := jwt.GetSigningMethod(*flagAlg) 200 | if alg == nil { 201 | return fmt.Errorf("Couldn't find signing method: %v", *flagAlg) 202 | } 203 | 204 | // create a new token 205 | token := jwt.NewWithClaims(alg, claims) 206 | 207 | // add command line headers 208 | if len(flagHead) > 0 { 209 | for k, v := range flagHead { 210 | token.Header[k] = v 211 | } 212 | } 213 | 214 | if isEs() { 215 | if k, ok := key.([]byte); !ok { 216 | return fmt.Errorf("Couldn't convert key data to key") 217 | } else { 218 | key, err = jwt.ParseECPrivateKeyFromPEM(k) 219 | if err != nil { 220 | return err 221 | } 222 | } 223 | } else if isRs() { 224 | if k, ok := key.([]byte); !ok { 225 | return fmt.Errorf("Couldn't convert key data to key") 226 | } else { 227 | key, err = jwt.ParseRSAPrivateKeyFromPEM(k) 228 | if err != nil { 229 | return err 230 | } 231 | } 232 | } 233 | 234 | if out, err := token.SignedString(key); err == nil { 235 | fmt.Println(out) 236 | } else { 237 | return fmt.Errorf("Error signing token: %v", err) 238 | } 239 | 240 | return nil 241 | } 242 | 243 | // showToken pretty-prints the token on the command line. 244 | func showToken() error { 245 | // get the token 246 | tokData, err := loadData(*flagShow) 247 | if err != nil { 248 | return fmt.Errorf("Couldn't read token: %v", err) 249 | } 250 | 251 | // trim possible whitespace from token 252 | tokData = regexp.MustCompile(`\s*$`).ReplaceAll(tokData, []byte{}) 253 | if *flagDebug { 254 | fmt.Fprintf(os.Stderr, "Token len: %v bytes\n", len(tokData)) 255 | } 256 | 257 | token, err := jwt.Parse(string(tokData), nil) 258 | if token == nil { 259 | return fmt.Errorf("malformed token: %v", err) 260 | } 261 | 262 | // Print the token details 263 | fmt.Println("Header:") 264 | if err := printJSON(token.Header); err != nil { 265 | return fmt.Errorf("Failed to output header: %v", err) 266 | } 267 | 268 | fmt.Println("Claims:") 269 | if err := printJSON(token.Claims); err != nil { 270 | return fmt.Errorf("Failed to output claims: %v", err) 271 | } 272 | 273 | return nil 274 | } 275 | 276 | func isEs() bool { 277 | return strings.HasPrefix(*flagAlg, "ES") 278 | } 279 | 280 | func isRs() bool { 281 | return strings.HasPrefix(*flagAlg, "RS") || strings.HasPrefix(*flagAlg, "PS") 282 | } 283 | -------------------------------------------------------------------------------- /cmd/jwt/args.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | "strings" 7 | ) 8 | 9 | type ArgList map[string]string 10 | 11 | func (l ArgList) String() string { 12 | data, _ := json.Marshal(l) 13 | return string(data) 14 | } 15 | 16 | func (l ArgList) Set(arg string) error { 17 | parts := strings.SplitN(arg, "=", 2) 18 | if len(parts) != 2 { 19 | return fmt.Errorf("Invalid argument '%v'. Must use format 'key=value'. %v", arg, parts) 20 | } 21 | l[parts[0]] = parts[1] 22 | return nil 23 | } 24 | -------------------------------------------------------------------------------- /doc.go: -------------------------------------------------------------------------------- 1 | // Package jwt is a Go implementation of JSON Web Tokens: http://self-issued.info/docs/draft-jones-json-web-token.html 2 | // 3 | // See README.md for more info. 4 | package jwt 5 | -------------------------------------------------------------------------------- /ecdsa.go: -------------------------------------------------------------------------------- 1 | package jwt 2 | 3 | import ( 4 | "crypto" 5 | "crypto/ecdsa" 6 | "crypto/rand" 7 | "errors" 8 | "math/big" 9 | ) 10 | 11 | var ( 12 | // Sadly this is missing from crypto/ecdsa compared to crypto/rsa 13 | ErrECDSAVerification = errors.New("crypto/ecdsa: verification error") 14 | ) 15 | 16 | // Implements the ECDSA family of signing methods signing methods 17 | // Expects *ecdsa.PrivateKey for signing and *ecdsa.PublicKey for verification 18 | type SigningMethodECDSA struct { 19 | Name string 20 | Hash crypto.Hash 21 | KeySize int 22 | CurveBits int 23 | } 24 | 25 | // Specific instances for EC256 and company 26 | var ( 27 | SigningMethodES256 *SigningMethodECDSA 28 | SigningMethodES384 *SigningMethodECDSA 29 | SigningMethodES512 *SigningMethodECDSA 30 | ) 31 | 32 | func init() { 33 | // ES256 34 | SigningMethodES256 = &SigningMethodECDSA{"ES256", crypto.SHA256, 32, 256} 35 | RegisterSigningMethod(SigningMethodES256.Alg(), func() SigningMethod { 36 | return SigningMethodES256 37 | }) 38 | 39 | // ES384 40 | SigningMethodES384 = &SigningMethodECDSA{"ES384", crypto.SHA384, 48, 384} 41 | RegisterSigningMethod(SigningMethodES384.Alg(), func() SigningMethod { 42 | return SigningMethodES384 43 | }) 44 | 45 | // ES512 46 | SigningMethodES512 = &SigningMethodECDSA{"ES512", crypto.SHA512, 66, 521} 47 | RegisterSigningMethod(SigningMethodES512.Alg(), func() SigningMethod { 48 | return SigningMethodES512 49 | }) 50 | } 51 | 52 | func (m *SigningMethodECDSA) Alg() string { 53 | return m.Name 54 | } 55 | 56 | // Implements the Verify method from SigningMethod 57 | // For this verify method, key must be an ecdsa.PublicKey struct 58 | func (m *SigningMethodECDSA) Verify(signingString, signature string, key interface{}) error { 59 | var err error 60 | 61 | // Decode the signature 62 | var sig []byte 63 | if sig, err = DecodeSegment(signature); err != nil { 64 | return err 65 | } 66 | 67 | // Get the key 68 | var ecdsaKey *ecdsa.PublicKey 69 | switch k := key.(type) { 70 | case *ecdsa.PublicKey: 71 | ecdsaKey = k 72 | default: 73 | return ErrInvalidKeyType 74 | } 75 | 76 | if len(sig) != 2*m.KeySize { 77 | return ErrECDSAVerification 78 | } 79 | 80 | r := big.NewInt(0).SetBytes(sig[:m.KeySize]) 81 | s := big.NewInt(0).SetBytes(sig[m.KeySize:]) 82 | 83 | // Create hasher 84 | if !m.Hash.Available() { 85 | return ErrHashUnavailable 86 | } 87 | hasher := m.Hash.New() 88 | hasher.Write([]byte(signingString)) 89 | 90 | // Verify the signature 91 | if verifystatus := ecdsa.Verify(ecdsaKey, hasher.Sum(nil), r, s); verifystatus == true { 92 | return nil 93 | } else { 94 | return ErrECDSAVerification 95 | } 96 | } 97 | 98 | // Implements the Sign method from SigningMethod 99 | // For this signing method, key must be an ecdsa.PrivateKey struct 100 | func (m *SigningMethodECDSA) Sign(signingString string, key interface{}) (string, error) { 101 | // Get the key 102 | var ecdsaKey *ecdsa.PrivateKey 103 | switch k := key.(type) { 104 | case *ecdsa.PrivateKey: 105 | ecdsaKey = k 106 | default: 107 | return "", ErrInvalidKeyType 108 | } 109 | 110 | // Create the hasher 111 | if !m.Hash.Available() { 112 | return "", ErrHashUnavailable 113 | } 114 | 115 | hasher := m.Hash.New() 116 | hasher.Write([]byte(signingString)) 117 | 118 | // Sign the string and return r, s 119 | if r, s, err := ecdsa.Sign(rand.Reader, ecdsaKey, hasher.Sum(nil)); err == nil { 120 | curveBits := ecdsaKey.Curve.Params().BitSize 121 | 122 | if m.CurveBits != curveBits { 123 | return "", ErrInvalidKey 124 | } 125 | 126 | keyBytes := curveBits / 8 127 | if curveBits%8 > 0 { 128 | keyBytes += 1 129 | } 130 | 131 | // We serialize the outpus (r and s) into big-endian byte arrays and pad 132 | // them with zeros on the left to make sure the sizes work out. Both arrays 133 | // must be keyBytes long, and the output must be 2*keyBytes long. 134 | rBytes := r.Bytes() 135 | rBytesPadded := make([]byte, keyBytes) 136 | copy(rBytesPadded[keyBytes-len(rBytes):], rBytes) 137 | 138 | sBytes := s.Bytes() 139 | sBytesPadded := make([]byte, keyBytes) 140 | copy(sBytesPadded[keyBytes-len(sBytes):], sBytes) 141 | 142 | out := append(rBytesPadded, sBytesPadded...) 143 | 144 | return EncodeSegment(out), nil 145 | } else { 146 | return "", err 147 | } 148 | } 149 | -------------------------------------------------------------------------------- /ecdsa_test.go: -------------------------------------------------------------------------------- 1 | package jwt_test 2 | 3 | import ( 4 | "crypto/ecdsa" 5 | "io/ioutil" 6 | "strings" 7 | "testing" 8 | 9 | "github.com/dgrijalva/jwt-go" 10 | ) 11 | 12 | var ecdsaTestData = []struct { 13 | name string 14 | keys map[string]string 15 | tokenString string 16 | alg string 17 | claims map[string]interface{} 18 | valid bool 19 | }{ 20 | { 21 | "Basic ES256", 22 | map[string]string{"private": "test/ec256-private.pem", "public": "test/ec256-public.pem"}, 23 | "eyJ0eXAiOiJKV1QiLCJhbGciOiJFUzI1NiJ9.eyJmb28iOiJiYXIifQ.feG39E-bn8HXAKhzDZq7yEAPWYDhZlwTn3sePJnU9VrGMmwdXAIEyoOnrjreYlVM_Z4N13eK9-TmMTWyfKJtHQ", 24 | "ES256", 25 | map[string]interface{}{"foo": "bar"}, 26 | true, 27 | }, 28 | { 29 | "Basic ES384", 30 | map[string]string{"private": "test/ec384-private.pem", "public": "test/ec384-public.pem"}, 31 | "eyJ0eXAiOiJKV1QiLCJhbGciOiJFUzM4NCJ9.eyJmb28iOiJiYXIifQ.ngAfKMbJUh0WWubSIYe5GMsA-aHNKwFbJk_wq3lq23aPp8H2anb1rRILIzVR0gUf4a8WzDtrzmiikuPWyCS6CN4-PwdgTk-5nehC7JXqlaBZU05p3toM3nWCwm_LXcld", 32 | "ES384", 33 | map[string]interface{}{"foo": "bar"}, 34 | true, 35 | }, 36 | { 37 | "Basic ES512", 38 | map[string]string{"private": "test/ec512-private.pem", "public": "test/ec512-public.pem"}, 39 | "eyJ0eXAiOiJKV1QiLCJhbGciOiJFUzUxMiJ9.eyJmb28iOiJiYXIifQ.AAU0TvGQOcdg2OvrwY73NHKgfk26UDekh9Prz-L_iWuTBIBqOFCWwwLsRiHB1JOddfKAls5do1W0jR_F30JpVd-6AJeTjGKA4C1A1H6gIKwRY0o_tFDIydZCl_lMBMeG5VNFAjO86-WCSKwc3hqaGkq1MugPRq_qrF9AVbuEB4JPLyL5", 40 | "ES512", 41 | map[string]interface{}{"foo": "bar"}, 42 | true, 43 | }, 44 | { 45 | "basic ES256 invalid: foo => bar", 46 | map[string]string{"private": "test/ec256-private.pem", "public": "test/ec256-public.pem"}, 47 | "eyJhbGciOiJFUzI1NiIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIifQ.MEQCIHoSJnmGlPaVQDqacx_2XlXEhhqtWceVopjomc2PJLtdAiAUTeGPoNYxZw0z8mgOnnIcjoxRuNDVZvybRZF3wR1l8W", 48 | "ES256", 49 | map[string]interface{}{"foo": "bar"}, 50 | false, 51 | }, 52 | } 53 | 54 | func TestECDSAVerify(t *testing.T) { 55 | for _, data := range ecdsaTestData { 56 | var err error 57 | 58 | key, _ := ioutil.ReadFile(data.keys["public"]) 59 | 60 | var ecdsaKey *ecdsa.PublicKey 61 | if ecdsaKey, err = jwt.ParseECPublicKeyFromPEM(key); err != nil { 62 | t.Errorf("Unable to parse ECDSA public key: %v", err) 63 | } 64 | 65 | parts := strings.Split(data.tokenString, ".") 66 | 67 | method := jwt.GetSigningMethod(data.alg) 68 | err = method.Verify(strings.Join(parts[0:2], "."), parts[2], ecdsaKey) 69 | if data.valid && err != nil { 70 | t.Errorf("[%v] Error while verifying key: %v", data.name, err) 71 | } 72 | if !data.valid && err == nil { 73 | t.Errorf("[%v] Invalid key passed validation", data.name) 74 | } 75 | } 76 | } 77 | 78 | func TestECDSASign(t *testing.T) { 79 | for _, data := range ecdsaTestData { 80 | var err error 81 | key, _ := ioutil.ReadFile(data.keys["private"]) 82 | 83 | var ecdsaKey *ecdsa.PrivateKey 84 | if ecdsaKey, err = jwt.ParseECPrivateKeyFromPEM(key); err != nil { 85 | t.Errorf("Unable to parse ECDSA private key: %v", err) 86 | } 87 | 88 | if data.valid { 89 | parts := strings.Split(data.tokenString, ".") 90 | method := jwt.GetSigningMethod(data.alg) 91 | sig, err := method.Sign(strings.Join(parts[0:2], "."), ecdsaKey) 92 | if err != nil { 93 | t.Errorf("[%v] Error signing token: %v", data.name, err) 94 | } 95 | if sig == parts[2] { 96 | t.Errorf("[%v] Identical signatures\nbefore:\n%v\nafter:\n%v", data.name, parts[2], sig) 97 | } 98 | } 99 | } 100 | } 101 | -------------------------------------------------------------------------------- /ecdsa_utils.go: -------------------------------------------------------------------------------- 1 | package jwt 2 | 3 | import ( 4 | "crypto/ecdsa" 5 | "crypto/x509" 6 | "encoding/pem" 7 | "errors" 8 | ) 9 | 10 | var ( 11 | ErrNotECPublicKey = errors.New("Key is not a valid ECDSA public key") 12 | ErrNotECPrivateKey = errors.New("Key is not a valid ECDSA private key") 13 | ) 14 | 15 | // Parse PEM encoded Elliptic Curve Private Key Structure 16 | func ParseECPrivateKeyFromPEM(key []byte) (*ecdsa.PrivateKey, error) { 17 | var err error 18 | 19 | // Parse PEM block 20 | var block *pem.Block 21 | if block, _ = pem.Decode(key); block == nil { 22 | return nil, ErrKeyMustBePEMEncoded 23 | } 24 | 25 | // Parse the key 26 | var parsedKey interface{} 27 | if parsedKey, err = x509.ParseECPrivateKey(block.Bytes); err != nil { 28 | if parsedKey, err = x509.ParsePKCS8PrivateKey(block.Bytes); err != nil { 29 | return nil, err 30 | } 31 | } 32 | 33 | var pkey *ecdsa.PrivateKey 34 | var ok bool 35 | if pkey, ok = parsedKey.(*ecdsa.PrivateKey); !ok { 36 | return nil, ErrNotECPrivateKey 37 | } 38 | 39 | return pkey, nil 40 | } 41 | 42 | // Parse PEM encoded PKCS1 or PKCS8 public key 43 | func ParseECPublicKeyFromPEM(key []byte) (*ecdsa.PublicKey, error) { 44 | var err error 45 | 46 | // Parse PEM block 47 | var block *pem.Block 48 | if block, _ = pem.Decode(key); block == nil { 49 | return nil, ErrKeyMustBePEMEncoded 50 | } 51 | 52 | // Parse the key 53 | var parsedKey interface{} 54 | if parsedKey, err = x509.ParsePKIXPublicKey(block.Bytes); err != nil { 55 | if cert, err := x509.ParseCertificate(block.Bytes); err == nil { 56 | parsedKey = cert.PublicKey 57 | } else { 58 | return nil, err 59 | } 60 | } 61 | 62 | var pkey *ecdsa.PublicKey 63 | var ok bool 64 | if pkey, ok = parsedKey.(*ecdsa.PublicKey); !ok { 65 | return nil, ErrNotECPublicKey 66 | } 67 | 68 | return pkey, nil 69 | } 70 | -------------------------------------------------------------------------------- /errors.go: -------------------------------------------------------------------------------- 1 | package jwt 2 | 3 | import ( 4 | "errors" 5 | ) 6 | 7 | // Error constants 8 | var ( 9 | ErrInvalidKey = errors.New("key is invalid") 10 | ErrInvalidKeyType = errors.New("key is of invalid type") 11 | ErrHashUnavailable = errors.New("the requested hash function is unavailable") 12 | ) 13 | 14 | // The errors that might occur when parsing and validating a token 15 | const ( 16 | ValidationErrorMalformed uint32 = 1 << iota // Token is malformed 17 | ValidationErrorUnverifiable // Token could not be verified because of signing problems 18 | ValidationErrorSignatureInvalid // Signature validation failed 19 | 20 | // Standard Claim validation errors 21 | ValidationErrorAudience // AUD validation failed 22 | ValidationErrorExpired // EXP validation failed 23 | ValidationErrorIssuedAt // IAT validation failed 24 | ValidationErrorIssuer // ISS validation failed 25 | ValidationErrorNotValidYet // NBF validation failed 26 | ValidationErrorId // JTI validation failed 27 | ValidationErrorClaimsInvalid // Generic claims validation error 28 | ) 29 | 30 | // Helper for constructing a ValidationError with a string error message 31 | func NewValidationError(errorText string, errorFlags uint32) *ValidationError { 32 | return &ValidationError{ 33 | text: errorText, 34 | Errors: errorFlags, 35 | } 36 | } 37 | 38 | // The error from Parse if token is not valid 39 | type ValidationError struct { 40 | Inner error // stores the error returned by external dependencies, i.e.: KeyFunc 41 | Errors uint32 // bitfield. see ValidationError... constants 42 | text string // errors that do not have a valid error just have text 43 | } 44 | 45 | // Validation error is an error type 46 | func (e ValidationError) Error() string { 47 | if e.Inner != nil { 48 | return e.Inner.Error() 49 | } else if e.text != "" { 50 | return e.text 51 | } else { 52 | return "token is invalid" 53 | } 54 | } 55 | 56 | // No errors 57 | func (e *ValidationError) valid() bool { 58 | return e.Errors == 0 59 | } 60 | -------------------------------------------------------------------------------- /example_test.go: -------------------------------------------------------------------------------- 1 | package jwt_test 2 | 3 | import ( 4 | "fmt" 5 | "github.com/dgrijalva/jwt-go" 6 | "time" 7 | ) 8 | 9 | // Example (atypical) using the StandardClaims type by itself to parse a token. 10 | // The StandardClaims type is designed to be embedded into your custom types 11 | // to provide standard validation features. You can use it alone, but there's 12 | // no way to retrieve other fields after parsing. 13 | // See the CustomClaimsType example for intended usage. 14 | func ExampleNewWithClaims_standardClaims() { 15 | mySigningKey := []byte("AllYourBase") 16 | 17 | // Create the Claims 18 | claims := &jwt.StandardClaims{ 19 | ExpiresAt: 15000, 20 | Issuer: "test", 21 | } 22 | 23 | token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims) 24 | ss, err := token.SignedString(mySigningKey) 25 | fmt.Printf("%v %v", ss, err) 26 | //Output: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1MDAwLCJpc3MiOiJ0ZXN0In0.QsODzZu3lUZMVdhbO76u3Jv02iYCvEHcYVUI1kOWEU0 27 | } 28 | 29 | // Example creating a token using a custom claims type. The StandardClaim is embedded 30 | // in the custom type to allow for easy encoding, parsing and validation of standard claims. 31 | func ExampleNewWithClaims_customClaimsType() { 32 | mySigningKey := []byte("AllYourBase") 33 | 34 | type MyCustomClaims struct { 35 | Foo string `json:"foo"` 36 | jwt.StandardClaims 37 | } 38 | 39 | // Create the Claims 40 | claims := MyCustomClaims{ 41 | "bar", 42 | jwt.StandardClaims{ 43 | ExpiresAt: 15000, 44 | Issuer: "test", 45 | }, 46 | } 47 | 48 | token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims) 49 | ss, err := token.SignedString(mySigningKey) 50 | fmt.Printf("%v %v", ss, err) 51 | //Output: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIiLCJleHAiOjE1MDAwLCJpc3MiOiJ0ZXN0In0.HE7fK0xOQwFEr4WDgRWj4teRPZ6i3GLwD5YCm6Pwu_c 52 | } 53 | 54 | // Example creating a token using a custom claims type. The StandardClaim is embedded 55 | // in the custom type to allow for easy encoding, parsing and validation of standard claims. 56 | func ExampleParseWithClaims_customClaimsType() { 57 | tokenString := "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIiLCJleHAiOjE1MDAwLCJpc3MiOiJ0ZXN0In0.HE7fK0xOQwFEr4WDgRWj4teRPZ6i3GLwD5YCm6Pwu_c" 58 | 59 | type MyCustomClaims struct { 60 | Foo string `json:"foo"` 61 | jwt.StandardClaims 62 | } 63 | 64 | // sample token is expired. override time so it parses as valid 65 | at(time.Unix(0, 0), func() { 66 | token, err := jwt.ParseWithClaims(tokenString, &MyCustomClaims{}, func(token *jwt.Token) (interface{}, error) { 67 | return []byte("AllYourBase"), nil 68 | }) 69 | 70 | if claims, ok := token.Claims.(*MyCustomClaims); ok && token.Valid { 71 | fmt.Printf("%v %v", claims.Foo, claims.StandardClaims.ExpiresAt) 72 | } else { 73 | fmt.Println(err) 74 | } 75 | }) 76 | 77 | // Output: bar 15000 78 | } 79 | 80 | // Override time value for tests. Restore default value after. 81 | func at(t time.Time, f func()) { 82 | jwt.TimeFunc = func() time.Time { 83 | return t 84 | } 85 | f() 86 | jwt.TimeFunc = time.Now 87 | } 88 | 89 | // An example of parsing the error types using bitfield checks 90 | func ExampleParse_errorChecking() { 91 | // Token from another example. This token is expired 92 | var tokenString = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIiLCJleHAiOjE1MDAwLCJpc3MiOiJ0ZXN0In0.HE7fK0xOQwFEr4WDgRWj4teRPZ6i3GLwD5YCm6Pwu_c" 93 | 94 | token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) { 95 | return []byte("AllYourBase"), nil 96 | }) 97 | 98 | if token.Valid { 99 | fmt.Println("You look nice today") 100 | } else if ve, ok := err.(*jwt.ValidationError); ok { 101 | if ve.Errors&jwt.ValidationErrorMalformed != 0 { 102 | fmt.Println("That's not even a token") 103 | } else if ve.Errors&(jwt.ValidationErrorExpired|jwt.ValidationErrorNotValidYet) != 0 { 104 | // Token is either expired or not active yet 105 | fmt.Println("Timing is everything") 106 | } else { 107 | fmt.Println("Couldn't handle this token:", err) 108 | } 109 | } else { 110 | fmt.Println("Couldn't handle this token:", err) 111 | } 112 | 113 | // Output: Timing is everything 114 | } 115 | -------------------------------------------------------------------------------- /hmac.go: -------------------------------------------------------------------------------- 1 | package jwt 2 | 3 | import ( 4 | "crypto" 5 | "crypto/hmac" 6 | "errors" 7 | ) 8 | 9 | // Implements the HMAC-SHA family of signing methods signing methods 10 | // Expects key type of []byte for both signing and validation 11 | type SigningMethodHMAC struct { 12 | Name string 13 | Hash crypto.Hash 14 | } 15 | 16 | // Specific instances for HS256 and company 17 | var ( 18 | SigningMethodHS256 *SigningMethodHMAC 19 | SigningMethodHS384 *SigningMethodHMAC 20 | SigningMethodHS512 *SigningMethodHMAC 21 | ErrSignatureInvalid = errors.New("signature is invalid") 22 | ) 23 | 24 | func init() { 25 | // HS256 26 | SigningMethodHS256 = &SigningMethodHMAC{"HS256", crypto.SHA256} 27 | RegisterSigningMethod(SigningMethodHS256.Alg(), func() SigningMethod { 28 | return SigningMethodHS256 29 | }) 30 | 31 | // HS384 32 | SigningMethodHS384 = &SigningMethodHMAC{"HS384", crypto.SHA384} 33 | RegisterSigningMethod(SigningMethodHS384.Alg(), func() SigningMethod { 34 | return SigningMethodHS384 35 | }) 36 | 37 | // HS512 38 | SigningMethodHS512 = &SigningMethodHMAC{"HS512", crypto.SHA512} 39 | RegisterSigningMethod(SigningMethodHS512.Alg(), func() SigningMethod { 40 | return SigningMethodHS512 41 | }) 42 | } 43 | 44 | func (m *SigningMethodHMAC) Alg() string { 45 | return m.Name 46 | } 47 | 48 | // Verify the signature of HSXXX tokens. Returns nil if the signature is valid. 49 | func (m *SigningMethodHMAC) Verify(signingString, signature string, key interface{}) error { 50 | // Verify the key is the right type 51 | keyBytes, ok := key.([]byte) 52 | if !ok { 53 | return ErrInvalidKeyType 54 | } 55 | 56 | // Decode signature, for comparison 57 | sig, err := DecodeSegment(signature) 58 | if err != nil { 59 | return err 60 | } 61 | 62 | // Can we use the specified hashing method? 63 | if !m.Hash.Available() { 64 | return ErrHashUnavailable 65 | } 66 | 67 | // This signing method is symmetric, so we validate the signature 68 | // by reproducing the signature from the signing string and key, then 69 | // comparing that against the provided signature. 70 | hasher := hmac.New(m.Hash.New, keyBytes) 71 | hasher.Write([]byte(signingString)) 72 | if !hmac.Equal(sig, hasher.Sum(nil)) { 73 | return ErrSignatureInvalid 74 | } 75 | 76 | // No validation errors. Signature is good. 77 | return nil 78 | } 79 | 80 | // Implements the Sign method from SigningMethod for this signing method. 81 | // Key must be []byte 82 | func (m *SigningMethodHMAC) Sign(signingString string, key interface{}) (string, error) { 83 | if keyBytes, ok := key.([]byte); ok { 84 | if !m.Hash.Available() { 85 | return "", ErrHashUnavailable 86 | } 87 | 88 | hasher := hmac.New(m.Hash.New, keyBytes) 89 | hasher.Write([]byte(signingString)) 90 | 91 | return EncodeSegment(hasher.Sum(nil)), nil 92 | } 93 | 94 | return "", ErrInvalidKeyType 95 | } 96 | -------------------------------------------------------------------------------- /hmac_example_test.go: -------------------------------------------------------------------------------- 1 | package jwt_test 2 | 3 | import ( 4 | "fmt" 5 | "github.com/dgrijalva/jwt-go" 6 | "io/ioutil" 7 | "time" 8 | ) 9 | 10 | // For HMAC signing method, the key can be any []byte. It is recommended to generate 11 | // a key using crypto/rand or something equivalent. You need the same key for signing 12 | // and validating. 13 | var hmacSampleSecret []byte 14 | 15 | func init() { 16 | // Load sample key data 17 | if keyData, e := ioutil.ReadFile("test/hmacTestKey"); e == nil { 18 | hmacSampleSecret = keyData 19 | } else { 20 | panic(e) 21 | } 22 | } 23 | 24 | // Example creating, signing, and encoding a JWT token using the HMAC signing method 25 | func ExampleNew_hmac() { 26 | // Create a new token object, specifying signing method and the claims 27 | // you would like it to contain. 28 | token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{ 29 | "foo": "bar", 30 | "nbf": time.Date(2015, 10, 10, 12, 0, 0, 0, time.UTC).Unix(), 31 | }) 32 | 33 | // Sign and get the complete encoded token as a string using the secret 34 | tokenString, err := token.SignedString(hmacSampleSecret) 35 | 36 | fmt.Println(tokenString, err) 37 | // Output: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIiLCJuYmYiOjE0NDQ0Nzg0MDB9.u1riaD1rW97opCoAuRCTy4w58Br-Zk-bh7vLiRIsrpU 38 | } 39 | 40 | // Example parsing and validating a token using the HMAC signing method 41 | func ExampleParse_hmac() { 42 | // sample token string taken from the New example 43 | tokenString := "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIiLCJuYmYiOjE0NDQ0Nzg0MDB9.u1riaD1rW97opCoAuRCTy4w58Br-Zk-bh7vLiRIsrpU" 44 | 45 | // Parse takes the token string and a function for looking up the key. The latter is especially 46 | // useful if you use multiple keys for your application. The standard is to use 'kid' in the 47 | // head of the token to identify which key to use, but the parsed token (head and claims) is provided 48 | // to the callback, providing flexibility. 49 | token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) { 50 | // Don't forget to validate the alg is what you expect: 51 | if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok { 52 | return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"]) 53 | } 54 | 55 | // hmacSampleSecret is a []byte containing your secret, e.g. []byte("my_secret_key") 56 | return hmacSampleSecret, nil 57 | }) 58 | 59 | if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid { 60 | fmt.Println(claims["foo"], claims["nbf"]) 61 | } else { 62 | fmt.Println(err) 63 | } 64 | 65 | // Output: bar 1.4444784e+09 66 | } 67 | -------------------------------------------------------------------------------- /hmac_test.go: -------------------------------------------------------------------------------- 1 | package jwt_test 2 | 3 | import ( 4 | "github.com/dgrijalva/jwt-go" 5 | "io/ioutil" 6 | "strings" 7 | "testing" 8 | ) 9 | 10 | var hmacTestData = []struct { 11 | name string 12 | tokenString string 13 | alg string 14 | claims map[string]interface{} 15 | valid bool 16 | }{ 17 | { 18 | "web sample", 19 | "eyJ0eXAiOiJKV1QiLA0KICJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJqb2UiLA0KICJleHAiOjEzMDA4MTkzODAsDQogImh0dHA6Ly9leGFtcGxlLmNvbS9pc19yb290Ijp0cnVlfQ.dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk", 20 | "HS256", 21 | map[string]interface{}{"iss": "joe", "exp": 1300819380, "http://example.com/is_root": true}, 22 | true, 23 | }, 24 | { 25 | "HS384", 26 | "eyJhbGciOiJIUzM4NCIsInR5cCI6IkpXVCJ9.eyJleHAiOjEuMzAwODE5MzhlKzA5LCJodHRwOi8vZXhhbXBsZS5jb20vaXNfcm9vdCI6dHJ1ZSwiaXNzIjoiam9lIn0.KWZEuOD5lbBxZ34g7F-SlVLAQ_r5KApWNWlZIIMyQVz5Zs58a7XdNzj5_0EcNoOy", 27 | "HS384", 28 | map[string]interface{}{"iss": "joe", "exp": 1300819380, "http://example.com/is_root": true}, 29 | true, 30 | }, 31 | { 32 | "HS512", 33 | "eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJleHAiOjEuMzAwODE5MzhlKzA5LCJodHRwOi8vZXhhbXBsZS5jb20vaXNfcm9vdCI6dHJ1ZSwiaXNzIjoiam9lIn0.CN7YijRX6Aw1n2jyI2Id1w90ja-DEMYiWixhYCyHnrZ1VfJRaFQz1bEbjjA5Fn4CLYaUG432dEYmSbS4Saokmw", 34 | "HS512", 35 | map[string]interface{}{"iss": "joe", "exp": 1300819380, "http://example.com/is_root": true}, 36 | true, 37 | }, 38 | { 39 | "web sample: invalid", 40 | "eyJ0eXAiOiJKV1QiLA0KICJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJqb2UiLA0KICJleHAiOjEzMDA4MTkzODAsDQogImh0dHA6Ly9leGFtcGxlLmNvbS9pc19yb290Ijp0cnVlfQ.dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXo", 41 | "HS256", 42 | map[string]interface{}{"iss": "joe", "exp": 1300819380, "http://example.com/is_root": true}, 43 | false, 44 | }, 45 | } 46 | 47 | // Sample data from http://tools.ietf.org/html/draft-jones-json-web-signature-04#appendix-A.1 48 | var hmacTestKey, _ = ioutil.ReadFile("test/hmacTestKey") 49 | 50 | func TestHMACVerify(t *testing.T) { 51 | for _, data := range hmacTestData { 52 | parts := strings.Split(data.tokenString, ".") 53 | 54 | method := jwt.GetSigningMethod(data.alg) 55 | err := method.Verify(strings.Join(parts[0:2], "."), parts[2], hmacTestKey) 56 | if data.valid && err != nil { 57 | t.Errorf("[%v] Error while verifying key: %v", data.name, err) 58 | } 59 | if !data.valid && err == nil { 60 | t.Errorf("[%v] Invalid key passed validation", data.name) 61 | } 62 | } 63 | } 64 | 65 | func TestHMACSign(t *testing.T) { 66 | for _, data := range hmacTestData { 67 | if data.valid { 68 | parts := strings.Split(data.tokenString, ".") 69 | method := jwt.GetSigningMethod(data.alg) 70 | sig, err := method.Sign(strings.Join(parts[0:2], "."), hmacTestKey) 71 | if err != nil { 72 | t.Errorf("[%v] Error signing token: %v", data.name, err) 73 | } 74 | if sig != parts[2] { 75 | t.Errorf("[%v] Incorrect signature.\nwas:\n%v\nexpecting:\n%v", data.name, sig, parts[2]) 76 | } 77 | } 78 | } 79 | } 80 | 81 | func BenchmarkHS256Signing(b *testing.B) { 82 | benchmarkSigning(b, jwt.SigningMethodHS256, hmacTestKey) 83 | } 84 | 85 | func BenchmarkHS384Signing(b *testing.B) { 86 | benchmarkSigning(b, jwt.SigningMethodHS384, hmacTestKey) 87 | } 88 | 89 | func BenchmarkHS512Signing(b *testing.B) { 90 | benchmarkSigning(b, jwt.SigningMethodHS512, hmacTestKey) 91 | } 92 | -------------------------------------------------------------------------------- /http_example_test.go: -------------------------------------------------------------------------------- 1 | package jwt_test 2 | 3 | // Example HTTP auth using asymmetric crypto/RSA keys 4 | // This is based on a (now outdated) example at https://gist.github.com/cryptix/45c33ecf0ae54828e63b 5 | 6 | import ( 7 | "bytes" 8 | "crypto/rsa" 9 | "fmt" 10 | "github.com/dgrijalva/jwt-go" 11 | "github.com/dgrijalva/jwt-go/request" 12 | "io" 13 | "io/ioutil" 14 | "log" 15 | "net" 16 | "net/http" 17 | "net/url" 18 | "strings" 19 | "time" 20 | ) 21 | 22 | // location of the files used for signing and verification 23 | const ( 24 | privKeyPath = "test/sample_key" // openssl genrsa -out app.rsa keysize 25 | pubKeyPath = "test/sample_key.pub" // openssl rsa -in app.rsa -pubout > app.rsa.pub 26 | ) 27 | 28 | var ( 29 | verifyKey *rsa.PublicKey 30 | signKey *rsa.PrivateKey 31 | serverPort int 32 | // storing sample username/password pairs 33 | // don't do this on a real server 34 | users = map[string]string{ 35 | "test": "known", 36 | } 37 | ) 38 | 39 | // read the key files before starting http handlers 40 | func init() { 41 | signBytes, err := ioutil.ReadFile(privKeyPath) 42 | fatal(err) 43 | 44 | signKey, err = jwt.ParseRSAPrivateKeyFromPEM(signBytes) 45 | fatal(err) 46 | 47 | verifyBytes, err := ioutil.ReadFile(pubKeyPath) 48 | fatal(err) 49 | 50 | verifyKey, err = jwt.ParseRSAPublicKeyFromPEM(verifyBytes) 51 | fatal(err) 52 | 53 | http.HandleFunc("/authenticate", authHandler) 54 | http.HandleFunc("/restricted", restrictedHandler) 55 | 56 | // Setup listener 57 | listener, err := net.ListenTCP("tcp", &net.TCPAddr{}) 58 | serverPort = listener.Addr().(*net.TCPAddr).Port 59 | 60 | log.Println("Listening...") 61 | go func() { 62 | fatal(http.Serve(listener, nil)) 63 | }() 64 | } 65 | 66 | var start func() 67 | 68 | func fatal(err error) { 69 | if err != nil { 70 | log.Fatal(err) 71 | } 72 | } 73 | 74 | // Define some custom types were going to use within our tokens 75 | type CustomerInfo struct { 76 | Name string 77 | Kind string 78 | } 79 | 80 | type CustomClaimsExample struct { 81 | *jwt.StandardClaims 82 | TokenType string 83 | CustomerInfo 84 | } 85 | 86 | func Example_getTokenViaHTTP() { 87 | // See func authHandler for an example auth handler that produces a token 88 | res, err := http.PostForm(fmt.Sprintf("http://localhost:%v/authenticate", serverPort), url.Values{ 89 | "user": {"test"}, 90 | "pass": {"known"}, 91 | }) 92 | if err != nil { 93 | fatal(err) 94 | } 95 | 96 | if res.StatusCode != 200 { 97 | fmt.Println("Unexpected status code", res.StatusCode) 98 | } 99 | 100 | // Read the token out of the response body 101 | buf := new(bytes.Buffer) 102 | io.Copy(buf, res.Body) 103 | res.Body.Close() 104 | tokenString := strings.TrimSpace(buf.String()) 105 | 106 | // Parse the token 107 | token, err := jwt.ParseWithClaims(tokenString, &CustomClaimsExample{}, func(token *jwt.Token) (interface{}, error) { 108 | // since we only use the one private key to sign the tokens, 109 | // we also only use its public counter part to verify 110 | return verifyKey, nil 111 | }) 112 | fatal(err) 113 | 114 | claims := token.Claims.(*CustomClaimsExample) 115 | fmt.Println(claims.CustomerInfo.Name) 116 | 117 | //Output: test 118 | } 119 | 120 | func Example_useTokenViaHTTP() { 121 | 122 | // Make a sample token 123 | // In a real world situation, this token will have been acquired from 124 | // some other API call (see Example_getTokenViaHTTP) 125 | token, err := createToken("foo") 126 | fatal(err) 127 | 128 | // Make request. See func restrictedHandler for example request processor 129 | req, err := http.NewRequest("GET", fmt.Sprintf("http://localhost:%v/restricted", serverPort), nil) 130 | fatal(err) 131 | req.Header.Set("Authorization", fmt.Sprintf("Bearer %v", token)) 132 | res, err := http.DefaultClient.Do(req) 133 | fatal(err) 134 | 135 | // Read the response body 136 | buf := new(bytes.Buffer) 137 | io.Copy(buf, res.Body) 138 | res.Body.Close() 139 | fmt.Println(buf.String()) 140 | 141 | // Output: Welcome, foo 142 | } 143 | 144 | func createToken(user string) (string, error) { 145 | // create a signer for rsa 256 146 | t := jwt.New(jwt.GetSigningMethod("RS256")) 147 | 148 | // set our claims 149 | t.Claims = &CustomClaimsExample{ 150 | &jwt.StandardClaims{ 151 | // set the expire time 152 | // see http://tools.ietf.org/html/draft-ietf-oauth-json-web-token-20#section-4.1.4 153 | ExpiresAt: time.Now().Add(time.Minute * 1).Unix(), 154 | }, 155 | "level1", 156 | CustomerInfo{user, "human"}, 157 | } 158 | 159 | // Creat token string 160 | return t.SignedString(signKey) 161 | } 162 | 163 | // reads the form values, checks them and creates the token 164 | func authHandler(w http.ResponseWriter, r *http.Request) { 165 | // make sure its post 166 | if r.Method != "POST" { 167 | w.WriteHeader(http.StatusBadRequest) 168 | fmt.Fprintln(w, "No POST", r.Method) 169 | return 170 | } 171 | 172 | user := r.FormValue("user") 173 | pass := r.FormValue("pass") 174 | 175 | log.Printf("Authenticate: user[%s] pass[%s]\n", user, pass) 176 | 177 | // check values 178 | if user != "test" || pass != "known" { 179 | w.WriteHeader(http.StatusForbidden) 180 | fmt.Fprintln(w, "Wrong info") 181 | return 182 | } 183 | 184 | tokenString, err := createToken(user) 185 | if err != nil { 186 | w.WriteHeader(http.StatusInternalServerError) 187 | fmt.Fprintln(w, "Sorry, error while Signing Token!") 188 | log.Printf("Token Signing error: %v\n", err) 189 | return 190 | } 191 | 192 | w.Header().Set("Content-Type", "application/jwt") 193 | w.WriteHeader(http.StatusOK) 194 | fmt.Fprintln(w, tokenString) 195 | } 196 | 197 | // only accessible with a valid token 198 | func restrictedHandler(w http.ResponseWriter, r *http.Request) { 199 | // Get token from request 200 | token, err := request.ParseFromRequestWithClaims(r, request.OAuth2Extractor, &CustomClaimsExample{}, func(token *jwt.Token) (interface{}, error) { 201 | // since we only use the one private key to sign the tokens, 202 | // we also only use its public counter part to verify 203 | return verifyKey, nil 204 | }) 205 | 206 | // If the token is missing or invalid, return error 207 | if err != nil { 208 | w.WriteHeader(http.StatusUnauthorized) 209 | fmt.Fprintln(w, "Invalid token:", err) 210 | return 211 | } 212 | 213 | // Token is valid 214 | fmt.Fprintln(w, "Welcome,", token.Claims.(*CustomClaimsExample).Name) 215 | return 216 | } 217 | -------------------------------------------------------------------------------- /map_claims.go: -------------------------------------------------------------------------------- 1 | package jwt 2 | 3 | import ( 4 | "encoding/json" 5 | "errors" 6 | // "fmt" 7 | ) 8 | 9 | // Claims type that uses the map[string]interface{} for JSON decoding 10 | // This is the default claims type if you don't supply one 11 | type MapClaims map[string]interface{} 12 | 13 | // VerifyAudience Compares the aud claim against cmp. 14 | // If required is false, this method will return true if the value matches or is unset 15 | func (m MapClaims) VerifyAudience(cmp string, req bool) bool { 16 | var aud []string 17 | switch v := m["aud"].(type) { 18 | case string: 19 | aud = append(aud, v) 20 | case []string: 21 | aud = v 22 | case []interface{}: 23 | for _, a := range v { 24 | vs, ok := a.(string) 25 | if !ok { 26 | return false 27 | } 28 | aud = append(aud, vs) 29 | } 30 | } 31 | return verifyAud(aud, cmp, req) 32 | } 33 | 34 | // Compares the exp claim against cmp. 35 | // If required is false, this method will return true if the value matches or is unset 36 | func (m MapClaims) VerifyExpiresAt(cmp int64, req bool) bool { 37 | switch exp := m["exp"].(type) { 38 | case float64: 39 | return verifyExp(int64(exp), cmp, req) 40 | case json.Number: 41 | v, _ := exp.Int64() 42 | return verifyExp(v, cmp, req) 43 | } 44 | return req == false 45 | } 46 | 47 | // Compares the iat claim against cmp. 48 | // If required is false, this method will return true if the value matches or is unset 49 | func (m MapClaims) VerifyIssuedAt(cmp int64, req bool) bool { 50 | switch iat := m["iat"].(type) { 51 | case float64: 52 | return verifyIat(int64(iat), cmp, req) 53 | case json.Number: 54 | v, _ := iat.Int64() 55 | return verifyIat(v, cmp, req) 56 | } 57 | return req == false 58 | } 59 | 60 | // Compares the iss claim against cmp. 61 | // If required is false, this method will return true if the value matches or is unset 62 | func (m MapClaims) VerifyIssuer(cmp string, req bool) bool { 63 | iss, _ := m["iss"].(string) 64 | return verifyIss(iss, cmp, req) 65 | } 66 | 67 | // Compares the nbf claim against cmp. 68 | // If required is false, this method will return true if the value matches or is unset 69 | func (m MapClaims) VerifyNotBefore(cmp int64, req bool) bool { 70 | switch nbf := m["nbf"].(type) { 71 | case float64: 72 | return verifyNbf(int64(nbf), cmp, req) 73 | case json.Number: 74 | v, _ := nbf.Int64() 75 | return verifyNbf(v, cmp, req) 76 | } 77 | return req == false 78 | } 79 | 80 | // Validates time based claims "exp, iat, nbf". 81 | // There is no accounting for clock skew. 82 | // As well, if any of the above claims are not in the token, it will still 83 | // be considered a valid claim. 84 | func (m MapClaims) Valid() error { 85 | vErr := new(ValidationError) 86 | now := TimeFunc().Unix() 87 | 88 | if m.VerifyExpiresAt(now, false) == false { 89 | vErr.Inner = errors.New("Token is expired") 90 | vErr.Errors |= ValidationErrorExpired 91 | } 92 | 93 | if m.VerifyIssuedAt(now, false) == false { 94 | vErr.Inner = errors.New("Token used before issued") 95 | vErr.Errors |= ValidationErrorIssuedAt 96 | } 97 | 98 | if m.VerifyNotBefore(now, false) == false { 99 | vErr.Inner = errors.New("Token is not valid yet") 100 | vErr.Errors |= ValidationErrorNotValidYet 101 | } 102 | 103 | if vErr.valid() { 104 | return nil 105 | } 106 | 107 | return vErr 108 | } 109 | -------------------------------------------------------------------------------- /map_claims_test.go: -------------------------------------------------------------------------------- 1 | package jwt 2 | 3 | import ( 4 | "testing" 5 | ) 6 | 7 | func TestVerifyAud(t *testing.T) { 8 | var nilInterface interface{} 9 | var nilListInterface []interface{} 10 | var intListInterface interface{} = []int{1,2,3} 11 | type test struct{ 12 | Name string 13 | MapClaims MapClaims 14 | Expected bool 15 | Comparison string 16 | Required bool 17 | } 18 | tests := []test{ 19 | // Matching Claim in aud 20 | // Required = true 21 | { Name: "String Aud matching required", MapClaims: MapClaims{"aud": "example.com"}, Expected: true , Required: true, Comparison: "example.com"}, 22 | { Name: "[]String Aud with match required", MapClaims: MapClaims{"aud": []string{"example.com", "example.example.com"}}, Expected: true, Required: true, Comparison: "example.com"}, 23 | 24 | // Required = false 25 | { Name: "String Aud with match not required", MapClaims: MapClaims{"aud": "example.com"}, Expected: true , Required: false, Comparison: "example.com"}, 26 | { Name: "Empty String Aud with match not required", MapClaims: MapClaims{}, Expected: true , Required: false, Comparison: "example.com"}, 27 | { Name: "Empty String Aud with match not required", MapClaims: MapClaims{"aud": ""}, Expected: true , Required: false, Comparison: "example.com"}, 28 | { Name: "Nil String Aud with match not required", MapClaims: MapClaims{"aud": nil}, Expected: true , Required: false, Comparison: "example.com"}, 29 | 30 | { Name: "[]String Aud with match not required", MapClaims: MapClaims{"aud": []string{"example.com", "example.example.com"}}, Expected: true, Required: false, Comparison: "example.com"}, 31 | { Name: "Empty []String Aud with match not required", MapClaims: MapClaims{"aud": []string{}}, Expected: true, Required: false, Comparison: "example.com"}, 32 | 33 | // Non-Matching Claim in aud 34 | // Required = true 35 | { Name: "String Aud without match required", MapClaims: MapClaims{"aud": "not.example.com"}, Expected: false, Required: true, Comparison: "example.com"}, 36 | { Name: "Empty String Aud without match required", MapClaims: MapClaims{"aud": ""}, Expected: false, Required: true, Comparison: "example.com"}, 37 | { Name: "[]String Aud without match required", MapClaims: MapClaims{"aud": []string{"not.example.com", "example.example.com"}}, Expected: false, Required: true, Comparison: "example.com"}, 38 | { Name: "Empty []String Aud without match required", MapClaims: MapClaims{"aud": []string{""}}, Expected: false, Required: true, Comparison: "example.com"}, 39 | { Name: "String Aud without match not required", MapClaims: MapClaims{"aud": "not.example.com"}, Expected: false, Required: true, Comparison: "example.com"}, 40 | { Name: "Empty String Aud without match not required", MapClaims: MapClaims{"aud": ""}, Expected: false, Required: true, Comparison: "example.com"}, 41 | { Name: "[]String Aud without match not required", MapClaims: MapClaims{"aud": []string{"not.example.com", "example.example.com"}}, Expected: false, Required: true, Comparison: "example.com"}, 42 | 43 | // Required = false 44 | { Name: "Empty []String Aud without match required", MapClaims: MapClaims{"aud": []string{""}}, Expected: false, Required: true, Comparison: "example.com"}, 45 | 46 | // []interface{} 47 | { Name: "Empty []interface{} Aud without match required", MapClaims: MapClaims{"aud": nilListInterface}, Expected: true, Required: false, Comparison: "example.com"}, 48 | { Name: "[]interface{} Aud wit match required", MapClaims: MapClaims{"aud": []interface{}{"a", "foo", "example.com"}}, Expected: true, Required: true, Comparison: "example.com"}, 49 | { Name: "[]interface{} Aud wit match but invalid types", MapClaims: MapClaims{"aud": []interface{}{"a", 5, "example.com"}}, Expected: false, Required: true, Comparison: "example.com"}, 50 | { Name: "[]interface{} Aud int wit match required", MapClaims: MapClaims{"aud": intListInterface}, Expected: false, Required: true, Comparison: "example.com"}, 51 | 52 | 53 | // interface{} 54 | { Name: "Empty interface{} Aud without match not required", MapClaims: MapClaims{"aud": nilInterface}, Expected: true, Required: false, Comparison: "example.com"}, 55 | 56 | } 57 | 58 | 59 | for _, test := range tests { 60 | t.Run(test.Name, func(t *testing.T) { 61 | got := test.MapClaims.VerifyAudience(test.Comparison, test.Required) 62 | 63 | if got != test.Expected { 64 | t.Errorf("Expected %v, got %v", test.Expected, got) 65 | } 66 | }) 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /none.go: -------------------------------------------------------------------------------- 1 | package jwt 2 | 3 | // Implements the none signing method. This is required by the spec 4 | // but you probably should never use it. 5 | var SigningMethodNone *signingMethodNone 6 | 7 | const UnsafeAllowNoneSignatureType unsafeNoneMagicConstant = "none signing method allowed" 8 | 9 | var NoneSignatureTypeDisallowedError error 10 | 11 | type signingMethodNone struct{} 12 | type unsafeNoneMagicConstant string 13 | 14 | func init() { 15 | SigningMethodNone = &signingMethodNone{} 16 | NoneSignatureTypeDisallowedError = NewValidationError("'none' signature type is not allowed", ValidationErrorSignatureInvalid) 17 | 18 | RegisterSigningMethod(SigningMethodNone.Alg(), func() SigningMethod { 19 | return SigningMethodNone 20 | }) 21 | } 22 | 23 | func (m *signingMethodNone) Alg() string { 24 | return "none" 25 | } 26 | 27 | // Only allow 'none' alg type if UnsafeAllowNoneSignatureType is specified as the key 28 | func (m *signingMethodNone) Verify(signingString, signature string, key interface{}) (err error) { 29 | // Key must be UnsafeAllowNoneSignatureType to prevent accidentally 30 | // accepting 'none' signing method 31 | if _, ok := key.(unsafeNoneMagicConstant); !ok { 32 | return NoneSignatureTypeDisallowedError 33 | } 34 | // If signing method is none, signature must be an empty string 35 | if signature != "" { 36 | return NewValidationError( 37 | "'none' signing method with non-empty signature", 38 | ValidationErrorSignatureInvalid, 39 | ) 40 | } 41 | 42 | // Accept 'none' signing method. 43 | return nil 44 | } 45 | 46 | // Only allow 'none' signing if UnsafeAllowNoneSignatureType is specified as the key 47 | func (m *signingMethodNone) Sign(signingString string, key interface{}) (string, error) { 48 | if _, ok := key.(unsafeNoneMagicConstant); ok { 49 | return "", nil 50 | } 51 | return "", NoneSignatureTypeDisallowedError 52 | } 53 | -------------------------------------------------------------------------------- /none_test.go: -------------------------------------------------------------------------------- 1 | package jwt_test 2 | 3 | import ( 4 | "github.com/dgrijalva/jwt-go" 5 | "strings" 6 | "testing" 7 | ) 8 | 9 | var noneTestData = []struct { 10 | name string 11 | tokenString string 12 | alg string 13 | key interface{} 14 | claims map[string]interface{} 15 | valid bool 16 | }{ 17 | { 18 | "Basic", 19 | "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJmb28iOiJiYXIifQ.", 20 | "none", 21 | jwt.UnsafeAllowNoneSignatureType, 22 | map[string]interface{}{"foo": "bar"}, 23 | true, 24 | }, 25 | { 26 | "Basic - no key", 27 | "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJmb28iOiJiYXIifQ.", 28 | "none", 29 | nil, 30 | map[string]interface{}{"foo": "bar"}, 31 | false, 32 | }, 33 | { 34 | "Signed", 35 | "eyJhbGciOiJSUzM4NCIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIifQ.W-jEzRfBigtCWsinvVVuldiuilzVdU5ty0MvpLaSaqK9PlAWWlDQ1VIQ_qSKzwL5IXaZkvZFJXT3yL3n7OUVu7zCNJzdwznbC8Z-b0z2lYvcklJYi2VOFRcGbJtXUqgjk2oGsiqUMUMOLP70TTefkpsgqDxbRh9CDUfpOJgW-dU7cmgaoswe3wjUAUi6B6G2YEaiuXC0XScQYSYVKIzgKXJV8Zw-7AN_DBUI4GkTpsvQ9fVVjZM9csQiEXhYekyrKu1nu_POpQonGd8yqkIyXPECNmmqH5jH4sFiF67XhD7_JpkvLziBpI-uh86evBUadmHhb9Otqw3uV3NTaXLzJw", 36 | "none", 37 | jwt.UnsafeAllowNoneSignatureType, 38 | map[string]interface{}{"foo": "bar"}, 39 | false, 40 | }, 41 | } 42 | 43 | func TestNoneVerify(t *testing.T) { 44 | for _, data := range noneTestData { 45 | parts := strings.Split(data.tokenString, ".") 46 | 47 | method := jwt.GetSigningMethod(data.alg) 48 | err := method.Verify(strings.Join(parts[0:2], "."), parts[2], data.key) 49 | if data.valid && err != nil { 50 | t.Errorf("[%v] Error while verifying key: %v", data.name, err) 51 | } 52 | if !data.valid && err == nil { 53 | t.Errorf("[%v] Invalid key passed validation", data.name) 54 | } 55 | } 56 | } 57 | 58 | func TestNoneSign(t *testing.T) { 59 | for _, data := range noneTestData { 60 | if data.valid { 61 | parts := strings.Split(data.tokenString, ".") 62 | method := jwt.GetSigningMethod(data.alg) 63 | sig, err := method.Sign(strings.Join(parts[0:2], "."), data.key) 64 | if err != nil { 65 | t.Errorf("[%v] Error signing token: %v", data.name, err) 66 | } 67 | if sig != parts[2] { 68 | t.Errorf("[%v] Incorrect signature.\nwas:\n%v\nexpecting:\n%v", data.name, sig, parts[2]) 69 | } 70 | } 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /parser.go: -------------------------------------------------------------------------------- 1 | package jwt 2 | 3 | import ( 4 | "bytes" 5 | "encoding/json" 6 | "fmt" 7 | "strings" 8 | ) 9 | 10 | type Parser struct { 11 | ValidMethods []string // If populated, only these methods will be considered valid 12 | UseJSONNumber bool // Use JSON Number format in JSON decoder 13 | SkipClaimsValidation bool // Skip claims validation during token parsing 14 | } 15 | 16 | // Parse, validate, and return a token. 17 | // keyFunc will receive the parsed token and should return the key for validating. 18 | // If everything is kosher, err will be nil 19 | func (p *Parser) Parse(tokenString string, keyFunc Keyfunc) (*Token, error) { 20 | return p.ParseWithClaims(tokenString, MapClaims{}, keyFunc) 21 | } 22 | 23 | func (p *Parser) ParseWithClaims(tokenString string, claims Claims, keyFunc Keyfunc) (*Token, error) { 24 | token, parts, err := p.ParseUnverified(tokenString, claims) 25 | if err != nil { 26 | return token, err 27 | } 28 | 29 | // Verify signing method is in the required set 30 | if p.ValidMethods != nil { 31 | var signingMethodValid = false 32 | var alg = token.Method.Alg() 33 | for _, m := range p.ValidMethods { 34 | if m == alg { 35 | signingMethodValid = true 36 | break 37 | } 38 | } 39 | if !signingMethodValid { 40 | // signing method is not in the listed set 41 | return token, NewValidationError(fmt.Sprintf("signing method %v is invalid", alg), ValidationErrorSignatureInvalid) 42 | } 43 | } 44 | 45 | // Lookup key 46 | var key interface{} 47 | if keyFunc == nil { 48 | // keyFunc was not provided. short circuiting validation 49 | return token, NewValidationError("no Keyfunc was provided.", ValidationErrorUnverifiable) 50 | } 51 | if key, err = keyFunc(token); err != nil { 52 | // keyFunc returned an error 53 | if ve, ok := err.(*ValidationError); ok { 54 | return token, ve 55 | } 56 | return token, &ValidationError{Inner: err, Errors: ValidationErrorUnverifiable} 57 | } 58 | 59 | vErr := &ValidationError{} 60 | 61 | // Validate Claims 62 | if !p.SkipClaimsValidation { 63 | if err := token.Claims.Valid(); err != nil { 64 | 65 | // If the Claims Valid returned an error, check if it is a validation error, 66 | // If it was another error type, create a ValidationError with a generic ClaimsInvalid flag set 67 | if e, ok := err.(*ValidationError); !ok { 68 | vErr = &ValidationError{Inner: err, Errors: ValidationErrorClaimsInvalid} 69 | } else { 70 | vErr = e 71 | } 72 | } 73 | } 74 | 75 | // Perform validation 76 | token.Signature = parts[2] 77 | if err = token.Method.Verify(strings.Join(parts[0:2], "."), token.Signature, key); err != nil { 78 | vErr.Inner = err 79 | vErr.Errors |= ValidationErrorSignatureInvalid 80 | } 81 | 82 | if vErr.valid() { 83 | token.Valid = true 84 | return token, nil 85 | } 86 | 87 | return token, vErr 88 | } 89 | 90 | // WARNING: Don't use this method unless you know what you're doing 91 | // 92 | // This method parses the token but doesn't validate the signature. It's only 93 | // ever useful in cases where you know the signature is valid (because it has 94 | // been checked previously in the stack) and you want to extract values from 95 | // it. 96 | func (p *Parser) ParseUnverified(tokenString string, claims Claims) (token *Token, parts []string, err error) { 97 | parts = strings.Split(tokenString, ".") 98 | if len(parts) != 3 { 99 | return nil, parts, NewValidationError("token contains an invalid number of segments", ValidationErrorMalformed) 100 | } 101 | 102 | token = &Token{Raw: tokenString} 103 | 104 | // parse Header 105 | var headerBytes []byte 106 | if headerBytes, err = DecodeSegment(parts[0]); err != nil { 107 | if strings.HasPrefix(strings.ToLower(tokenString), "bearer ") { 108 | return token, parts, NewValidationError("tokenstring should not contain 'bearer '", ValidationErrorMalformed) 109 | } 110 | return token, parts, &ValidationError{Inner: err, Errors: ValidationErrorMalformed} 111 | } 112 | if err = json.Unmarshal(headerBytes, &token.Header); err != nil { 113 | return token, parts, &ValidationError{Inner: err, Errors: ValidationErrorMalformed} 114 | } 115 | 116 | // parse Claims 117 | var claimBytes []byte 118 | token.Claims = claims 119 | 120 | if claimBytes, err = DecodeSegment(parts[1]); err != nil { 121 | return token, parts, &ValidationError{Inner: err, Errors: ValidationErrorMalformed} 122 | } 123 | dec := json.NewDecoder(bytes.NewBuffer(claimBytes)) 124 | if p.UseJSONNumber { 125 | dec.UseNumber() 126 | } 127 | // JSON Decode. Special case for map type to avoid weird pointer behavior 128 | if c, ok := token.Claims.(MapClaims); ok { 129 | err = dec.Decode(&c) 130 | } else { 131 | err = dec.Decode(&claims) 132 | } 133 | // Handle decode error 134 | if err != nil { 135 | return token, parts, &ValidationError{Inner: err, Errors: ValidationErrorMalformed} 136 | } 137 | 138 | // Lookup signature method 139 | if method, ok := token.Header["alg"].(string); ok { 140 | if token.Method = GetSigningMethod(method); token.Method == nil { 141 | return token, parts, NewValidationError("signing method (alg) is unavailable.", ValidationErrorUnverifiable) 142 | } 143 | } else { 144 | return token, parts, NewValidationError("signing method (alg) is unspecified.", ValidationErrorUnverifiable) 145 | } 146 | 147 | return token, parts, nil 148 | } 149 | -------------------------------------------------------------------------------- /parser_test.go: -------------------------------------------------------------------------------- 1 | package jwt_test 2 | 3 | import ( 4 | "crypto/rsa" 5 | "encoding/json" 6 | "fmt" 7 | "reflect" 8 | "testing" 9 | "time" 10 | 11 | "github.com/dgrijalva/jwt-go" 12 | "github.com/dgrijalva/jwt-go/test" 13 | ) 14 | 15 | var keyFuncError error = fmt.Errorf("error loading key") 16 | 17 | var ( 18 | jwtTestDefaultKey *rsa.PublicKey 19 | defaultKeyFunc jwt.Keyfunc = func(t *jwt.Token) (interface{}, error) { return jwtTestDefaultKey, nil } 20 | emptyKeyFunc jwt.Keyfunc = func(t *jwt.Token) (interface{}, error) { return nil, nil } 21 | errorKeyFunc jwt.Keyfunc = func(t *jwt.Token) (interface{}, error) { return nil, keyFuncError } 22 | nilKeyFunc jwt.Keyfunc = nil 23 | ) 24 | 25 | func init() { 26 | jwtTestDefaultKey = test.LoadRSAPublicKeyFromDisk("test/sample_key.pub") 27 | } 28 | 29 | var jwtTestData = []struct { 30 | name string 31 | tokenString string 32 | keyfunc jwt.Keyfunc 33 | claims jwt.Claims 34 | valid bool 35 | errors uint32 36 | parser *jwt.Parser 37 | }{ 38 | { 39 | "basic", 40 | "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJmb28iOiJiYXIifQ.FhkiHkoESI_cG3NPigFrxEk9Z60_oXrOT2vGm9Pn6RDgYNovYORQmmA0zs1AoAOf09ly2Nx2YAg6ABqAYga1AcMFkJljwxTT5fYphTuqpWdy4BELeSYJx5Ty2gmr8e7RonuUztrdD5WfPqLKMm1Ozp_T6zALpRmwTIW0QPnaBXaQD90FplAg46Iy1UlDKr-Eupy0i5SLch5Q-p2ZpaL_5fnTIUDlxC3pWhJTyx_71qDI-mAA_5lE_VdroOeflG56sSmDxopPEG3bFlSu1eowyBfxtu0_CuVd-M42RU75Zc4Gsj6uV77MBtbMrf4_7M_NUTSgoIF3fRqxrj0NzihIBg", 41 | defaultKeyFunc, 42 | jwt.MapClaims{"foo": "bar"}, 43 | true, 44 | 0, 45 | nil, 46 | }, 47 | { 48 | "basic expired", 49 | "", // autogen 50 | defaultKeyFunc, 51 | jwt.MapClaims{"foo": "bar", "exp": float64(time.Now().Unix() - 100)}, 52 | false, 53 | jwt.ValidationErrorExpired, 54 | nil, 55 | }, 56 | { 57 | "basic nbf", 58 | "", // autogen 59 | defaultKeyFunc, 60 | jwt.MapClaims{"foo": "bar", "nbf": float64(time.Now().Unix() + 100)}, 61 | false, 62 | jwt.ValidationErrorNotValidYet, 63 | nil, 64 | }, 65 | { 66 | "expired and nbf", 67 | "", // autogen 68 | defaultKeyFunc, 69 | jwt.MapClaims{"foo": "bar", "nbf": float64(time.Now().Unix() + 100), "exp": float64(time.Now().Unix() - 100)}, 70 | false, 71 | jwt.ValidationErrorNotValidYet | jwt.ValidationErrorExpired, 72 | nil, 73 | }, 74 | { 75 | "basic invalid", 76 | "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJmb28iOiJiYXIifQ.EhkiHkoESI_cG3NPigFrxEk9Z60_oXrOT2vGm9Pn6RDgYNovYORQmmA0zs1AoAOf09ly2Nx2YAg6ABqAYga1AcMFkJljwxTT5fYphTuqpWdy4BELeSYJx5Ty2gmr8e7RonuUztrdD5WfPqLKMm1Ozp_T6zALpRmwTIW0QPnaBXaQD90FplAg46Iy1UlDKr-Eupy0i5SLch5Q-p2ZpaL_5fnTIUDlxC3pWhJTyx_71qDI-mAA_5lE_VdroOeflG56sSmDxopPEG3bFlSu1eowyBfxtu0_CuVd-M42RU75Zc4Gsj6uV77MBtbMrf4_7M_NUTSgoIF3fRqxrj0NzihIBg", 77 | defaultKeyFunc, 78 | jwt.MapClaims{"foo": "bar"}, 79 | false, 80 | jwt.ValidationErrorSignatureInvalid, 81 | nil, 82 | }, 83 | { 84 | "basic nokeyfunc", 85 | "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJmb28iOiJiYXIifQ.FhkiHkoESI_cG3NPigFrxEk9Z60_oXrOT2vGm9Pn6RDgYNovYORQmmA0zs1AoAOf09ly2Nx2YAg6ABqAYga1AcMFkJljwxTT5fYphTuqpWdy4BELeSYJx5Ty2gmr8e7RonuUztrdD5WfPqLKMm1Ozp_T6zALpRmwTIW0QPnaBXaQD90FplAg46Iy1UlDKr-Eupy0i5SLch5Q-p2ZpaL_5fnTIUDlxC3pWhJTyx_71qDI-mAA_5lE_VdroOeflG56sSmDxopPEG3bFlSu1eowyBfxtu0_CuVd-M42RU75Zc4Gsj6uV77MBtbMrf4_7M_NUTSgoIF3fRqxrj0NzihIBg", 86 | nilKeyFunc, 87 | jwt.MapClaims{"foo": "bar"}, 88 | false, 89 | jwt.ValidationErrorUnverifiable, 90 | nil, 91 | }, 92 | { 93 | "basic nokey", 94 | "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJmb28iOiJiYXIifQ.FhkiHkoESI_cG3NPigFrxEk9Z60_oXrOT2vGm9Pn6RDgYNovYORQmmA0zs1AoAOf09ly2Nx2YAg6ABqAYga1AcMFkJljwxTT5fYphTuqpWdy4BELeSYJx5Ty2gmr8e7RonuUztrdD5WfPqLKMm1Ozp_T6zALpRmwTIW0QPnaBXaQD90FplAg46Iy1UlDKr-Eupy0i5SLch5Q-p2ZpaL_5fnTIUDlxC3pWhJTyx_71qDI-mAA_5lE_VdroOeflG56sSmDxopPEG3bFlSu1eowyBfxtu0_CuVd-M42RU75Zc4Gsj6uV77MBtbMrf4_7M_NUTSgoIF3fRqxrj0NzihIBg", 95 | emptyKeyFunc, 96 | jwt.MapClaims{"foo": "bar"}, 97 | false, 98 | jwt.ValidationErrorSignatureInvalid, 99 | nil, 100 | }, 101 | { 102 | "basic errorkey", 103 | "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJmb28iOiJiYXIifQ.FhkiHkoESI_cG3NPigFrxEk9Z60_oXrOT2vGm9Pn6RDgYNovYORQmmA0zs1AoAOf09ly2Nx2YAg6ABqAYga1AcMFkJljwxTT5fYphTuqpWdy4BELeSYJx5Ty2gmr8e7RonuUztrdD5WfPqLKMm1Ozp_T6zALpRmwTIW0QPnaBXaQD90FplAg46Iy1UlDKr-Eupy0i5SLch5Q-p2ZpaL_5fnTIUDlxC3pWhJTyx_71qDI-mAA_5lE_VdroOeflG56sSmDxopPEG3bFlSu1eowyBfxtu0_CuVd-M42RU75Zc4Gsj6uV77MBtbMrf4_7M_NUTSgoIF3fRqxrj0NzihIBg", 104 | errorKeyFunc, 105 | jwt.MapClaims{"foo": "bar"}, 106 | false, 107 | jwt.ValidationErrorUnverifiable, 108 | nil, 109 | }, 110 | { 111 | "invalid signing method", 112 | "", 113 | defaultKeyFunc, 114 | jwt.MapClaims{"foo": "bar"}, 115 | false, 116 | jwt.ValidationErrorSignatureInvalid, 117 | &jwt.Parser{ValidMethods: []string{"HS256"}}, 118 | }, 119 | { 120 | "valid signing method", 121 | "", 122 | defaultKeyFunc, 123 | jwt.MapClaims{"foo": "bar"}, 124 | true, 125 | 0, 126 | &jwt.Parser{ValidMethods: []string{"RS256", "HS256"}}, 127 | }, 128 | { 129 | "JSON Number", 130 | "", 131 | defaultKeyFunc, 132 | jwt.MapClaims{"foo": json.Number("123.4")}, 133 | true, 134 | 0, 135 | &jwt.Parser{UseJSONNumber: true}, 136 | }, 137 | { 138 | "Standard Claims", 139 | "", 140 | defaultKeyFunc, 141 | &jwt.StandardClaims{ 142 | ExpiresAt: time.Now().Add(time.Second * 10).Unix(), 143 | }, 144 | true, 145 | 0, 146 | &jwt.Parser{UseJSONNumber: true}, 147 | }, 148 | { 149 | "JSON Number - basic expired", 150 | "", // autogen 151 | defaultKeyFunc, 152 | jwt.MapClaims{"foo": "bar", "exp": json.Number(fmt.Sprintf("%v", time.Now().Unix()-100))}, 153 | false, 154 | jwt.ValidationErrorExpired, 155 | &jwt.Parser{UseJSONNumber: true}, 156 | }, 157 | { 158 | "JSON Number - basic nbf", 159 | "", // autogen 160 | defaultKeyFunc, 161 | jwt.MapClaims{"foo": "bar", "nbf": json.Number(fmt.Sprintf("%v", time.Now().Unix()+100))}, 162 | false, 163 | jwt.ValidationErrorNotValidYet, 164 | &jwt.Parser{UseJSONNumber: true}, 165 | }, 166 | { 167 | "JSON Number - expired and nbf", 168 | "", // autogen 169 | defaultKeyFunc, 170 | jwt.MapClaims{"foo": "bar", "nbf": json.Number(fmt.Sprintf("%v", time.Now().Unix()+100)), "exp": json.Number(fmt.Sprintf("%v", time.Now().Unix()-100))}, 171 | false, 172 | jwt.ValidationErrorNotValidYet | jwt.ValidationErrorExpired, 173 | &jwt.Parser{UseJSONNumber: true}, 174 | }, 175 | { 176 | "SkipClaimsValidation during token parsing", 177 | "", // autogen 178 | defaultKeyFunc, 179 | jwt.MapClaims{"foo": "bar", "nbf": json.Number(fmt.Sprintf("%v", time.Now().Unix()+100))}, 180 | true, 181 | 0, 182 | &jwt.Parser{UseJSONNumber: true, SkipClaimsValidation: true}, 183 | }, 184 | } 185 | 186 | func TestParser_Parse(t *testing.T) { 187 | privateKey := test.LoadRSAPrivateKeyFromDisk("test/sample_key") 188 | 189 | // Iterate over test data set and run tests 190 | for _, data := range jwtTestData { 191 | // If the token string is blank, use helper function to generate string 192 | if data.tokenString == "" { 193 | data.tokenString = test.MakeSampleToken(data.claims, privateKey) 194 | } 195 | 196 | // Parse the token 197 | var token *jwt.Token 198 | var err error 199 | var parser = data.parser 200 | if parser == nil { 201 | parser = new(jwt.Parser) 202 | } 203 | // Figure out correct claims type 204 | switch data.claims.(type) { 205 | case jwt.MapClaims: 206 | token, err = parser.ParseWithClaims(data.tokenString, jwt.MapClaims{}, data.keyfunc) 207 | case *jwt.StandardClaims: 208 | token, err = parser.ParseWithClaims(data.tokenString, &jwt.StandardClaims{}, data.keyfunc) 209 | } 210 | 211 | // Verify result matches expectation 212 | if !reflect.DeepEqual(data.claims, token.Claims) { 213 | t.Errorf("[%v] Claims mismatch. Expecting: %v Got: %v", data.name, data.claims, token.Claims) 214 | } 215 | 216 | if data.valid && err != nil { 217 | t.Errorf("[%v] Error while verifying token: %T:%v", data.name, err, err) 218 | } 219 | 220 | if !data.valid && err == nil { 221 | t.Errorf("[%v] Invalid token passed validation", data.name) 222 | } 223 | 224 | if (err == nil && !token.Valid) || (err != nil && token.Valid) { 225 | t.Errorf("[%v] Inconsistent behavior between returned error and token.Valid", data.name) 226 | } 227 | 228 | if data.errors != 0 { 229 | if err == nil { 230 | t.Errorf("[%v] Expecting error. Didn't get one.", data.name) 231 | } else { 232 | 233 | ve := err.(*jwt.ValidationError) 234 | // compare the bitfield part of the error 235 | if e := ve.Errors; e != data.errors { 236 | t.Errorf("[%v] Errors don't match expectation. %v != %v", data.name, e, data.errors) 237 | } 238 | 239 | if err.Error() == keyFuncError.Error() && ve.Inner != keyFuncError { 240 | t.Errorf("[%v] Inner error does not match expectation. %v != %v", data.name, ve.Inner, keyFuncError) 241 | } 242 | } 243 | } 244 | if data.valid && token.Signature == "" { 245 | t.Errorf("[%v] Signature is left unpopulated after parsing", data.name) 246 | } 247 | } 248 | } 249 | 250 | func TestParser_ParseUnverified(t *testing.T) { 251 | privateKey := test.LoadRSAPrivateKeyFromDisk("test/sample_key") 252 | 253 | // Iterate over test data set and run tests 254 | for _, data := range jwtTestData { 255 | // If the token string is blank, use helper function to generate string 256 | if data.tokenString == "" { 257 | data.tokenString = test.MakeSampleToken(data.claims, privateKey) 258 | } 259 | 260 | // Parse the token 261 | var token *jwt.Token 262 | var err error 263 | var parser = data.parser 264 | if parser == nil { 265 | parser = new(jwt.Parser) 266 | } 267 | // Figure out correct claims type 268 | switch data.claims.(type) { 269 | case jwt.MapClaims: 270 | token, _, err = parser.ParseUnverified(data.tokenString, jwt.MapClaims{}) 271 | case *jwt.StandardClaims: 272 | token, _, err = parser.ParseUnverified(data.tokenString, &jwt.StandardClaims{}) 273 | } 274 | 275 | if err != nil { 276 | t.Errorf("[%v] Invalid token", data.name) 277 | } 278 | 279 | // Verify result matches expectation 280 | if !reflect.DeepEqual(data.claims, token.Claims) { 281 | t.Errorf("[%v] Claims mismatch. Expecting: %v Got: %v", data.name, data.claims, token.Claims) 282 | } 283 | 284 | if data.valid && err != nil { 285 | t.Errorf("[%v] Error while verifying token: %T:%v", data.name, err, err) 286 | } 287 | } 288 | } 289 | 290 | // Helper method for benchmarking various methods 291 | func benchmarkSigning(b *testing.B, method jwt.SigningMethod, key interface{}) { 292 | t := jwt.New(method) 293 | b.RunParallel(func(pb *testing.PB) { 294 | for pb.Next() { 295 | if _, err := t.SignedString(key); err != nil { 296 | b.Fatal(err) 297 | } 298 | } 299 | }) 300 | 301 | } 302 | -------------------------------------------------------------------------------- /request/doc.go: -------------------------------------------------------------------------------- 1 | // Utility package for extracting JWT tokens from 2 | // HTTP requests. 3 | // 4 | // The main function is ParseFromRequest and it's WithClaims variant. 5 | // See examples for how to use the various Extractor implementations 6 | // or roll your own. 7 | package request 8 | -------------------------------------------------------------------------------- /request/extractor.go: -------------------------------------------------------------------------------- 1 | package request 2 | 3 | import ( 4 | "errors" 5 | "net/http" 6 | ) 7 | 8 | // Errors 9 | var ( 10 | ErrNoTokenInRequest = errors.New("no token present in request") 11 | ) 12 | 13 | // Interface for extracting a token from an HTTP request. 14 | // The ExtractToken method should return a token string or an error. 15 | // If no token is present, you must return ErrNoTokenInRequest. 16 | type Extractor interface { 17 | ExtractToken(*http.Request) (string, error) 18 | } 19 | 20 | // Extractor for finding a token in a header. Looks at each specified 21 | // header in order until there's a match 22 | type HeaderExtractor []string 23 | 24 | func (e HeaderExtractor) ExtractToken(req *http.Request) (string, error) { 25 | // loop over header names and return the first one that contains data 26 | for _, header := range e { 27 | if ah := req.Header.Get(header); ah != "" { 28 | return ah, nil 29 | } 30 | } 31 | return "", ErrNoTokenInRequest 32 | } 33 | 34 | // Extract token from request arguments. This includes a POSTed form or 35 | // GET URL arguments. Argument names are tried in order until there's a match. 36 | // This extractor calls `ParseMultipartForm` on the request 37 | type ArgumentExtractor []string 38 | 39 | func (e ArgumentExtractor) ExtractToken(req *http.Request) (string, error) { 40 | // Make sure form is parsed 41 | req.ParseMultipartForm(10e6) 42 | 43 | // loop over arg names and return the first one that contains data 44 | for _, arg := range e { 45 | if ah := req.Form.Get(arg); ah != "" { 46 | return ah, nil 47 | } 48 | } 49 | 50 | return "", ErrNoTokenInRequest 51 | } 52 | 53 | // Tries Extractors in order until one returns a token string or an error occurs 54 | type MultiExtractor []Extractor 55 | 56 | func (e MultiExtractor) ExtractToken(req *http.Request) (string, error) { 57 | // loop over header names and return the first one that contains data 58 | for _, extractor := range e { 59 | if tok, err := extractor.ExtractToken(req); tok != "" { 60 | return tok, nil 61 | } else if err != ErrNoTokenInRequest { 62 | return "", err 63 | } 64 | } 65 | return "", ErrNoTokenInRequest 66 | } 67 | 68 | // Wrap an Extractor in this to post-process the value before it's handed off. 69 | // See AuthorizationHeaderExtractor for an example 70 | type PostExtractionFilter struct { 71 | Extractor 72 | Filter func(string) (string, error) 73 | } 74 | 75 | func (e *PostExtractionFilter) ExtractToken(req *http.Request) (string, error) { 76 | if tok, err := e.Extractor.ExtractToken(req); tok != "" { 77 | return e.Filter(tok) 78 | } else { 79 | return "", err 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /request/extractor_example_test.go: -------------------------------------------------------------------------------- 1 | package request 2 | 3 | import ( 4 | "fmt" 5 | "net/url" 6 | ) 7 | 8 | const ( 9 | exampleTokenA = "A" 10 | ) 11 | 12 | func ExampleHeaderExtractor() { 13 | req := makeExampleRequest("GET", "/", map[string]string{"Token": exampleTokenA}, nil) 14 | tokenString, err := HeaderExtractor{"Token"}.ExtractToken(req) 15 | if err == nil { 16 | fmt.Println(tokenString) 17 | } else { 18 | fmt.Println(err) 19 | } 20 | //Output: A 21 | } 22 | 23 | func ExampleArgumentExtractor() { 24 | req := makeExampleRequest("GET", "/", nil, url.Values{"token": {extractorTestTokenA}}) 25 | tokenString, err := ArgumentExtractor{"token"}.ExtractToken(req) 26 | if err == nil { 27 | fmt.Println(tokenString) 28 | } else { 29 | fmt.Println(err) 30 | } 31 | //Output: A 32 | } 33 | -------------------------------------------------------------------------------- /request/extractor_test.go: -------------------------------------------------------------------------------- 1 | package request 2 | 3 | import ( 4 | "fmt" 5 | "net/http" 6 | "net/url" 7 | "testing" 8 | ) 9 | 10 | var extractorTestTokenA = "A" 11 | var extractorTestTokenB = "B" 12 | 13 | var extractorTestData = []struct { 14 | name string 15 | extractor Extractor 16 | headers map[string]string 17 | query url.Values 18 | token string 19 | err error 20 | }{ 21 | { 22 | name: "simple header", 23 | extractor: HeaderExtractor{"Foo"}, 24 | headers: map[string]string{"Foo": extractorTestTokenA}, 25 | query: nil, 26 | token: extractorTestTokenA, 27 | err: nil, 28 | }, 29 | { 30 | name: "simple argument", 31 | extractor: ArgumentExtractor{"token"}, 32 | headers: map[string]string{}, 33 | query: url.Values{"token": {extractorTestTokenA}}, 34 | token: extractorTestTokenA, 35 | err: nil, 36 | }, 37 | { 38 | name: "multiple extractors", 39 | extractor: MultiExtractor{ 40 | HeaderExtractor{"Foo"}, 41 | ArgumentExtractor{"token"}, 42 | }, 43 | headers: map[string]string{"Foo": extractorTestTokenA}, 44 | query: url.Values{"token": {extractorTestTokenB}}, 45 | token: extractorTestTokenA, 46 | err: nil, 47 | }, 48 | { 49 | name: "simple miss", 50 | extractor: HeaderExtractor{"This-Header-Is-Not-Set"}, 51 | headers: map[string]string{"Foo": extractorTestTokenA}, 52 | query: nil, 53 | token: "", 54 | err: ErrNoTokenInRequest, 55 | }, 56 | { 57 | name: "filter", 58 | extractor: AuthorizationHeaderExtractor, 59 | headers: map[string]string{"Authorization": "Bearer " + extractorTestTokenA}, 60 | query: nil, 61 | token: extractorTestTokenA, 62 | err: nil, 63 | }, 64 | } 65 | 66 | func TestExtractor(t *testing.T) { 67 | // Bearer token request 68 | for _, data := range extractorTestData { 69 | // Make request from test struct 70 | r := makeExampleRequest("GET", "/", data.headers, data.query) 71 | 72 | // Test extractor 73 | token, err := data.extractor.ExtractToken(r) 74 | if token != data.token { 75 | t.Errorf("[%v] Expected token '%v'. Got '%v'", data.name, data.token, token) 76 | continue 77 | } 78 | if err != data.err { 79 | t.Errorf("[%v] Expected error '%v'. Got '%v'", data.name, data.err, err) 80 | continue 81 | } 82 | } 83 | } 84 | 85 | func makeExampleRequest(method, path string, headers map[string]string, urlArgs url.Values) *http.Request { 86 | r, _ := http.NewRequest(method, fmt.Sprintf("%v?%v", path, urlArgs.Encode()), nil) 87 | for k, v := range headers { 88 | r.Header.Set(k, v) 89 | } 90 | return r 91 | } 92 | -------------------------------------------------------------------------------- /request/oauth2.go: -------------------------------------------------------------------------------- 1 | package request 2 | 3 | import ( 4 | "strings" 5 | ) 6 | 7 | // Strips 'Bearer ' prefix from bearer token string 8 | func stripBearerPrefixFromTokenString(tok string) (string, error) { 9 | // Should be a bearer token 10 | if len(tok) > 6 && strings.ToUpper(tok[0:7]) == "BEARER " { 11 | return tok[7:], nil 12 | } 13 | return tok, nil 14 | } 15 | 16 | // Extract bearer token from Authorization header 17 | // Uses PostExtractionFilter to strip "Bearer " prefix from header 18 | var AuthorizationHeaderExtractor = &PostExtractionFilter{ 19 | HeaderExtractor{"Authorization"}, 20 | stripBearerPrefixFromTokenString, 21 | } 22 | 23 | // Extractor for OAuth2 access tokens. Looks in 'Authorization' 24 | // header then 'access_token' argument for a token. 25 | var OAuth2Extractor = &MultiExtractor{ 26 | AuthorizationHeaderExtractor, 27 | ArgumentExtractor{"access_token"}, 28 | } 29 | -------------------------------------------------------------------------------- /request/request.go: -------------------------------------------------------------------------------- 1 | package request 2 | 3 | import ( 4 | "github.com/dgrijalva/jwt-go" 5 | "net/http" 6 | ) 7 | 8 | // Extract and parse a JWT token from an HTTP request. 9 | // This behaves the same as Parse, but accepts a request and an extractor 10 | // instead of a token string. The Extractor interface allows you to define 11 | // the logic for extracting a token. Several useful implementations are provided. 12 | // 13 | // You can provide options to modify parsing behavior 14 | func ParseFromRequest(req *http.Request, extractor Extractor, keyFunc jwt.Keyfunc, options ...ParseFromRequestOption) (token *jwt.Token, err error) { 15 | // Create basic parser struct 16 | p := &fromRequestParser{req, extractor, nil, nil} 17 | 18 | // Handle options 19 | for _, option := range options { 20 | option(p) 21 | } 22 | 23 | // Set defaults 24 | if p.claims == nil { 25 | p.claims = jwt.MapClaims{} 26 | } 27 | if p.parser == nil { 28 | p.parser = &jwt.Parser{} 29 | } 30 | 31 | // perform extract 32 | tokenString, err := p.extractor.ExtractToken(req) 33 | if err != nil { 34 | return nil, err 35 | } 36 | 37 | // perform parse 38 | return p.parser.ParseWithClaims(tokenString, p.claims, keyFunc) 39 | } 40 | 41 | // ParseFromRequest but with custom Claims type 42 | // DEPRECATED: use ParseFromRequest and the WithClaims option 43 | func ParseFromRequestWithClaims(req *http.Request, extractor Extractor, claims jwt.Claims, keyFunc jwt.Keyfunc) (token *jwt.Token, err error) { 44 | return ParseFromRequest(req, extractor, keyFunc, WithClaims(claims)) 45 | } 46 | 47 | type fromRequestParser struct { 48 | req *http.Request 49 | extractor Extractor 50 | claims jwt.Claims 51 | parser *jwt.Parser 52 | } 53 | 54 | type ParseFromRequestOption func(*fromRequestParser) 55 | 56 | // Parse with custom claims 57 | func WithClaims(claims jwt.Claims) ParseFromRequestOption { 58 | return func(p *fromRequestParser) { 59 | p.claims = claims 60 | } 61 | } 62 | 63 | // Parse using a custom parser 64 | func WithParser(parser *jwt.Parser) ParseFromRequestOption { 65 | return func(p *fromRequestParser) { 66 | p.parser = parser 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /request/request_test.go: -------------------------------------------------------------------------------- 1 | package request 2 | 3 | import ( 4 | "fmt" 5 | "github.com/dgrijalva/jwt-go" 6 | "github.com/dgrijalva/jwt-go/test" 7 | "net/http" 8 | "net/url" 9 | "reflect" 10 | "strings" 11 | "testing" 12 | ) 13 | 14 | var requestTestData = []struct { 15 | name string 16 | claims jwt.MapClaims 17 | extractor Extractor 18 | headers map[string]string 19 | query url.Values 20 | valid bool 21 | }{ 22 | { 23 | "authorization bearer token", 24 | jwt.MapClaims{"foo": "bar"}, 25 | AuthorizationHeaderExtractor, 26 | map[string]string{"Authorization": "Bearer %v"}, 27 | url.Values{}, 28 | true, 29 | }, 30 | { 31 | "oauth bearer token - header", 32 | jwt.MapClaims{"foo": "bar"}, 33 | OAuth2Extractor, 34 | map[string]string{"Authorization": "Bearer %v"}, 35 | url.Values{}, 36 | true, 37 | }, 38 | { 39 | "oauth bearer token - url", 40 | jwt.MapClaims{"foo": "bar"}, 41 | OAuth2Extractor, 42 | map[string]string{}, 43 | url.Values{"access_token": {"%v"}}, 44 | true, 45 | }, 46 | { 47 | "url token", 48 | jwt.MapClaims{"foo": "bar"}, 49 | ArgumentExtractor{"token"}, 50 | map[string]string{}, 51 | url.Values{"token": {"%v"}}, 52 | true, 53 | }, 54 | } 55 | 56 | func TestParseRequest(t *testing.T) { 57 | // load keys from disk 58 | privateKey := test.LoadRSAPrivateKeyFromDisk("../test/sample_key") 59 | publicKey := test.LoadRSAPublicKeyFromDisk("../test/sample_key.pub") 60 | keyfunc := func(*jwt.Token) (interface{}, error) { 61 | return publicKey, nil 62 | } 63 | 64 | // Bearer token request 65 | for _, data := range requestTestData { 66 | // Make token from claims 67 | tokenString := test.MakeSampleToken(data.claims, privateKey) 68 | 69 | // Make query string 70 | for k, vv := range data.query { 71 | for i, v := range vv { 72 | if strings.Contains(v, "%v") { 73 | data.query[k][i] = fmt.Sprintf(v, tokenString) 74 | } 75 | } 76 | } 77 | 78 | // Make request from test struct 79 | r, _ := http.NewRequest("GET", fmt.Sprintf("/?%v", data.query.Encode()), nil) 80 | for k, v := range data.headers { 81 | if strings.Contains(v, "%v") { 82 | r.Header.Set(k, fmt.Sprintf(v, tokenString)) 83 | } else { 84 | r.Header.Set(k, tokenString) 85 | } 86 | } 87 | token, err := ParseFromRequestWithClaims(r, data.extractor, jwt.MapClaims{}, keyfunc) 88 | 89 | if token == nil { 90 | t.Errorf("[%v] Token was not found: %v", data.name, err) 91 | continue 92 | } 93 | if !reflect.DeepEqual(data.claims, token.Claims) { 94 | t.Errorf("[%v] Claims mismatch. Expecting: %v Got: %v", data.name, data.claims, token.Claims) 95 | } 96 | if data.valid && err != nil { 97 | t.Errorf("[%v] Error while verifying token: %v", data.name, err) 98 | } 99 | if !data.valid && err == nil { 100 | t.Errorf("[%v] Invalid token passed validation", data.name) 101 | } 102 | } 103 | } 104 | -------------------------------------------------------------------------------- /rsa.go: -------------------------------------------------------------------------------- 1 | package jwt 2 | 3 | import ( 4 | "crypto" 5 | "crypto/rand" 6 | "crypto/rsa" 7 | ) 8 | 9 | // Implements the RSA family of signing methods signing methods 10 | // Expects *rsa.PrivateKey for signing and *rsa.PublicKey for validation 11 | type SigningMethodRSA struct { 12 | Name string 13 | Hash crypto.Hash 14 | } 15 | 16 | // Specific instances for RS256 and company 17 | var ( 18 | SigningMethodRS256 *SigningMethodRSA 19 | SigningMethodRS384 *SigningMethodRSA 20 | SigningMethodRS512 *SigningMethodRSA 21 | ) 22 | 23 | func init() { 24 | // RS256 25 | SigningMethodRS256 = &SigningMethodRSA{"RS256", crypto.SHA256} 26 | RegisterSigningMethod(SigningMethodRS256.Alg(), func() SigningMethod { 27 | return SigningMethodRS256 28 | }) 29 | 30 | // RS384 31 | SigningMethodRS384 = &SigningMethodRSA{"RS384", crypto.SHA384} 32 | RegisterSigningMethod(SigningMethodRS384.Alg(), func() SigningMethod { 33 | return SigningMethodRS384 34 | }) 35 | 36 | // RS512 37 | SigningMethodRS512 = &SigningMethodRSA{"RS512", crypto.SHA512} 38 | RegisterSigningMethod(SigningMethodRS512.Alg(), func() SigningMethod { 39 | return SigningMethodRS512 40 | }) 41 | } 42 | 43 | func (m *SigningMethodRSA) Alg() string { 44 | return m.Name 45 | } 46 | 47 | // Implements the Verify method from SigningMethod 48 | // For this signing method, must be an *rsa.PublicKey structure. 49 | func (m *SigningMethodRSA) Verify(signingString, signature string, key interface{}) error { 50 | var err error 51 | 52 | // Decode the signature 53 | var sig []byte 54 | if sig, err = DecodeSegment(signature); err != nil { 55 | return err 56 | } 57 | 58 | var rsaKey *rsa.PublicKey 59 | var ok bool 60 | 61 | if rsaKey, ok = key.(*rsa.PublicKey); !ok { 62 | return ErrInvalidKeyType 63 | } 64 | 65 | // Create hasher 66 | if !m.Hash.Available() { 67 | return ErrHashUnavailable 68 | } 69 | hasher := m.Hash.New() 70 | hasher.Write([]byte(signingString)) 71 | 72 | // Verify the signature 73 | return rsa.VerifyPKCS1v15(rsaKey, m.Hash, hasher.Sum(nil), sig) 74 | } 75 | 76 | // Implements the Sign method from SigningMethod 77 | // For this signing method, must be an *rsa.PrivateKey structure. 78 | func (m *SigningMethodRSA) Sign(signingString string, key interface{}) (string, error) { 79 | var rsaKey *rsa.PrivateKey 80 | var ok bool 81 | 82 | // Validate type of key 83 | if rsaKey, ok = key.(*rsa.PrivateKey); !ok { 84 | return "", ErrInvalidKey 85 | } 86 | 87 | // Create the hasher 88 | if !m.Hash.Available() { 89 | return "", ErrHashUnavailable 90 | } 91 | 92 | hasher := m.Hash.New() 93 | hasher.Write([]byte(signingString)) 94 | 95 | // Sign the string and return the encoded bytes 96 | if sigBytes, err := rsa.SignPKCS1v15(rand.Reader, rsaKey, m.Hash, hasher.Sum(nil)); err == nil { 97 | return EncodeSegment(sigBytes), nil 98 | } else { 99 | return "", err 100 | } 101 | } 102 | -------------------------------------------------------------------------------- /rsa_pss.go: -------------------------------------------------------------------------------- 1 | // +build go1.4 2 | 3 | package jwt 4 | 5 | import ( 6 | "crypto" 7 | "crypto/rand" 8 | "crypto/rsa" 9 | ) 10 | 11 | // Implements the RSAPSS family of signing methods signing methods 12 | type SigningMethodRSAPSS struct { 13 | *SigningMethodRSA 14 | Options *rsa.PSSOptions 15 | // VerifyOptions is optional. If set overrides Options for rsa.VerifyPPS. 16 | // Used to accept tokens signed with rsa.PSSSaltLengthAuto, what doesn't follow 17 | // https://tools.ietf.org/html/rfc7518#section-3.5 but was used previously. 18 | // See https://github.com/dgrijalva/jwt-go/issues/285#issuecomment-437451244 for details. 19 | VerifyOptions *rsa.PSSOptions 20 | } 21 | 22 | // Specific instances for RS/PS and company. 23 | var ( 24 | SigningMethodPS256 *SigningMethodRSAPSS 25 | SigningMethodPS384 *SigningMethodRSAPSS 26 | SigningMethodPS512 *SigningMethodRSAPSS 27 | ) 28 | 29 | func init() { 30 | // PS256 31 | SigningMethodPS256 = &SigningMethodRSAPSS{ 32 | SigningMethodRSA: &SigningMethodRSA{ 33 | Name: "PS256", 34 | Hash: crypto.SHA256, 35 | }, 36 | Options: &rsa.PSSOptions{ 37 | SaltLength: rsa.PSSSaltLengthEqualsHash, 38 | }, 39 | VerifyOptions: &rsa.PSSOptions{ 40 | SaltLength: rsa.PSSSaltLengthAuto, 41 | }, 42 | } 43 | RegisterSigningMethod(SigningMethodPS256.Alg(), func() SigningMethod { 44 | return SigningMethodPS256 45 | }) 46 | 47 | // PS384 48 | SigningMethodPS384 = &SigningMethodRSAPSS{ 49 | SigningMethodRSA: &SigningMethodRSA{ 50 | Name: "PS384", 51 | Hash: crypto.SHA384, 52 | }, 53 | Options: &rsa.PSSOptions{ 54 | SaltLength: rsa.PSSSaltLengthEqualsHash, 55 | }, 56 | VerifyOptions: &rsa.PSSOptions{ 57 | SaltLength: rsa.PSSSaltLengthAuto, 58 | }, 59 | } 60 | RegisterSigningMethod(SigningMethodPS384.Alg(), func() SigningMethod { 61 | return SigningMethodPS384 62 | }) 63 | 64 | // PS512 65 | SigningMethodPS512 = &SigningMethodRSAPSS{ 66 | SigningMethodRSA: &SigningMethodRSA{ 67 | Name: "PS512", 68 | Hash: crypto.SHA512, 69 | }, 70 | Options: &rsa.PSSOptions{ 71 | SaltLength: rsa.PSSSaltLengthEqualsHash, 72 | }, 73 | VerifyOptions: &rsa.PSSOptions{ 74 | SaltLength: rsa.PSSSaltLengthAuto, 75 | }, 76 | } 77 | RegisterSigningMethod(SigningMethodPS512.Alg(), func() SigningMethod { 78 | return SigningMethodPS512 79 | }) 80 | } 81 | 82 | // Implements the Verify method from SigningMethod 83 | // For this verify method, key must be an rsa.PublicKey struct 84 | func (m *SigningMethodRSAPSS) Verify(signingString, signature string, key interface{}) error { 85 | var err error 86 | 87 | // Decode the signature 88 | var sig []byte 89 | if sig, err = DecodeSegment(signature); err != nil { 90 | return err 91 | } 92 | 93 | var rsaKey *rsa.PublicKey 94 | switch k := key.(type) { 95 | case *rsa.PublicKey: 96 | rsaKey = k 97 | default: 98 | return ErrInvalidKey 99 | } 100 | 101 | // Create hasher 102 | if !m.Hash.Available() { 103 | return ErrHashUnavailable 104 | } 105 | hasher := m.Hash.New() 106 | hasher.Write([]byte(signingString)) 107 | 108 | opts := m.Options 109 | if m.VerifyOptions != nil { 110 | opts = m.VerifyOptions 111 | } 112 | 113 | return rsa.VerifyPSS(rsaKey, m.Hash, hasher.Sum(nil), sig, opts) 114 | } 115 | 116 | // Implements the Sign method from SigningMethod 117 | // For this signing method, key must be an rsa.PrivateKey struct 118 | func (m *SigningMethodRSAPSS) Sign(signingString string, key interface{}) (string, error) { 119 | var rsaKey *rsa.PrivateKey 120 | 121 | switch k := key.(type) { 122 | case *rsa.PrivateKey: 123 | rsaKey = k 124 | default: 125 | return "", ErrInvalidKeyType 126 | } 127 | 128 | // Create the hasher 129 | if !m.Hash.Available() { 130 | return "", ErrHashUnavailable 131 | } 132 | 133 | hasher := m.Hash.New() 134 | hasher.Write([]byte(signingString)) 135 | 136 | // Sign the string and return the encoded bytes 137 | if sigBytes, err := rsa.SignPSS(rand.Reader, rsaKey, m.Hash, hasher.Sum(nil), m.Options); err == nil { 138 | return EncodeSegment(sigBytes), nil 139 | } else { 140 | return "", err 141 | } 142 | } 143 | -------------------------------------------------------------------------------- /rsa_pss_test.go: -------------------------------------------------------------------------------- 1 | // +build go1.4 2 | 3 | package jwt_test 4 | 5 | import ( 6 | "crypto/rsa" 7 | "io/ioutil" 8 | "strings" 9 | "testing" 10 | "time" 11 | 12 | "github.com/dgrijalva/jwt-go" 13 | "github.com/dgrijalva/jwt-go/test" 14 | ) 15 | 16 | var rsaPSSTestData = []struct { 17 | name string 18 | tokenString string 19 | alg string 20 | claims map[string]interface{} 21 | valid bool 22 | }{ 23 | { 24 | "Basic PS256", 25 | "eyJhbGciOiJQUzI1NiIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIifQ.PPG4xyDVY8ffp4CcxofNmsTDXsrVG2npdQuibLhJbv4ClyPTUtR5giNSvuxo03kB6I8VXVr0Y9X7UxhJVEoJOmULAwRWaUsDnIewQa101cVhMa6iR8X37kfFoiZ6NkS-c7henVkkQWu2HtotkEtQvN5hFlk8IevXXPmvZlhQhwzB1sGzGYnoi1zOfuL98d3BIjUjtlwii5w6gYG2AEEzp7HnHCsb3jIwUPdq86Oe6hIFjtBwduIK90ca4UqzARpcfwxHwVLMpatKask00AgGVI0ysdk0BLMjmLutquD03XbThHScC2C2_Pp4cHWgMzvbgLU2RYYZcZRKr46QeNgz9w", 26 | "PS256", 27 | map[string]interface{}{"foo": "bar"}, 28 | true, 29 | }, 30 | { 31 | "Basic PS384", 32 | "eyJhbGciOiJQUzM4NCIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIifQ.w7-qqgj97gK4fJsq_DCqdYQiylJjzWONvD0qWWWhqEOFk2P1eDULPnqHRnjgTXoO4HAw4YIWCsZPet7nR3Xxq4ZhMqvKW8b7KlfRTb9cH8zqFvzMmybQ4jv2hKc3bXYqVow3AoR7hN_CWXI3Dv6Kd2X5xhtxRHI6IL39oTVDUQ74LACe-9t4c3QRPuj6Pq1H4FAT2E2kW_0KOc6EQhCLWEhm2Z2__OZskDC8AiPpP8Kv4k2vB7l0IKQu8Pr4RcNBlqJdq8dA5D3hk5TLxP8V5nG1Ib80MOMMqoS3FQvSLyolFX-R_jZ3-zfq6Ebsqr0yEb0AH2CfsECF7935Pa0FKQ", 33 | "PS384", 34 | map[string]interface{}{"foo": "bar"}, 35 | true, 36 | }, 37 | { 38 | "Basic PS512", 39 | "eyJhbGciOiJQUzUxMiIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIifQ.GX1HWGzFaJevuSLavqqFYaW8_TpvcjQ8KfC5fXiSDzSiT9UD9nB_ikSmDNyDILNdtjZLSvVKfXxZJqCfefxAtiozEDDdJthZ-F0uO4SPFHlGiXszvKeodh7BuTWRI2wL9-ZO4mFa8nq3GMeQAfo9cx11i7nfN8n2YNQ9SHGovG7_T_AvaMZB_jT6jkDHpwGR9mz7x1sycckEo6teLdHRnH_ZdlHlxqknmyTu8Odr5Xh0sJFOL8BepWbbvIIn-P161rRHHiDWFv6nhlHwZnVzjx7HQrWSGb6-s2cdLie9QL_8XaMcUpjLkfOMKkDOfHo6AvpL7Jbwi83Z2ZTHjJWB-A", 40 | "PS512", 41 | map[string]interface{}{"foo": "bar"}, 42 | true, 43 | }, 44 | { 45 | "basic PS256 invalid: foo => bar", 46 | "eyJhbGciOiJQUzI1NiIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIifQ.PPG4xyDVY8ffp4CcxofNmsTDXsrVG2npdQuibLhJbv4ClyPTUtR5giNSvuxo03kB6I8VXVr0Y9X7UxhJVEoJOmULAwRWaUsDnIewQa101cVhMa6iR8X37kfFoiZ6NkS-c7henVkkQWu2HtotkEtQvN5hFlk8IevXXPmvZlhQhwzB1sGzGYnoi1zOfuL98d3BIjUjtlwii5w6gYG2AEEzp7HnHCsb3jIwUPdq86Oe6hIFjtBwduIK90ca4UqzARpcfwxHwVLMpatKask00AgGVI0ysdk0BLMjmLutquD03XbThHScC2C2_Pp4cHWgMzvbgLU2RYYZcZRKr46QeNgz9W", 47 | "PS256", 48 | map[string]interface{}{"foo": "bar"}, 49 | false, 50 | }, 51 | } 52 | 53 | func TestRSAPSSVerify(t *testing.T) { 54 | var err error 55 | 56 | key, _ := ioutil.ReadFile("test/sample_key.pub") 57 | var rsaPSSKey *rsa.PublicKey 58 | if rsaPSSKey, err = jwt.ParseRSAPublicKeyFromPEM(key); err != nil { 59 | t.Errorf("Unable to parse RSA public key: %v", err) 60 | } 61 | 62 | for _, data := range rsaPSSTestData { 63 | parts := strings.Split(data.tokenString, ".") 64 | 65 | method := jwt.GetSigningMethod(data.alg) 66 | err := method.Verify(strings.Join(parts[0:2], "."), parts[2], rsaPSSKey) 67 | if data.valid && err != nil { 68 | t.Errorf("[%v] Error while verifying key: %v", data.name, err) 69 | } 70 | if !data.valid && err == nil { 71 | t.Errorf("[%v] Invalid key passed validation", data.name) 72 | } 73 | } 74 | } 75 | 76 | func TestRSAPSSSign(t *testing.T) { 77 | var err error 78 | 79 | key, _ := ioutil.ReadFile("test/sample_key") 80 | var rsaPSSKey *rsa.PrivateKey 81 | if rsaPSSKey, err = jwt.ParseRSAPrivateKeyFromPEM(key); err != nil { 82 | t.Errorf("Unable to parse RSA private key: %v", err) 83 | } 84 | 85 | for _, data := range rsaPSSTestData { 86 | if data.valid { 87 | parts := strings.Split(data.tokenString, ".") 88 | method := jwt.GetSigningMethod(data.alg) 89 | sig, err := method.Sign(strings.Join(parts[0:2], "."), rsaPSSKey) 90 | if err != nil { 91 | t.Errorf("[%v] Error signing token: %v", data.name, err) 92 | } 93 | if sig == parts[2] { 94 | t.Errorf("[%v] Signatures shouldn't match\nnew:\n%v\noriginal:\n%v", data.name, sig, parts[2]) 95 | } 96 | } 97 | } 98 | } 99 | 100 | func TestRSAPSSSaltLengthCompatibility(t *testing.T) { 101 | // Fails token verify, if salt length is auto. 102 | ps256SaltLengthEqualsHash := &jwt.SigningMethodRSAPSS{ 103 | SigningMethodRSA: jwt.SigningMethodPS256.SigningMethodRSA, 104 | Options: &rsa.PSSOptions{ 105 | SaltLength: rsa.PSSSaltLengthEqualsHash, 106 | }, 107 | } 108 | 109 | // Behaves as before https://github.com/dgrijalva/jwt-go/issues/285 fix. 110 | ps256SaltLengthAuto := &jwt.SigningMethodRSAPSS{ 111 | SigningMethodRSA: jwt.SigningMethodPS256.SigningMethodRSA, 112 | Options: &rsa.PSSOptions{ 113 | SaltLength: rsa.PSSSaltLengthAuto, 114 | }, 115 | } 116 | if !verify(jwt.SigningMethodPS256, makeToken(ps256SaltLengthEqualsHash)) { 117 | t.Error("SigningMethodPS256 should accept salt length that is defined in RFC") 118 | } 119 | if !verify(ps256SaltLengthEqualsHash, makeToken(jwt.SigningMethodPS256)) { 120 | t.Error("Sign by SigningMethodPS256 should have salt length that is defined in RFC") 121 | } 122 | if !verify(jwt.SigningMethodPS256, makeToken(ps256SaltLengthAuto)) { 123 | t.Error("SigningMethodPS256 should accept auto salt length to be compatible with previous versions") 124 | } 125 | if !verify(ps256SaltLengthAuto, makeToken(jwt.SigningMethodPS256)) { 126 | t.Error("Sign by SigningMethodPS256 should be accepted by previous versions") 127 | } 128 | if verify(ps256SaltLengthEqualsHash, makeToken(ps256SaltLengthAuto)) { 129 | t.Error("Auto salt length should be not accepted, when RFC salt length is required") 130 | } 131 | } 132 | 133 | func makeToken(method jwt.SigningMethod) string { 134 | token := jwt.NewWithClaims(method, jwt.StandardClaims{ 135 | Issuer: "example", 136 | IssuedAt: time.Now().Unix(), 137 | }) 138 | privateKey := test.LoadRSAPrivateKeyFromDisk("test/sample_key") 139 | signed, err := token.SignedString(privateKey) 140 | if err != nil { 141 | panic(err) 142 | } 143 | return signed 144 | } 145 | 146 | func verify(signingMethod jwt.SigningMethod, token string) bool { 147 | segments := strings.Split(token, ".") 148 | err := signingMethod.Verify(strings.Join(segments[:2], "."), segments[2], test.LoadRSAPublicKeyFromDisk("test/sample_key.pub")) 149 | return err == nil 150 | } 151 | -------------------------------------------------------------------------------- /rsa_test.go: -------------------------------------------------------------------------------- 1 | package jwt_test 2 | 3 | import ( 4 | "github.com/dgrijalva/jwt-go" 5 | "io/ioutil" 6 | "strings" 7 | "testing" 8 | ) 9 | 10 | var rsaTestData = []struct { 11 | name string 12 | tokenString string 13 | alg string 14 | claims map[string]interface{} 15 | valid bool 16 | }{ 17 | { 18 | "Basic RS256", 19 | "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJmb28iOiJiYXIifQ.FhkiHkoESI_cG3NPigFrxEk9Z60_oXrOT2vGm9Pn6RDgYNovYORQmmA0zs1AoAOf09ly2Nx2YAg6ABqAYga1AcMFkJljwxTT5fYphTuqpWdy4BELeSYJx5Ty2gmr8e7RonuUztrdD5WfPqLKMm1Ozp_T6zALpRmwTIW0QPnaBXaQD90FplAg46Iy1UlDKr-Eupy0i5SLch5Q-p2ZpaL_5fnTIUDlxC3pWhJTyx_71qDI-mAA_5lE_VdroOeflG56sSmDxopPEG3bFlSu1eowyBfxtu0_CuVd-M42RU75Zc4Gsj6uV77MBtbMrf4_7M_NUTSgoIF3fRqxrj0NzihIBg", 20 | "RS256", 21 | map[string]interface{}{"foo": "bar"}, 22 | true, 23 | }, 24 | { 25 | "Basic RS384", 26 | "eyJhbGciOiJSUzM4NCIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIifQ.W-jEzRfBigtCWsinvVVuldiuilzVdU5ty0MvpLaSaqK9PlAWWlDQ1VIQ_qSKzwL5IXaZkvZFJXT3yL3n7OUVu7zCNJzdwznbC8Z-b0z2lYvcklJYi2VOFRcGbJtXUqgjk2oGsiqUMUMOLP70TTefkpsgqDxbRh9CDUfpOJgW-dU7cmgaoswe3wjUAUi6B6G2YEaiuXC0XScQYSYVKIzgKXJV8Zw-7AN_DBUI4GkTpsvQ9fVVjZM9csQiEXhYekyrKu1nu_POpQonGd8yqkIyXPECNmmqH5jH4sFiF67XhD7_JpkvLziBpI-uh86evBUadmHhb9Otqw3uV3NTaXLzJw", 27 | "RS384", 28 | map[string]interface{}{"foo": "bar"}, 29 | true, 30 | }, 31 | { 32 | "Basic RS512", 33 | "eyJhbGciOiJSUzUxMiIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIifQ.zBlLlmRrUxx4SJPUbV37Q1joRcI9EW13grnKduK3wtYKmDXbgDpF1cZ6B-2Jsm5RB8REmMiLpGms-EjXhgnyh2TSHE-9W2gA_jvshegLWtwRVDX40ODSkTb7OVuaWgiy9y7llvcknFBTIg-FnVPVpXMmeV_pvwQyhaz1SSwSPrDyxEmksz1hq7YONXhXPpGaNbMMeDTNP_1oj8DZaqTIL9TwV8_1wb2Odt_Fy58Ke2RVFijsOLdnyEAjt2n9Mxihu9i3PhNBkkxa2GbnXBfq3kzvZ_xxGGopLdHhJjcGWXO-NiwI9_tiu14NRv4L2xC0ItD9Yz68v2ZIZEp_DuzwRQ", 34 | "RS512", 35 | map[string]interface{}{"foo": "bar"}, 36 | true, 37 | }, 38 | { 39 | "basic invalid: foo => bar", 40 | "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJmb28iOiJiYXIifQ.EhkiHkoESI_cG3NPigFrxEk9Z60_oXrOT2vGm9Pn6RDgYNovYORQmmA0zs1AoAOf09ly2Nx2YAg6ABqAYga1AcMFkJljwxTT5fYphTuqpWdy4BELeSYJx5Ty2gmr8e7RonuUztrdD5WfPqLKMm1Ozp_T6zALpRmwTIW0QPnaBXaQD90FplAg46Iy1UlDKr-Eupy0i5SLch5Q-p2ZpaL_5fnTIUDlxC3pWhJTyx_71qDI-mAA_5lE_VdroOeflG56sSmDxopPEG3bFlSu1eowyBfxtu0_CuVd-M42RU75Zc4Gsj6uV77MBtbMrf4_7M_NUTSgoIF3fRqxrj0NzihIBg", 41 | "RS256", 42 | map[string]interface{}{"foo": "bar"}, 43 | false, 44 | }, 45 | } 46 | 47 | func TestRSAVerify(t *testing.T) { 48 | keyData, _ := ioutil.ReadFile("test/sample_key.pub") 49 | key, _ := jwt.ParseRSAPublicKeyFromPEM(keyData) 50 | 51 | for _, data := range rsaTestData { 52 | parts := strings.Split(data.tokenString, ".") 53 | 54 | method := jwt.GetSigningMethod(data.alg) 55 | err := method.Verify(strings.Join(parts[0:2], "."), parts[2], key) 56 | if data.valid && err != nil { 57 | t.Errorf("[%v] Error while verifying key: %v", data.name, err) 58 | } 59 | if !data.valid && err == nil { 60 | t.Errorf("[%v] Invalid key passed validation", data.name) 61 | } 62 | } 63 | } 64 | 65 | func TestRSASign(t *testing.T) { 66 | keyData, _ := ioutil.ReadFile("test/sample_key") 67 | key, _ := jwt.ParseRSAPrivateKeyFromPEM(keyData) 68 | 69 | for _, data := range rsaTestData { 70 | if data.valid { 71 | parts := strings.Split(data.tokenString, ".") 72 | method := jwt.GetSigningMethod(data.alg) 73 | sig, err := method.Sign(strings.Join(parts[0:2], "."), key) 74 | if err != nil { 75 | t.Errorf("[%v] Error signing token: %v", data.name, err) 76 | } 77 | if sig != parts[2] { 78 | t.Errorf("[%v] Incorrect signature.\nwas:\n%v\nexpecting:\n%v", data.name, sig, parts[2]) 79 | } 80 | } 81 | } 82 | } 83 | 84 | func TestRSAVerifyWithPreParsedPrivateKey(t *testing.T) { 85 | key, _ := ioutil.ReadFile("test/sample_key.pub") 86 | parsedKey, err := jwt.ParseRSAPublicKeyFromPEM(key) 87 | if err != nil { 88 | t.Fatal(err) 89 | } 90 | testData := rsaTestData[0] 91 | parts := strings.Split(testData.tokenString, ".") 92 | err = jwt.SigningMethodRS256.Verify(strings.Join(parts[0:2], "."), parts[2], parsedKey) 93 | if err != nil { 94 | t.Errorf("[%v] Error while verifying key: %v", testData.name, err) 95 | } 96 | } 97 | 98 | func TestRSAWithPreParsedPrivateKey(t *testing.T) { 99 | key, _ := ioutil.ReadFile("test/sample_key") 100 | parsedKey, err := jwt.ParseRSAPrivateKeyFromPEM(key) 101 | if err != nil { 102 | t.Fatal(err) 103 | } 104 | testData := rsaTestData[0] 105 | parts := strings.Split(testData.tokenString, ".") 106 | sig, err := jwt.SigningMethodRS256.Sign(strings.Join(parts[0:2], "."), parsedKey) 107 | if err != nil { 108 | t.Errorf("[%v] Error signing token: %v", testData.name, err) 109 | } 110 | if sig != parts[2] { 111 | t.Errorf("[%v] Incorrect signature.\nwas:\n%v\nexpecting:\n%v", testData.name, sig, parts[2]) 112 | } 113 | } 114 | 115 | func TestRSAKeyParsing(t *testing.T) { 116 | key, _ := ioutil.ReadFile("test/sample_key") 117 | secureKey, _ := ioutil.ReadFile("test/privateSecure.pem") 118 | pubKey, _ := ioutil.ReadFile("test/sample_key.pub") 119 | badKey := []byte("All your base are belong to key") 120 | 121 | // Test parsePrivateKey 122 | if _, e := jwt.ParseRSAPrivateKeyFromPEM(key); e != nil { 123 | t.Errorf("Failed to parse valid private key: %v", e) 124 | } 125 | 126 | if k, e := jwt.ParseRSAPrivateKeyFromPEM(pubKey); e == nil { 127 | t.Errorf("Parsed public key as valid private key: %v", k) 128 | } 129 | 130 | if k, e := jwt.ParseRSAPrivateKeyFromPEM(badKey); e == nil { 131 | t.Errorf("Parsed invalid key as valid private key: %v", k) 132 | } 133 | 134 | if _, e := jwt.ParseRSAPrivateKeyFromPEMWithPassword(secureKey, "password"); e != nil { 135 | t.Errorf("Failed to parse valid private key with password: %v", e) 136 | } 137 | 138 | if k, e := jwt.ParseRSAPrivateKeyFromPEMWithPassword(secureKey, "123132"); e == nil { 139 | t.Errorf("Parsed private key with invalid password %v", k) 140 | } 141 | 142 | // Test parsePublicKey 143 | if _, e := jwt.ParseRSAPublicKeyFromPEM(pubKey); e != nil { 144 | t.Errorf("Failed to parse valid public key: %v", e) 145 | } 146 | 147 | if k, e := jwt.ParseRSAPublicKeyFromPEM(key); e == nil { 148 | t.Errorf("Parsed private key as valid public key: %v", k) 149 | } 150 | 151 | if k, e := jwt.ParseRSAPublicKeyFromPEM(badKey); e == nil { 152 | t.Errorf("Parsed invalid key as valid private key: %v", k) 153 | } 154 | 155 | } 156 | 157 | func BenchmarkRS256Signing(b *testing.B) { 158 | key, _ := ioutil.ReadFile("test/sample_key") 159 | parsedKey, err := jwt.ParseRSAPrivateKeyFromPEM(key) 160 | if err != nil { 161 | b.Fatal(err) 162 | } 163 | 164 | benchmarkSigning(b, jwt.SigningMethodRS256, parsedKey) 165 | } 166 | 167 | func BenchmarkRS384Signing(b *testing.B) { 168 | key, _ := ioutil.ReadFile("test/sample_key") 169 | parsedKey, err := jwt.ParseRSAPrivateKeyFromPEM(key) 170 | if err != nil { 171 | b.Fatal(err) 172 | } 173 | 174 | benchmarkSigning(b, jwt.SigningMethodRS384, parsedKey) 175 | } 176 | 177 | func BenchmarkRS512Signing(b *testing.B) { 178 | key, _ := ioutil.ReadFile("test/sample_key") 179 | parsedKey, err := jwt.ParseRSAPrivateKeyFromPEM(key) 180 | if err != nil { 181 | b.Fatal(err) 182 | } 183 | 184 | benchmarkSigning(b, jwt.SigningMethodRS512, parsedKey) 185 | } 186 | -------------------------------------------------------------------------------- /rsa_utils.go: -------------------------------------------------------------------------------- 1 | package jwt 2 | 3 | import ( 4 | "crypto/rsa" 5 | "crypto/x509" 6 | "encoding/pem" 7 | "errors" 8 | ) 9 | 10 | var ( 11 | ErrKeyMustBePEMEncoded = errors.New("Invalid Key: Key must be a PEM encoded PKCS1 or PKCS8 key") 12 | ErrNotRSAPrivateKey = errors.New("Key is not a valid RSA private key") 13 | ErrNotRSAPublicKey = errors.New("Key is not a valid RSA public key") 14 | ) 15 | 16 | // Parse PEM encoded PKCS1 or PKCS8 private key 17 | func ParseRSAPrivateKeyFromPEM(key []byte) (*rsa.PrivateKey, error) { 18 | var err error 19 | 20 | // Parse PEM block 21 | var block *pem.Block 22 | if block, _ = pem.Decode(key); block == nil { 23 | return nil, ErrKeyMustBePEMEncoded 24 | } 25 | 26 | var parsedKey interface{} 27 | if parsedKey, err = x509.ParsePKCS1PrivateKey(block.Bytes); err != nil { 28 | if parsedKey, err = x509.ParsePKCS8PrivateKey(block.Bytes); err != nil { 29 | return nil, err 30 | } 31 | } 32 | 33 | var pkey *rsa.PrivateKey 34 | var ok bool 35 | if pkey, ok = parsedKey.(*rsa.PrivateKey); !ok { 36 | return nil, ErrNotRSAPrivateKey 37 | } 38 | 39 | return pkey, nil 40 | } 41 | 42 | // Parse PEM encoded PKCS1 or PKCS8 private key protected with password 43 | func ParseRSAPrivateKeyFromPEMWithPassword(key []byte, password string) (*rsa.PrivateKey, error) { 44 | var err error 45 | 46 | // Parse PEM block 47 | var block *pem.Block 48 | if block, _ = pem.Decode(key); block == nil { 49 | return nil, ErrKeyMustBePEMEncoded 50 | } 51 | 52 | var parsedKey interface{} 53 | 54 | var blockDecrypted []byte 55 | if blockDecrypted, err = x509.DecryptPEMBlock(block, []byte(password)); err != nil { 56 | return nil, err 57 | } 58 | 59 | if parsedKey, err = x509.ParsePKCS1PrivateKey(blockDecrypted); err != nil { 60 | if parsedKey, err = x509.ParsePKCS8PrivateKey(blockDecrypted); err != nil { 61 | return nil, err 62 | } 63 | } 64 | 65 | var pkey *rsa.PrivateKey 66 | var ok bool 67 | if pkey, ok = parsedKey.(*rsa.PrivateKey); !ok { 68 | return nil, ErrNotRSAPrivateKey 69 | } 70 | 71 | return pkey, nil 72 | } 73 | 74 | // Parse PEM encoded PKCS1 or PKCS8 public key 75 | func ParseRSAPublicKeyFromPEM(key []byte) (*rsa.PublicKey, error) { 76 | var err error 77 | 78 | // Parse PEM block 79 | var block *pem.Block 80 | if block, _ = pem.Decode(key); block == nil { 81 | return nil, ErrKeyMustBePEMEncoded 82 | } 83 | 84 | // Parse the key 85 | var parsedKey interface{} 86 | if parsedKey, err = x509.ParsePKIXPublicKey(block.Bytes); err != nil { 87 | if cert, err := x509.ParseCertificate(block.Bytes); err == nil { 88 | parsedKey = cert.PublicKey 89 | } else { 90 | return nil, err 91 | } 92 | } 93 | 94 | var pkey *rsa.PublicKey 95 | var ok bool 96 | if pkey, ok = parsedKey.(*rsa.PublicKey); !ok { 97 | return nil, ErrNotRSAPublicKey 98 | } 99 | 100 | return pkey, nil 101 | } 102 | -------------------------------------------------------------------------------- /signing_method.go: -------------------------------------------------------------------------------- 1 | package jwt 2 | 3 | import ( 4 | "sync" 5 | ) 6 | 7 | var signingMethods = map[string]func() SigningMethod{} 8 | var signingMethodLock = new(sync.RWMutex) 9 | 10 | // Implement SigningMethod to add new methods for signing or verifying tokens. 11 | type SigningMethod interface { 12 | Verify(signingString, signature string, key interface{}) error // Returns nil if signature is valid 13 | Sign(signingString string, key interface{}) (string, error) // Returns encoded signature or error 14 | Alg() string // returns the alg identifier for this method (example: 'HS256') 15 | } 16 | 17 | // Register the "alg" name and a factory function for signing method. 18 | // This is typically done during init() in the method's implementation 19 | func RegisterSigningMethod(alg string, f func() SigningMethod) { 20 | signingMethodLock.Lock() 21 | defer signingMethodLock.Unlock() 22 | 23 | signingMethods[alg] = f 24 | } 25 | 26 | // Get a signing method from an "alg" string 27 | func GetSigningMethod(alg string) (method SigningMethod) { 28 | signingMethodLock.RLock() 29 | defer signingMethodLock.RUnlock() 30 | 31 | if methodF, ok := signingMethods[alg]; ok { 32 | method = methodF() 33 | } 34 | return 35 | } 36 | -------------------------------------------------------------------------------- /test/ec256-private.pem: -------------------------------------------------------------------------------- 1 | -----BEGIN EC PRIVATE KEY----- 2 | MHcCAQEEIAh5qA3rmqQQuu0vbKV/+zouz/y/Iy2pLpIcWUSyImSwoAoGCCqGSM49 3 | AwEHoUQDQgAEYD54V/vp+54P9DXarYqx4MPcm+HKRIQzNasYSoRQHQ/6S6Ps8tpM 4 | cT+KvIIC8W/e9k0W7Cm72M1P9jU7SLf/vg== 5 | -----END EC PRIVATE KEY----- 6 | -------------------------------------------------------------------------------- /test/ec256-public.pem: -------------------------------------------------------------------------------- 1 | -----BEGIN PUBLIC KEY----- 2 | MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEYD54V/vp+54P9DXarYqx4MPcm+HK 3 | RIQzNasYSoRQHQ/6S6Ps8tpMcT+KvIIC8W/e9k0W7Cm72M1P9jU7SLf/vg== 4 | -----END PUBLIC KEY----- 5 | -------------------------------------------------------------------------------- /test/ec384-private.pem: -------------------------------------------------------------------------------- 1 | -----BEGIN EC PRIVATE KEY----- 2 | MIGkAgEBBDCaCvMHKhcG/qT7xsNLYnDT7sE/D+TtWIol1ROdaK1a564vx5pHbsRy 3 | SEKcIxISi1igBwYFK4EEACKhZANiAATYa7rJaU7feLMqrAx6adZFNQOpaUH/Uylb 4 | ZLriOLON5YFVwtVUpO1FfEXZUIQpptRPtc5ixIPY658yhBSb6irfIJUSP9aYTflJ 5 | GKk/mDkK4t8mWBzhiD5B6jg9cEGhGgA= 6 | -----END EC PRIVATE KEY----- 7 | -------------------------------------------------------------------------------- /test/ec384-public.pem: -------------------------------------------------------------------------------- 1 | -----BEGIN PUBLIC KEY----- 2 | MHYwEAYHKoZIzj0CAQYFK4EEACIDYgAE2Gu6yWlO33izKqwMemnWRTUDqWlB/1Mp 3 | W2S64jizjeWBVcLVVKTtRXxF2VCEKabUT7XOYsSD2OufMoQUm+oq3yCVEj/WmE35 4 | SRipP5g5CuLfJlgc4Yg+Qeo4PXBBoRoA 5 | -----END PUBLIC KEY----- 6 | -------------------------------------------------------------------------------- /test/ec512-private.pem: -------------------------------------------------------------------------------- 1 | -----BEGIN EC PRIVATE KEY----- 2 | MIHcAgEBBEIB0pE4uFaWRx7t03BsYlYvF1YvKaBGyvoakxnodm9ou0R9wC+sJAjH 3 | QZZJikOg4SwNqgQ/hyrOuDK2oAVHhgVGcYmgBwYFK4EEACOhgYkDgYYABAAJXIuw 4 | 12MUzpHggia9POBFYXSxaOGKGbMjIyDI+6q7wi7LMw3HgbaOmgIqFG72o8JBQwYN 5 | 4IbXHf+f86CRY1AA2wHzbHvt6IhkCXTNxBEffa1yMUgu8n9cKKF2iLgyQKcKqW33 6 | 8fGOw/n3Rm2Yd/EB56u2rnD29qS+nOM9eGS+gy39OQ== 7 | -----END EC PRIVATE KEY----- 8 | -------------------------------------------------------------------------------- /test/ec512-public.pem: -------------------------------------------------------------------------------- 1 | -----BEGIN PUBLIC KEY----- 2 | MIGbMBAGByqGSM49AgEGBSuBBAAjA4GGAAQACVyLsNdjFM6R4IImvTzgRWF0sWjh 3 | ihmzIyMgyPuqu8IuyzMNx4G2jpoCKhRu9qPCQUMGDeCG1x3/n/OgkWNQANsB82x7 4 | 7eiIZAl0zcQRH32tcjFILvJ/XCihdoi4MkCnCqlt9/HxjsP590ZtmHfxAeertq5w 5 | 9vakvpzjPXhkvoMt/Tk= 6 | -----END PUBLIC KEY----- 7 | -------------------------------------------------------------------------------- /test/helpers.go: -------------------------------------------------------------------------------- 1 | package test 2 | 3 | import ( 4 | "crypto/rsa" 5 | "github.com/dgrijalva/jwt-go" 6 | "io/ioutil" 7 | ) 8 | 9 | func LoadRSAPrivateKeyFromDisk(location string) *rsa.PrivateKey { 10 | keyData, e := ioutil.ReadFile(location) 11 | if e != nil { 12 | panic(e.Error()) 13 | } 14 | key, e := jwt.ParseRSAPrivateKeyFromPEM(keyData) 15 | if e != nil { 16 | panic(e.Error()) 17 | } 18 | return key 19 | } 20 | 21 | func LoadRSAPublicKeyFromDisk(location string) *rsa.PublicKey { 22 | keyData, e := ioutil.ReadFile(location) 23 | if e != nil { 24 | panic(e.Error()) 25 | } 26 | key, e := jwt.ParseRSAPublicKeyFromPEM(keyData) 27 | if e != nil { 28 | panic(e.Error()) 29 | } 30 | return key 31 | } 32 | 33 | func MakeSampleToken(c jwt.Claims, key interface{}) string { 34 | token := jwt.NewWithClaims(jwt.SigningMethodRS256, c) 35 | s, e := token.SignedString(key) 36 | 37 | if e != nil { 38 | panic(e.Error()) 39 | } 40 | 41 | return s 42 | } 43 | -------------------------------------------------------------------------------- /test/hmacTestKey: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dgrijalva/jwt-go/9742bd7fca1c67ba2eb793750f56ee3094d1b04f/test/hmacTestKey -------------------------------------------------------------------------------- /test/privateSecure.pem: -------------------------------------------------------------------------------- 1 | -----BEGIN RSA PRIVATE KEY----- 2 | Proc-Type: 4,ENCRYPTED 3 | DEK-Info: DES-EDE3-CBC,7487BB8910A3741B 4 | 5 | iL7m48mbFSIy1Y5xbXWwPTR07ufxu7o+myGUE+AdDeWWISkd5W6Gl44oX/jgXldS 6 | mL/ntUXoZzQz2WKEYLwssAtSTGF+QgSIMvV5faiP+pLYvWgk0oVr42po00CvADFL 7 | eDAJC7LgagYifS1l4EAK4MY8RGCHyJWEN5JAr0fc/Haa3WfWZ009kOWAp8MDuYxB 8 | hQlCKUmnUpXCp5c6jwbjlyinLj8XwzzjZ/rVRsY+t2Z0Vcd5qzR5BV8IJCqbG5Py 9 | z15/EFgMG2N2eYMsiEKgdXeKW2H5XIoWyun/3pBigWaDnTtiWSt9kz2MplqYfIT7 10 | F+0XE3gdDGalAeN3YwFPHCkxxBmcI+s6lQG9INmf2/gkJQ+MOZBVXKmGLv6Qis3l 11 | 0eyUz1yZvNzf0zlcUBjiPulLF3peThHMEzhSsATfPomyg5NJ0X7ttd0ybnq+sPe4 12 | qg2OJ8qNhYrqnx7Xlvj61+B2NAZVHvIioma1FzqX8DxQYrnR5S6DJExDqvzNxEz6 13 | 5VPQlH2Ig4hTvNzla84WgJ6USc/2SS4ehCReiNvfeNG9sPZKQnr/Ss8KPIYsKGcC 14 | Pz/vEqbWDmJwHb7KixCQKPt1EbD+/uf0YnhskOWM15YiFbYAOZKJ5rcbz2Zu66vg 15 | GAmqcBsHeFR3s/bObEzjxOmMfSr1vzvr4ActNJWVtfNKZNobSehZiMSHL54AXAZW 16 | Yj48pwTbf7b1sbF0FeCuwTFiYxM+yiZVO5ciYOfmo4HUg53PjknKpcKtEFSj02P1 17 | 8JRBSb++V0IeMDyZLl12zgURDsvualbJMMBBR8emIpF13h0qdyah431gDhHGBnnC 18 | J5UDGq21/flFjzz0x/Okjwf7mPK5pcmF+uW7AxtHqws6m93yD5+RFmfZ8cb/8CL8 19 | jmsQslj+OIE64ykkRoJWpNBKyQjL3CnPnLmAB6TQKxegR94C7/hP1FvRW+W0AgZy 20 | g2QczKQU3KBQP18Ui1HTbkOUJT0Lsy4FnmJFCB/STPRo6NlJiATKHq/cqHWQUvZd 21 | d4oTMb1opKfs7AI9wiJBuskpGAECdRnVduml3dT4p//3BiP6K9ImWMSJeFpjFAFs 22 | AbBMKyitMs0Fyn9AJRPl23TKVQ3cYeSTxus4wLmx5ECSsHRV6g06nYjBp4GWEqSX 23 | RVclXF3zmy3b1+O5s2chJN6TrypzYSEYXJb1vvQLK0lNXqwxZAFV7Roi6xSG0fSY 24 | EAtdUifLonu43EkrLh55KEwkXdVV8xneUjh+TF8VgJKMnqDFfeHFdmN53YYh3n3F 25 | kpYSmVLRzQmLbH9dY+7kqvnsQm8y76vjug3p4IbEbHp/fNGf+gv7KDng1HyCl9A+ 26 | Ow/Hlr0NqCAIhminScbRsZ4SgbRTRgGEYZXvyOtQa/uL6I8t2NR4W7ynispMs0QL 27 | RD61i3++bQXuTi4i8dg3yqIfe9S22NHSzZY/lAHAmmc3r5NrQ1TM1hsSxXawT5CU 28 | anWFjbH6YQ/QplkkAqZMpropWn6ZdNDg/+BUjukDs0HZrbdGy846WxQUvE7G2bAw 29 | IFQ1SymBZBtfnZXhfAXOHoWh017p6HsIkb2xmFrigMj7Jh10VVhdWg== 30 | -----END RSA PRIVATE KEY----- 31 | -------------------------------------------------------------------------------- /test/sample_key: -------------------------------------------------------------------------------- 1 | -----BEGIN RSA PRIVATE KEY----- 2 | MIIEowIBAAKCAQEA4f5wg5l2hKsTeNem/V41fGnJm6gOdrj8ym3rFkEU/wT8RDtn 3 | SgFEZOQpHEgQ7JL38xUfU0Y3g6aYw9QT0hJ7mCpz9Er5qLaMXJwZxzHzAahlfA0i 4 | cqabvJOMvQtzD6uQv6wPEyZtDTWiQi9AXwBpHssPnpYGIn20ZZuNlX2BrClciHhC 5 | PUIIZOQn/MmqTD31jSyjoQoV7MhhMTATKJx2XrHhR+1DcKJzQBSTAGnpYVaqpsAR 6 | ap+nwRipr3nUTuxyGohBTSmjJ2usSeQXHI3bODIRe1AuTyHceAbewn8b462yEWKA 7 | Rdpd9AjQW5SIVPfdsz5B6GlYQ5LdYKtznTuy7wIDAQABAoIBAQCwia1k7+2oZ2d3 8 | n6agCAbqIE1QXfCmh41ZqJHbOY3oRQG3X1wpcGH4Gk+O+zDVTV2JszdcOt7E5dAy 9 | MaomETAhRxB7hlIOnEN7WKm+dGNrKRvV0wDU5ReFMRHg31/Lnu8c+5BvGjZX+ky9 10 | POIhFFYJqwCRlopGSUIxmVj5rSgtzk3iWOQXr+ah1bjEXvlxDOWkHN6YfpV5ThdE 11 | KdBIPGEVqa63r9n2h+qazKrtiRqJqGnOrHzOECYbRFYhexsNFz7YT02xdfSHn7gM 12 | IvabDDP/Qp0PjE1jdouiMaFHYnLBbgvlnZW9yuVf/rpXTUq/njxIXMmvmEyyvSDn 13 | FcFikB8pAoGBAPF77hK4m3/rdGT7X8a/gwvZ2R121aBcdPwEaUhvj/36dx596zvY 14 | mEOjrWfZhF083/nYWE2kVquj2wjs+otCLfifEEgXcVPTnEOPO9Zg3uNSL0nNQghj 15 | FuD3iGLTUBCtM66oTe0jLSslHe8gLGEQqyMzHOzYxNqibxcOZIe8Qt0NAoGBAO+U 16 | I5+XWjWEgDmvyC3TrOSf/KCGjtu0TSv30ipv27bDLMrpvPmD/5lpptTFwcxvVhCs 17 | 2b+chCjlghFSWFbBULBrfci2FtliClOVMYrlNBdUSJhf3aYSG2Doe6Bgt1n2CpNn 18 | /iu37Y3NfemZBJA7hNl4dYe+f+uzM87cdQ214+jrAoGAXA0XxX8ll2+ToOLJsaNT 19 | OvNB9h9Uc5qK5X5w+7G7O998BN2PC/MWp8H+2fVqpXgNENpNXttkRm1hk1dych86 20 | EunfdPuqsX+as44oCyJGFHVBnWpm33eWQw9YqANRI+pCJzP08I5WK3osnPiwshd+ 21 | hR54yjgfYhBFNI7B95PmEQkCgYBzFSz7h1+s34Ycr8SvxsOBWxymG5zaCsUbPsL0 22 | 4aCgLScCHb9J+E86aVbbVFdglYa5Id7DPTL61ixhl7WZjujspeXZGSbmq0Kcnckb 23 | mDgqkLECiOJW2NHP/j0McAkDLL4tysF8TLDO8gvuvzNC+WQ6drO2ThrypLVZQ+ry 24 | eBIPmwKBgEZxhqa0gVvHQG/7Od69KWj4eJP28kq13RhKay8JOoN0vPmspXJo1HY3 25 | CKuHRG+AP579dncdUnOMvfXOtkdM4vk0+hWASBQzM9xzVcztCa+koAugjVaLS9A+ 26 | 9uQoqEeVNTckxx0S2bYevRy7hGQmUJTyQm3j1zEUR5jpdbL83Fbq 27 | -----END RSA PRIVATE KEY----- 28 | -------------------------------------------------------------------------------- /test/sample_key.pub: -------------------------------------------------------------------------------- 1 | -----BEGIN PUBLIC KEY----- 2 | MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA4f5wg5l2hKsTeNem/V41 3 | fGnJm6gOdrj8ym3rFkEU/wT8RDtnSgFEZOQpHEgQ7JL38xUfU0Y3g6aYw9QT0hJ7 4 | mCpz9Er5qLaMXJwZxzHzAahlfA0icqabvJOMvQtzD6uQv6wPEyZtDTWiQi9AXwBp 5 | HssPnpYGIn20ZZuNlX2BrClciHhCPUIIZOQn/MmqTD31jSyjoQoV7MhhMTATKJx2 6 | XrHhR+1DcKJzQBSTAGnpYVaqpsARap+nwRipr3nUTuxyGohBTSmjJ2usSeQXHI3b 7 | ODIRe1AuTyHceAbewn8b462yEWKARdpd9AjQW5SIVPfdsz5B6GlYQ5LdYKtznTuy 8 | 7wIDAQAB 9 | -----END PUBLIC KEY----- 10 | -------------------------------------------------------------------------------- /token.go: -------------------------------------------------------------------------------- 1 | package jwt 2 | 3 | import ( 4 | "encoding/base64" 5 | "encoding/json" 6 | "strings" 7 | "time" 8 | ) 9 | 10 | // TimeFunc provides the current time when parsing token to validate "exp" claim (expiration time). 11 | // You can override it to use another time value. This is useful for testing or if your 12 | // server uses a different time zone than your tokens. 13 | var TimeFunc = time.Now 14 | 15 | // Parse methods use this callback function to supply 16 | // the key for verification. The function receives the parsed, 17 | // but unverified Token. This allows you to use properties in the 18 | // Header of the token (such as `kid`) to identify which key to use. 19 | type Keyfunc func(*Token) (interface{}, error) 20 | 21 | // A JWT Token. Different fields will be used depending on whether you're 22 | // creating or parsing/verifying a token. 23 | type Token struct { 24 | Raw string // The raw token. Populated when you Parse a token 25 | Method SigningMethod // The signing method used or to be used 26 | Header map[string]interface{} // The first segment of the token 27 | Claims Claims // The second segment of the token 28 | Signature string // The third segment of the token. Populated when you Parse a token 29 | Valid bool // Is the token valid? Populated when you Parse/Verify a token 30 | } 31 | 32 | // Create a new Token. Takes a signing method 33 | func New(method SigningMethod) *Token { 34 | return NewWithClaims(method, MapClaims{}) 35 | } 36 | 37 | func NewWithClaims(method SigningMethod, claims Claims) *Token { 38 | return &Token{ 39 | Header: map[string]interface{}{ 40 | "typ": "JWT", 41 | "alg": method.Alg(), 42 | }, 43 | Claims: claims, 44 | Method: method, 45 | } 46 | } 47 | 48 | // Get the complete, signed token 49 | func (t *Token) SignedString(key interface{}) (string, error) { 50 | var sig, sstr string 51 | var err error 52 | if sstr, err = t.SigningString(); err != nil { 53 | return "", err 54 | } 55 | if sig, err = t.Method.Sign(sstr, key); err != nil { 56 | return "", err 57 | } 58 | return strings.Join([]string{sstr, sig}, "."), nil 59 | } 60 | 61 | // Generate the signing string. This is the 62 | // most expensive part of the whole deal. Unless you 63 | // need this for something special, just go straight for 64 | // the SignedString. 65 | func (t *Token) SigningString() (string, error) { 66 | var err error 67 | parts := make([]string, 2) 68 | for i, _ := range parts { 69 | var jsonValue []byte 70 | if i == 0 { 71 | if jsonValue, err = json.Marshal(t.Header); err != nil { 72 | return "", err 73 | } 74 | } else { 75 | if jsonValue, err = json.Marshal(t.Claims); err != nil { 76 | return "", err 77 | } 78 | } 79 | 80 | parts[i] = EncodeSegment(jsonValue) 81 | } 82 | return strings.Join(parts, "."), nil 83 | } 84 | 85 | // Parse, validate, and return a token. 86 | // keyFunc will receive the parsed token and should return the key for validating. 87 | // If everything is kosher, err will be nil 88 | func Parse(tokenString string, keyFunc Keyfunc) (*Token, error) { 89 | return new(Parser).Parse(tokenString, keyFunc) 90 | } 91 | 92 | func ParseWithClaims(tokenString string, claims Claims, keyFunc Keyfunc) (*Token, error) { 93 | return new(Parser).ParseWithClaims(tokenString, claims, keyFunc) 94 | } 95 | 96 | // Encode JWT specific base64url encoding with padding stripped 97 | func EncodeSegment(seg []byte) string { 98 | return strings.TrimRight(base64.URLEncoding.EncodeToString(seg), "=") 99 | } 100 | 101 | // Decode JWT specific base64url encoding with padding stripped 102 | func DecodeSegment(seg string) ([]byte, error) { 103 | if l := len(seg) % 4; l > 0 { 104 | seg += strings.Repeat("=", 4-l) 105 | } 106 | 107 | return base64.URLEncoding.DecodeString(seg) 108 | } 109 | --------------------------------------------------------------------------------