forked from mirror/jwt
Merge branch 'release_3_0_0' into dg/request
This commit is contained in:
commit
bc13ee82c3
|
@ -1,7 +1,8 @@
|
|||
language: go
|
||||
|
||||
go:
|
||||
- 1.3.3
|
||||
- 1.4.2
|
||||
- 1.3
|
||||
- 1.4
|
||||
- 1.5
|
||||
- 1.6
|
||||
- tip
|
||||
|
|
103
README.md
103
README.md
|
@ -4,6 +4,7 @@ A [go](http://www.golang.org) (or 'golang' for search engine friendliness) imple
|
|||
|
||||
**NOTICE:** A vulnerability in JWT was [recently published](https://auth0.com/blog/2015/03/31/critical-vulnerabilities-in-json-web-token-libraries/). As this library doesn't force users to validate the `alg` is what they expected, it's possible your usage is effected. There will be an update soon to remedy this, and it will likey require backwards-incompatible changes to the API. In the short term, please make sure your implementation verifies the `alg` is what you expect.
|
||||
|
||||
|
||||
## What the heck is a JWT?
|
||||
|
||||
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.
|
||||
|
@ -14,7 +15,7 @@ The part in the middle is the interesting bit. It's called the Claims and conta
|
|||
|
||||
## What's in the box?
|
||||
|
||||
This library supports the parsing and verification as well as the generation and signing of JWTs. Current supported signing algorithms are RSA256 and HMAC SHA256, though hooks are present for adding your own.
|
||||
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.
|
||||
|
||||
## Parse and Verify
|
||||
|
||||
|
@ -26,7 +27,7 @@ Parsing and verifying tokens is pretty straight forward. You pass in the token
|
|||
if _, ok := token.Method.(*jwt.SigningMethodRSA); !ok {
|
||||
return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
|
||||
}
|
||||
return myLookupKey(token.Header["kid"])
|
||||
return myLookupKey(token.Header["kid"]), nil
|
||||
})
|
||||
|
||||
if err == nil && token.Valid {
|
||||
|
@ -35,18 +36,18 @@ Parsing and verifying tokens is pretty straight forward. You pass in the token
|
|||
deliverUtterRejection(":(")
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
## Create a token
|
||||
|
||||
```go
|
||||
// Create the token
|
||||
token := jwt.New(jwt.SigningMethodHS256)
|
||||
// Set some claims
|
||||
token.Claims["foo"] = "bar"
|
||||
token.Claims["exp"] = time.Now().Add(time.Hour * 72).Unix()
|
||||
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
|
||||
"foo": "bar",
|
||||
"exp": time.Now().Add(time.Hour * 72).Unix(),
|
||||
})
|
||||
// Sign and get the complete encoded token as a string
|
||||
tokenString, err := token.SignedString(mySigningKey)
|
||||
```
|
||||
```
|
||||
|
||||
## Extensions
|
||||
|
||||
|
@ -62,6 +63,92 @@ This project uses [Semantic Versioning 2.0.0](http://semver.org). Accepted pull
|
|||
|
||||
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.v2`. It will do the right thing WRT semantic versioning.
|
||||
|
||||
## Migration Guide from v2 -> v3
|
||||
|
||||
Added the ability to supply a typed object for the claims section of the token.
|
||||
|
||||
Unfortunately this requires a breaking change. A few new methods were added to support this,
|
||||
and the old default of `map[string]interface{}` was changed to `jwt.MapClaims`.
|
||||
|
||||
The old example for creating a token looked like this..
|
||||
|
||||
```go
|
||||
token := jwt.New(jwt.SigningMethodHS256)
|
||||
token.Claims["foo"] = "bar"
|
||||
token.Claims["exp"] = time.Now().Add(time.Hour * 72).Unix()
|
||||
```
|
||||
|
||||
is now directly mapped to...
|
||||
|
||||
```go
|
||||
token := jwt.New(jwt.SigningMethodHS256)
|
||||
claims := token.Claims.(jwt.MapClaims)
|
||||
claims["foo"] = "bar"
|
||||
claims["exp"] = time.Now().Add(time.Hour * 72).Unix()
|
||||
```
|
||||
|
||||
However, we added a helper `jwt.NewWithClaims` which accepts a claims object.
|
||||
|
||||
Any type can now be used as the claim object for inside a token so long as it implements the interface `jwt.Claims`.
|
||||
|
||||
So, we added an additional claim type `jwt.StandardClaims` was added.
|
||||
This is intended to be used as a base for creating your own types from,
|
||||
and includes a few helper functions for verifying the claims defined [here](https://tools.ietf.org/html/rfc7519#section-4.1).
|
||||
|
||||
```go
|
||||
claims := jwt.StandardClaims{
|
||||
Audience: "myapi"
|
||||
ExpiresAt: time.Now().Add(time.Hour * 72).Unix(),
|
||||
}
|
||||
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
|
||||
```
|
||||
|
||||
On the other end of usage all of the `jwt.Parse` and friends got a `WithClaims` suffix added to them.
|
||||
|
||||
```go
|
||||
token, err := jwt.Parse(token, keyFunc)
|
||||
claims := token.Claims.(jwt.MapClaim)
|
||||
//like you used to..
|
||||
claims["foo"]
|
||||
claims["bar"]
|
||||
```
|
||||
|
||||
New method usage:
|
||||
```go
|
||||
token, err := jwt.ParseWithClaims(token, keyFunc, &jwt.StandardClaims{})
|
||||
claims := token.Claims.(jwt.StandardClaims)
|
||||
fmt.Println(claims.IssuedAt)
|
||||
```
|
||||
|
||||
## Usage Tips
|
||||
|
||||
### Signing vs Encryption
|
||||
|
||||
A token is simply a JSON object that is signed by its author. this tells you exactly two things about the data:
|
||||
|
||||
* The author of the token was in the possession of the signing secret
|
||||
* The data has not been modified since it was signed
|
||||
|
||||
It's important to know that JWT does not provide encryption, which means anyone who has access to the token can read its contents. If you need to protect (encrypt) the data, there is a companion spec, `JWE`, that provides this functionality. JWE is currently outside the scope of this library.
|
||||
|
||||
### Choosing a Signing Method
|
||||
|
||||
There are several signing methods available, and you should probably take the time to learn about the various options before choosing one. The principal design decision is most likely going to be symmetric vs asymmetric.
|
||||
|
||||
Symmetric signing methods, such as HSA, use only a single secret. This is probably the simplest signing method to use since any `[]byte` can be used as a valid secret. They are also slightly computationally faster to use, though this rarely is enough to matter. Symmetric signing methods work the best when both producers and consumers of tokens are trusted, or even the same system. Since the same secret is used to both sign and validate tokens, you can't easily distribute the key for validation.
|
||||
|
||||
Asymmetric signing methods, such as RSA, use different keys for signing and verifying tokens. This makes it possible to produce tokens with a private key, and allow any consumer to access the public key for verification.
|
||||
|
||||
### JWT and OAuth
|
||||
|
||||
It's worth mentioning that OAuth and JWT are not the same thing. A JWT token is simply a signed JSON object. It can be used anywhere such a thing is useful. There is some confusion, though, as JWT is the most common type of bearer token used in OAuth2 authentication.
|
||||
|
||||
Without going too far down the rabbit hole, here's a description of the interaction of these technologies:
|
||||
|
||||
* OAuth is a protocol for allowing an identity provider to be separate from the service a user is logging in to. For example, whenever you use Facebook to log into a different service (Yelp, Spotify, etc), you are using OAuth.
|
||||
* OAuth defines several options for passing around authentication data. One popular method is called a "bearer token". A bearer token is simply a string that _should_ only be held by an authenticated user. Thus, simply presenting this token proves your identity. You can probably derive from here why a JWT might make a good bearer token.
|
||||
* Because bearer tokens are used for authentication, it's important they're kept secret. This is why transactions that use bearer tokens typically happen over SSL.
|
||||
|
||||
## More
|
||||
|
||||
Documentation can be found [on godoc.org](http://godoc.org/github.com/dgrijalva/jwt-go).
|
||||
|
|
|
@ -1,5 +1,20 @@
|
|||
## `jwt-go` Version History
|
||||
|
||||
#### 3.0.0
|
||||
|
||||
* 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.
|
||||
* Added `Claims` interface type to allow users to decode the claims into a custom type
|
||||
* 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.
|
||||
* 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.
|
||||
|
||||
#### 2.5.0
|
||||
|
||||
This will likely be the last backwards compatible release before 3.0.0.
|
||||
|
||||
* Added support for signing method none. You shouldn't use this. The API tries to make this clear.
|
||||
* Updated/fixed some documentation
|
||||
* Added more helpful error message when trying to parse tokens that begin with `BEARER `
|
||||
|
||||
#### 2.4.0
|
||||
|
||||
* Added new type, Parser, to allow for configuration of various parsing parameters
|
||||
|
|
|
@ -0,0 +1,193 @@
|
|||
package jwt
|
||||
|
||||
import "crypto/subtle"
|
||||
|
||||
// For a type to be a Claims object, it must just have a Valid method that determines
|
||||
// if the token is invalid for any supported reason
|
||||
type Claims interface {
|
||||
Valid() error
|
||||
}
|
||||
|
||||
// Structured version of Claims Section, as referenced at
|
||||
// https://tools.ietf.org/html/rfc7519#section-4.1
|
||||
type StandardClaims struct {
|
||||
Audience string `json:"aud,omitempty"`
|
||||
ExpiresAt int64 `json:"exp,omitempty"`
|
||||
Id string `json:"jti,omitempty"`
|
||||
IssuedAt int64 `json:"iat,omitempty"`
|
||||
Issuer string `json:"iss,omitempty"`
|
||||
NotBefore int64 `json:"nbf,omitempty"`
|
||||
Subject string `json:"sub,omitempty"`
|
||||
}
|
||||
|
||||
// Validates time based claims "exp, iat, nbf".
|
||||
// There is no accounting for clock skew.
|
||||
// As well, if any of the above claims are not in the token, it will still
|
||||
// be considered a valid claim.
|
||||
func (c StandardClaims) Valid() error {
|
||||
vErr := new(ValidationError)
|
||||
now := TimeFunc().Unix()
|
||||
|
||||
// The claims below are optional, by default, so if they are set to the
|
||||
// default value in Go, let's not fail the verification for them.
|
||||
if c.VerifyExpiresAt(now, false) == false {
|
||||
vErr.err = "Token is expired"
|
||||
vErr.Errors |= ValidationErrorExpired
|
||||
}
|
||||
|
||||
if c.VerifyIssuedAt(now, false) == false {
|
||||
vErr.err = "Token used before issued, clock skew issue?"
|
||||
vErr.Errors |= ValidationErrorIssuedAt
|
||||
}
|
||||
|
||||
if c.VerifyNotBefore(now, false) == false {
|
||||
vErr.err = "Token is not valid yet"
|
||||
vErr.Errors |= ValidationErrorNotValidYet
|
||||
}
|
||||
|
||||
if vErr.valid() {
|
||||
return nil
|
||||
}
|
||||
|
||||
return vErr
|
||||
}
|
||||
|
||||
// Compares the aud claim against cmp.
|
||||
// If required is false, this method will return true if the value matches or is unset
|
||||
func (c *StandardClaims) VerifyAudience(cmp string, req bool) bool {
|
||||
return verifyAud(c.Audience, cmp, req)
|
||||
}
|
||||
|
||||
// Compares the exp claim against cmp.
|
||||
// If required is false, this method will return true if the value matches or is unset
|
||||
func (c *StandardClaims) VerifyExpiresAt(cmp int64, req bool) bool {
|
||||
return verifyExp(c.ExpiresAt, cmp, req)
|
||||
}
|
||||
|
||||
// Compares the iat claim against cmp.
|
||||
// If required is false, this method will return true if the value matches or is unset
|
||||
func (c *StandardClaims) VerifyIssuedAt(cmp int64, req bool) bool {
|
||||
return verifyIat(c.IssuedAt, cmp, req)
|
||||
}
|
||||
|
||||
// Compares the iss claim against cmp.
|
||||
// If required is false, this method will return true if the value matches or is unset
|
||||
func (c *StandardClaims) VerifyIssuer(cmp string, req bool) bool {
|
||||
return verifyIss(c.Issuer, cmp, req)
|
||||
}
|
||||
|
||||
// Compares the nbf claim against cmp.
|
||||
// If required is false, this method will return true if the value matches or is unset
|
||||
func (c *StandardClaims) VerifyNotBefore(cmp int64, req bool) bool {
|
||||
return verifyNbf(c.NotBefore, cmp, req)
|
||||
}
|
||||
|
||||
type MapClaims map[string]interface{}
|
||||
|
||||
// Compares the aud claim against cmp.
|
||||
// If required is false, this method will return true if the value matches or is unset
|
||||
func (m MapClaims) VerifyAudience(cmp string, req bool) bool {
|
||||
aud, _ := m["aud"].(string)
|
||||
return verifyAud(aud, cmp, req)
|
||||
}
|
||||
|
||||
// Compares the exp claim against cmp.
|
||||
// If required is false, this method will return true if the value matches or is unset
|
||||
func (m MapClaims) VerifyExpiresAt(cmp int64, req bool) bool {
|
||||
exp, _ := m["exp"].(float64)
|
||||
return verifyExp(int64(exp), cmp, req)
|
||||
}
|
||||
|
||||
// Compares the iat claim against cmp.
|
||||
// If required is false, this method will return true if the value matches or is unset
|
||||
func (m MapClaims) VerifyIssuedAt(cmp int64, req bool) bool {
|
||||
iat, _ := m["iat"].(float64)
|
||||
return verifyIat(int64(iat), cmp, req)
|
||||
}
|
||||
|
||||
// Compares the iss claim against cmp.
|
||||
// If required is false, this method will return true if the value matches or is unset
|
||||
func (m MapClaims) VerifyIssuer(cmp string, req bool) bool {
|
||||
iss, _ := m["iss"].(string)
|
||||
return verifyIss(iss, cmp, req)
|
||||
}
|
||||
|
||||
// Compares the nbf claim against cmp.
|
||||
// If required is false, this method will return true if the value matches or is unset
|
||||
func (m MapClaims) VerifyNotBefore(cmp int64, req bool) bool {
|
||||
nbf, _ := m["nbf"].(float64)
|
||||
return verifyNbf(int64(nbf), cmp, req)
|
||||
}
|
||||
|
||||
// Validates time based claims "exp, iat, nbf".
|
||||
// There is no accounting for clock skew.
|
||||
// As well, if any of the above claims are not in the token, it will still
|
||||
// be considered a valid claim.
|
||||
func (m MapClaims) Valid() error {
|
||||
vErr := new(ValidationError)
|
||||
now := TimeFunc().Unix()
|
||||
|
||||
if m.VerifyExpiresAt(now, false) == false {
|
||||
vErr.err = "Token is expired"
|
||||
vErr.Errors |= ValidationErrorExpired
|
||||
}
|
||||
|
||||
if m.VerifyIssuedAt(now, false) == false {
|
||||
vErr.err = "Token used before issued, clock skew issue?"
|
||||
vErr.Errors |= ValidationErrorIssuedAt
|
||||
}
|
||||
|
||||
if m.VerifyNotBefore(now, false) == false {
|
||||
vErr.err = "Token is not valid yet"
|
||||
vErr.Errors |= ValidationErrorNotValidYet
|
||||
}
|
||||
|
||||
if vErr.valid() {
|
||||
return nil
|
||||
}
|
||||
|
||||
return vErr
|
||||
}
|
||||
|
||||
func verifyAud(aud string, cmp string, required bool) bool {
|
||||
if aud == "" {
|
||||
return !required
|
||||
}
|
||||
if subtle.ConstantTimeCompare([]byte(aud), []byte(cmp)) != 0 {
|
||||
return true
|
||||
} else {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func verifyExp(exp int64, now int64, required bool) bool {
|
||||
if exp == 0 {
|
||||
return !required
|
||||
}
|
||||
return now <= exp
|
||||
}
|
||||
|
||||
func verifyIat(iat int64, now int64, required bool) bool {
|
||||
if iat == 0 {
|
||||
return !required
|
||||
}
|
||||
return now >= iat
|
||||
}
|
||||
|
||||
func verifyIss(iss string, cmp string, required bool) bool {
|
||||
if iss == "" {
|
||||
return !required
|
||||
}
|
||||
if subtle.ConstantTimeCompare([]byte(iss), []byte(cmp)) != 0 {
|
||||
return true
|
||||
} else {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func verifyNbf(nbf int64, now int64, required bool) bool {
|
||||
if nbf == 0 {
|
||||
return !required
|
||||
}
|
||||
return now >= nbf
|
||||
}
|
|
@ -163,7 +163,7 @@ func signToken() error {
|
|||
}
|
||||
|
||||
// parse the JSON of the claims
|
||||
var claims map[string]interface{}
|
||||
var claims jwt.MapClaims
|
||||
if err := json.Unmarshal(tokData, &claims); err != nil {
|
||||
return fmt.Errorf("Couldn't parse claims JSON: %v", err)
|
||||
}
|
||||
|
@ -182,8 +182,7 @@ func signToken() error {
|
|||
}
|
||||
|
||||
// create a new token
|
||||
token := jwt.New(alg)
|
||||
token.Claims = claims
|
||||
token := jwt.NewWithClaims(alg, claims)
|
||||
|
||||
if isEs() {
|
||||
if k, ok := key.([]byte); !ok {
|
||||
|
|
11
errors.go
11
errors.go
|
@ -16,8 +16,15 @@ const (
|
|||
ValidationErrorMalformed uint32 = 1 << iota // Token is malformed
|
||||
ValidationErrorUnverifiable // Token could not be verified because of signing problems
|
||||
ValidationErrorSignatureInvalid // Signature validation failed
|
||||
ValidationErrorExpired // Exp validation failed
|
||||
ValidationErrorNotValidYet // NBF validation failed
|
||||
|
||||
// Standard Claim validation errors
|
||||
ValidationErrorAudience // AUD validation failed
|
||||
ValidationErrorExpired // EXP validation failed
|
||||
ValidationErrorIssuedAt // IAT validation failed
|
||||
ValidationErrorIssuer // ISS validation failed
|
||||
ValidationErrorNotValidYet // NBF validation failed
|
||||
ValidationErrorId // JTI validation failed
|
||||
ValidationErrorClaimsInvalid // Generic claims validation error
|
||||
)
|
||||
|
||||
// The error from Parse if token is not valid
|
||||
|
|
|
@ -2,8 +2,9 @@ package jwt_test
|
|||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/dgrijalva/jwt-go"
|
||||
"time"
|
||||
|
||||
"github.com/dgrijalva/jwt-go"
|
||||
)
|
||||
|
||||
func ExampleParse(myToken string, myLookupKey func(interface{}) (interface{}, error)) {
|
||||
|
@ -18,15 +19,55 @@ func ExampleParse(myToken string, myLookupKey func(interface{}) (interface{}, er
|
|||
}
|
||||
}
|
||||
|
||||
func ExampleNew(mySigningKey []byte) (string, error) {
|
||||
func ExampleNew() {
|
||||
// Create the token
|
||||
token := jwt.New(jwt.SigningMethodHS256)
|
||||
token := jwt.New(jwt.SigningMethodRS256)
|
||||
|
||||
// Set some claims
|
||||
token.Claims["foo"] = "bar"
|
||||
token.Claims["exp"] = time.Now().Add(time.Hour * 72).Unix()
|
||||
// Sign and get the complete encoded token as a string
|
||||
tokenString, err := token.SignedString(mySigningKey)
|
||||
return tokenString, err
|
||||
claims := token.Claims.(jwt.MapClaims)
|
||||
claims["foo"] = "bar"
|
||||
claims["exp"] = time.Unix(0, 0).Add(time.Hour * 1).Unix()
|
||||
|
||||
fmt.Printf("<%T> foo:%v exp:%v\n", token.Claims, claims["foo"], claims["exp"])
|
||||
//Output: <jwt.MapClaims> foo:bar exp:3600
|
||||
}
|
||||
|
||||
func ExampleNewWithClaims() {
|
||||
mySigningKey := []byte("AllYourBase")
|
||||
|
||||
// Create the Claims
|
||||
claims := jwt.StandardClaims{
|
||||
ExpiresAt: 15000,
|
||||
Issuer: "test",
|
||||
}
|
||||
|
||||
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
|
||||
ss, err := token.SignedString(mySigningKey)
|
||||
fmt.Printf("%v %v", ss, err)
|
||||
//Output: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1MDAwLCJpc3MiOiJ0ZXN0In0.QsODzZu3lUZMVdhbO76u3Jv02iYCvEHcYVUI1kOWEU0 <nil>
|
||||
}
|
||||
|
||||
func ExampleNewWithClaims_customType() {
|
||||
mySigningKey := []byte("AllYourBase")
|
||||
|
||||
type MyCustomClaims struct {
|
||||
Foo string `json:"foo"`
|
||||
jwt.StandardClaims
|
||||
}
|
||||
|
||||
// Create the Claims
|
||||
claims := MyCustomClaims{
|
||||
"bar",
|
||||
jwt.StandardClaims{
|
||||
ExpiresAt: 15000,
|
||||
Issuer: "test",
|
||||
},
|
||||
}
|
||||
|
||||
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
|
||||
ss, err := token.SignedString(mySigningKey)
|
||||
fmt.Printf("%v %v", ss, err)
|
||||
//Output: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIiLCJleHAiOjE1MDAwLCJpc3MiOiJ0ZXN0In0.HE7fK0xOQwFEr4WDgRWj4teRPZ6i3GLwD5YCm6Pwu_c <nil>
|
||||
}
|
||||
|
||||
func ExampleParse_errorChecking(myToken string, myLookupKey func(interface{}) (interface{}, error)) {
|
||||
|
|
|
@ -0,0 +1,54 @@
|
|||
package jwt
|
||||
|
||||
// Implements the none signing method. This is required by the spec
|
||||
// but you probably should never use it.
|
||||
var SigningMethodNone *signingMethodNone
|
||||
|
||||
const UnsafeAllowNoneSignatureType unsafeNoneMagicConstant = "none signing method allowed"
|
||||
|
||||
var NoneSignatureTypeDisallowedError error
|
||||
|
||||
type signingMethodNone struct{}
|
||||
type unsafeNoneMagicConstant string
|
||||
|
||||
func init() {
|
||||
SigningMethodNone = &signingMethodNone{}
|
||||
NoneSignatureTypeDisallowedError = &ValidationError{
|
||||
"'none' signature type is not allowed",
|
||||
ValidationErrorSignatureInvalid,
|
||||
}
|
||||
RegisterSigningMethod(SigningMethodNone.Alg(), func() SigningMethod {
|
||||
return SigningMethodNone
|
||||
})
|
||||
}
|
||||
|
||||
func (m *signingMethodNone) Alg() string {
|
||||
return "none"
|
||||
}
|
||||
|
||||
// Only allow 'none' alg type if UnsafeAllowNoneSignatureType is specified as the key
|
||||
func (m *signingMethodNone) Verify(signingString, signature string, key interface{}) (err error) {
|
||||
// Key must be UnsafeAllowNoneSignatureType to prevent accidentally
|
||||
// accepting 'none' signing method
|
||||
if _, ok := key.(unsafeNoneMagicConstant); !ok {
|
||||
return NoneSignatureTypeDisallowedError
|
||||
}
|
||||
// If signing method is none, signature must be an empty string
|
||||
if signature != "" {
|
||||
return &ValidationError{
|
||||
"'none' signing method with non-empty signature",
|
||||
ValidationErrorSignatureInvalid,
|
||||
}
|
||||
}
|
||||
|
||||
// Accept 'none' signing method.
|
||||
return nil
|
||||
}
|
||||
|
||||
// Only allow 'none' signing if UnsafeAllowNoneSignatureType is specified as the key
|
||||
func (m *signingMethodNone) Sign(signingString string, key interface{}) (string, error) {
|
||||
if _, ok := key.(unsafeNoneMagicConstant); ok {
|
||||
return "", nil
|
||||
}
|
||||
return "", NoneSignatureTypeDisallowedError
|
||||
}
|
|
@ -0,0 +1,72 @@
|
|||
package jwt_test
|
||||
|
||||
import (
|
||||
"github.com/dgrijalva/jwt-go"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
var noneTestData = []struct {
|
||||
name string
|
||||
tokenString string
|
||||
alg string
|
||||
key interface{}
|
||||
claims map[string]interface{}
|
||||
valid bool
|
||||
}{
|
||||
{
|
||||
"Basic",
|
||||
"eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJmb28iOiJiYXIifQ.",
|
||||
"none",
|
||||
jwt.UnsafeAllowNoneSignatureType,
|
||||
map[string]interface{}{"foo": "bar"},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"Basic - no key",
|
||||
"eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJmb28iOiJiYXIifQ.",
|
||||
"none",
|
||||
nil,
|
||||
map[string]interface{}{"foo": "bar"},
|
||||
false,
|
||||
},
|
||||
{
|
||||
"Signed",
|
||||
"eyJhbGciOiJSUzM4NCIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIifQ.W-jEzRfBigtCWsinvVVuldiuilzVdU5ty0MvpLaSaqK9PlAWWlDQ1VIQ_qSKzwL5IXaZkvZFJXT3yL3n7OUVu7zCNJzdwznbC8Z-b0z2lYvcklJYi2VOFRcGbJtXUqgjk2oGsiqUMUMOLP70TTefkpsgqDxbRh9CDUfpOJgW-dU7cmgaoswe3wjUAUi6B6G2YEaiuXC0XScQYSYVKIzgKXJV8Zw-7AN_DBUI4GkTpsvQ9fVVjZM9csQiEXhYekyrKu1nu_POpQonGd8yqkIyXPECNmmqH5jH4sFiF67XhD7_JpkvLziBpI-uh86evBUadmHhb9Otqw3uV3NTaXLzJw",
|
||||
"none",
|
||||
jwt.UnsafeAllowNoneSignatureType,
|
||||
map[string]interface{}{"foo": "bar"},
|
||||
false,
|
||||
},
|
||||
}
|
||||
|
||||
func TestNoneVerify(t *testing.T) {
|
||||
for _, data := range noneTestData {
|
||||
parts := strings.Split(data.tokenString, ".")
|
||||
|
||||
method := jwt.GetSigningMethod(data.alg)
|
||||
err := method.Verify(strings.Join(parts[0:2], "."), parts[2], data.key)
|
||||
if data.valid && err != nil {
|
||||
t.Errorf("[%v] Error while verifying key: %v", data.name, err)
|
||||
}
|
||||
if !data.valid && err == nil {
|
||||
t.Errorf("[%v] Invalid key passed validation", data.name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestNoneSign(t *testing.T) {
|
||||
for _, data := range noneTestData {
|
||||
if data.valid {
|
||||
parts := strings.Split(data.tokenString, ".")
|
||||
method := jwt.GetSigningMethod(data.alg)
|
||||
sig, err := method.Sign(strings.Join(parts[0:2], "."), data.key)
|
||||
if err != nil {
|
||||
t.Errorf("[%v] Error signing token: %v", data.name, err)
|
||||
}
|
||||
if sig != parts[2] {
|
||||
t.Errorf("[%v] Incorrect signature.\nwas:\n%v\nexpecting:\n%v", data.name, sig, parts[2])
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
35
parser.go
35
parser.go
|
@ -16,6 +16,10 @@ type Parser struct {
|
|||
// keyFunc will receive the parsed token and should return the key for validating.
|
||||
// If everything is kosher, err will be nil
|
||||
func (p *Parser) Parse(tokenString string, keyFunc Keyfunc) (*Token, error) {
|
||||
return p.ParseWithClaims(tokenString, keyFunc, &MapClaims{})
|
||||
}
|
||||
|
||||
func (p *Parser) ParseWithClaims(tokenString string, keyFunc Keyfunc, claims Claims) (*Token, error) {
|
||||
parts := strings.Split(tokenString, ".")
|
||||
if len(parts) != 3 {
|
||||
return nil, &ValidationError{err: "token contains an invalid number of segments", Errors: ValidationErrorMalformed}
|
||||
|
@ -23,9 +27,13 @@ func (p *Parser) Parse(tokenString string, keyFunc Keyfunc) (*Token, error) {
|
|||
|
||||
var err error
|
||||
token := &Token{Raw: tokenString}
|
||||
|
||||
// parse Header
|
||||
var headerBytes []byte
|
||||
if headerBytes, err = DecodeSegment(parts[0]); err != nil {
|
||||
if strings.HasPrefix(strings.ToLower(tokenString), "bearer ") {
|
||||
return token, &ValidationError{err: "tokenstring should not contain 'bearer '", Errors: ValidationErrorMalformed}
|
||||
}
|
||||
return token, &ValidationError{err: err.Error(), Errors: ValidationErrorMalformed}
|
||||
}
|
||||
if err = json.Unmarshal(headerBytes, &token.Header); err != nil {
|
||||
|
@ -34,6 +42,7 @@ func (p *Parser) Parse(tokenString string, keyFunc Keyfunc) (*Token, error) {
|
|||
|
||||
// parse Claims
|
||||
var claimBytes []byte
|
||||
|
||||
if claimBytes, err = DecodeSegment(parts[1]); err != nil {
|
||||
return token, &ValidationError{err: err.Error(), Errors: ValidationErrorMalformed}
|
||||
}
|
||||
|
@ -41,10 +50,12 @@ func (p *Parser) Parse(tokenString string, keyFunc Keyfunc) (*Token, error) {
|
|||
if p.UseJSONNumber {
|
||||
dec.UseNumber()
|
||||
}
|
||||
if err = dec.Decode(&token.Claims); err != nil {
|
||||
if err = dec.Decode(&claims); err != nil {
|
||||
return token, &ValidationError{err: err.Error(), Errors: ValidationErrorMalformed}
|
||||
}
|
||||
|
||||
token.Claims = claims
|
||||
|
||||
// Lookup signature method
|
||||
if method, ok := token.Header["alg"].(string); ok {
|
||||
if token.Method = GetSigningMethod(method); token.Method == nil {
|
||||
|
@ -81,19 +92,17 @@ func (p *Parser) Parse(tokenString string, keyFunc Keyfunc) (*Token, error) {
|
|||
return token, &ValidationError{err: err.Error(), Errors: ValidationErrorUnverifiable}
|
||||
}
|
||||
|
||||
// Check expiration times
|
||||
vErr := &ValidationError{}
|
||||
now := TimeFunc().Unix()
|
||||
if exp, ok := token.Claims["exp"].(float64); ok {
|
||||
if now > int64(exp) {
|
||||
vErr.err = "token is expired"
|
||||
vErr.Errors |= ValidationErrorExpired
|
||||
}
|
||||
}
|
||||
if nbf, ok := token.Claims["nbf"].(float64); ok {
|
||||
if now < int64(nbf) {
|
||||
vErr.err = "token is not valid yet"
|
||||
vErr.Errors |= ValidationErrorNotValidYet
|
||||
|
||||
// Validate Claims
|
||||
if err := token.Claims.Valid(); err != nil {
|
||||
|
||||
// If the Claims Valid returned an error, check if it is a validation error,
|
||||
// If it was another error type, create a ValidationError with a generic ClaimsInvalid flag set
|
||||
if e, ok := err.(*ValidationError); !ok {
|
||||
vErr = &ValidationError{err: err.Error(), Errors: ValidationErrorClaimsInvalid}
|
||||
} else {
|
||||
vErr = e
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -1,17 +1,19 @@
|
|||
package jwt_test
|
||||
|
||||
import (
|
||||
"crypto/rsa"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"github.com/dgrijalva/jwt-go"
|
||||
"io/ioutil"
|
||||
"reflect"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/dgrijalva/jwt-go"
|
||||
)
|
||||
|
||||
var (
|
||||
jwtTestDefaultKey []byte
|
||||
jwtTestDefaultKey *rsa.PublicKey
|
||||
defaultKeyFunc jwt.Keyfunc = func(t *jwt.Token) (interface{}, error) { return jwtTestDefaultKey, nil }
|
||||
emptyKeyFunc jwt.Keyfunc = func(t *jwt.Token) (interface{}, error) { return nil, nil }
|
||||
errorKeyFunc jwt.Keyfunc = func(t *jwt.Token) (interface{}, error) { return nil, fmt.Errorf("error loading key") }
|
||||
|
@ -22,7 +24,7 @@ var jwtTestData = []struct {
|
|||
name string
|
||||
tokenString string
|
||||
keyfunc jwt.Keyfunc
|
||||
claims map[string]interface{}
|
||||
claims jwt.MapClaims
|
||||
valid bool
|
||||
errors uint32
|
||||
parser *jwt.Parser
|
||||
|
@ -31,7 +33,7 @@ var jwtTestData = []struct {
|
|||
"basic",
|
||||
"eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJmb28iOiJiYXIifQ.FhkiHkoESI_cG3NPigFrxEk9Z60_oXrOT2vGm9Pn6RDgYNovYORQmmA0zs1AoAOf09ly2Nx2YAg6ABqAYga1AcMFkJljwxTT5fYphTuqpWdy4BELeSYJx5Ty2gmr8e7RonuUztrdD5WfPqLKMm1Ozp_T6zALpRmwTIW0QPnaBXaQD90FplAg46Iy1UlDKr-Eupy0i5SLch5Q-p2ZpaL_5fnTIUDlxC3pWhJTyx_71qDI-mAA_5lE_VdroOeflG56sSmDxopPEG3bFlSu1eowyBfxtu0_CuVd-M42RU75Zc4Gsj6uV77MBtbMrf4_7M_NUTSgoIF3fRqxrj0NzihIBg",
|
||||
defaultKeyFunc,
|
||||
map[string]interface{}{"foo": "bar"},
|
||||
jwt.MapClaims{"foo": "bar"},
|
||||
true,
|
||||
0,
|
||||
nil,
|
||||
|
@ -40,7 +42,7 @@ var jwtTestData = []struct {
|
|||
"basic expired",
|
||||
"", // autogen
|
||||
defaultKeyFunc,
|
||||
map[string]interface{}{"foo": "bar", "exp": float64(time.Now().Unix() - 100)},
|
||||
jwt.MapClaims{"foo": "bar", "exp": float64(time.Now().Unix() - 100)},
|
||||
false,
|
||||
jwt.ValidationErrorExpired,
|
||||
nil,
|
||||
|
@ -49,7 +51,7 @@ var jwtTestData = []struct {
|
|||
"basic nbf",
|
||||
"", // autogen
|
||||
defaultKeyFunc,
|
||||
map[string]interface{}{"foo": "bar", "nbf": float64(time.Now().Unix() + 100)},
|
||||
jwt.MapClaims{"foo": "bar", "nbf": float64(time.Now().Unix() + 100)},
|
||||
false,
|
||||
jwt.ValidationErrorNotValidYet,
|
||||
nil,
|
||||
|
@ -58,7 +60,7 @@ var jwtTestData = []struct {
|
|||
"expired and nbf",
|
||||
"", // autogen
|
||||
defaultKeyFunc,
|
||||
map[string]interface{}{"foo": "bar", "nbf": float64(time.Now().Unix() + 100), "exp": float64(time.Now().Unix() - 100)},
|
||||
jwt.MapClaims{"foo": "bar", "nbf": float64(time.Now().Unix() + 100), "exp": float64(time.Now().Unix() - 100)},
|
||||
false,
|
||||
jwt.ValidationErrorNotValidYet | jwt.ValidationErrorExpired,
|
||||
nil,
|
||||
|
@ -67,7 +69,7 @@ var jwtTestData = []struct {
|
|||
"basic invalid",
|
||||
"eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJmb28iOiJiYXIifQ.EhkiHkoESI_cG3NPigFrxEk9Z60_oXrOT2vGm9Pn6RDgYNovYORQmmA0zs1AoAOf09ly2Nx2YAg6ABqAYga1AcMFkJljwxTT5fYphTuqpWdy4BELeSYJx5Ty2gmr8e7RonuUztrdD5WfPqLKMm1Ozp_T6zALpRmwTIW0QPnaBXaQD90FplAg46Iy1UlDKr-Eupy0i5SLch5Q-p2ZpaL_5fnTIUDlxC3pWhJTyx_71qDI-mAA_5lE_VdroOeflG56sSmDxopPEG3bFlSu1eowyBfxtu0_CuVd-M42RU75Zc4Gsj6uV77MBtbMrf4_7M_NUTSgoIF3fRqxrj0NzihIBg",
|
||||
defaultKeyFunc,
|
||||
map[string]interface{}{"foo": "bar"},
|
||||
jwt.MapClaims{"foo": "bar"},
|
||||
false,
|
||||
jwt.ValidationErrorSignatureInvalid,
|
||||
nil,
|
||||
|
@ -76,7 +78,7 @@ var jwtTestData = []struct {
|
|||
"basic nokeyfunc",
|
||||
"eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJmb28iOiJiYXIifQ.FhkiHkoESI_cG3NPigFrxEk9Z60_oXrOT2vGm9Pn6RDgYNovYORQmmA0zs1AoAOf09ly2Nx2YAg6ABqAYga1AcMFkJljwxTT5fYphTuqpWdy4BELeSYJx5Ty2gmr8e7RonuUztrdD5WfPqLKMm1Ozp_T6zALpRmwTIW0QPnaBXaQD90FplAg46Iy1UlDKr-Eupy0i5SLch5Q-p2ZpaL_5fnTIUDlxC3pWhJTyx_71qDI-mAA_5lE_VdroOeflG56sSmDxopPEG3bFlSu1eowyBfxtu0_CuVd-M42RU75Zc4Gsj6uV77MBtbMrf4_7M_NUTSgoIF3fRqxrj0NzihIBg",
|
||||
nilKeyFunc,
|
||||
map[string]interface{}{"foo": "bar"},
|
||||
jwt.MapClaims{"foo": "bar"},
|
||||
false,
|
||||
jwt.ValidationErrorUnverifiable,
|
||||
nil,
|
||||
|
@ -85,7 +87,7 @@ var jwtTestData = []struct {
|
|||
"basic nokey",
|
||||
"eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJmb28iOiJiYXIifQ.FhkiHkoESI_cG3NPigFrxEk9Z60_oXrOT2vGm9Pn6RDgYNovYORQmmA0zs1AoAOf09ly2Nx2YAg6ABqAYga1AcMFkJljwxTT5fYphTuqpWdy4BELeSYJx5Ty2gmr8e7RonuUztrdD5WfPqLKMm1Ozp_T6zALpRmwTIW0QPnaBXaQD90FplAg46Iy1UlDKr-Eupy0i5SLch5Q-p2ZpaL_5fnTIUDlxC3pWhJTyx_71qDI-mAA_5lE_VdroOeflG56sSmDxopPEG3bFlSu1eowyBfxtu0_CuVd-M42RU75Zc4Gsj6uV77MBtbMrf4_7M_NUTSgoIF3fRqxrj0NzihIBg",
|
||||
emptyKeyFunc,
|
||||
map[string]interface{}{"foo": "bar"},
|
||||
jwt.MapClaims{"foo": "bar"},
|
||||
false,
|
||||
jwt.ValidationErrorSignatureInvalid,
|
||||
nil,
|
||||
|
@ -94,7 +96,7 @@ var jwtTestData = []struct {
|
|||
"basic errorkey",
|
||||
"eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJmb28iOiJiYXIifQ.FhkiHkoESI_cG3NPigFrxEk9Z60_oXrOT2vGm9Pn6RDgYNovYORQmmA0zs1AoAOf09ly2Nx2YAg6ABqAYga1AcMFkJljwxTT5fYphTuqpWdy4BELeSYJx5Ty2gmr8e7RonuUztrdD5WfPqLKMm1Ozp_T6zALpRmwTIW0QPnaBXaQD90FplAg46Iy1UlDKr-Eupy0i5SLch5Q-p2ZpaL_5fnTIUDlxC3pWhJTyx_71qDI-mAA_5lE_VdroOeflG56sSmDxopPEG3bFlSu1eowyBfxtu0_CuVd-M42RU75Zc4Gsj6uV77MBtbMrf4_7M_NUTSgoIF3fRqxrj0NzihIBg",
|
||||
errorKeyFunc,
|
||||
map[string]interface{}{"foo": "bar"},
|
||||
jwt.MapClaims{"foo": "bar"},
|
||||
false,
|
||||
jwt.ValidationErrorUnverifiable,
|
||||
nil,
|
||||
|
@ -129,20 +131,26 @@ var jwtTestData = []struct {
|
|||
}
|
||||
|
||||
func init() {
|
||||
var e error
|
||||
if jwtTestDefaultKey, e = ioutil.ReadFile("test/sample_key.pub"); e != nil {
|
||||
if keyData, e := ioutil.ReadFile("test/sample_key.pub"); e == nil {
|
||||
if jwtTestDefaultKey, e = jwt.ParseRSAPublicKeyFromPEM(keyData); e != nil {
|
||||
panic(e)
|
||||
}
|
||||
} else {
|
||||
panic(e)
|
||||
}
|
||||
}
|
||||
|
||||
func makeSample(c map[string]interface{}) string {
|
||||
key, e := ioutil.ReadFile("test/sample_key")
|
||||
func makeSample(c jwt.MapClaims) string {
|
||||
keyData, e := ioutil.ReadFile("test/sample_key")
|
||||
if e != nil {
|
||||
panic(e.Error())
|
||||
}
|
||||
key, e := jwt.ParseRSAPrivateKeyFromPEM(keyData)
|
||||
if e != nil {
|
||||
panic(e.Error())
|
||||
}
|
||||
|
||||
token := jwt.New(jwt.SigningMethodRS256)
|
||||
token.Claims = c
|
||||
token := jwt.NewWithClaims(jwt.SigningMethodRS256, c)
|
||||
s, e := token.SignedString(key)
|
||||
|
||||
if e != nil {
|
||||
|
@ -166,15 +174,18 @@ func TestParser_Parse(t *testing.T) {
|
|||
token, err = jwt.Parse(data.tokenString, data.keyfunc)
|
||||
}
|
||||
|
||||
if !reflect.DeepEqual(data.claims, token.Claims) {
|
||||
if !reflect.DeepEqual(&data.claims, token.Claims) {
|
||||
t.Errorf("[%v] Claims mismatch. Expecting: %v Got: %v", data.name, data.claims, token.Claims)
|
||||
}
|
||||
|
||||
if data.valid && err != nil {
|
||||
t.Errorf("[%v] Error while verifying token: %T:%v", data.name, err, err)
|
||||
}
|
||||
|
||||
if !data.valid && err == nil {
|
||||
t.Errorf("[%v] Invalid token passed validation", data.name)
|
||||
}
|
||||
|
||||
if data.errors != 0 {
|
||||
if err == nil {
|
||||
t.Errorf("[%v] Expecting error. Didn't get one.", data.name)
|
||||
|
@ -191,7 +202,6 @@ func TestParser_Parse(t *testing.T) {
|
|||
}
|
||||
}
|
||||
|
||||
|
||||
// Helper method for benchmarking various methods
|
||||
func benchmarkSigning(b *testing.B, method jwt.SigningMethod, key interface{}) {
|
||||
t := jwt.New(method)
|
||||
|
|
|
@ -2,8 +2,8 @@ package request
|
|||
|
||||
import (
|
||||
"github.com/dgrijalva/jwt-go"
|
||||
"strings"
|
||||
"net/http"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Try to find the token in an http.Request.
|
||||
|
@ -11,19 +11,22 @@ import (
|
|||
// Currently, it looks in the Authorization header as well as
|
||||
// looking for an 'access_token' request parameter in req.Form.
|
||||
func ParseFromRequest(req *http.Request, keyFunc jwt.Keyfunc) (token *jwt.Token, err error) {
|
||||
return ParseFromRequestWithClaims(req, keyFunc, &jwt.MapClaims{})
|
||||
}
|
||||
|
||||
func ParseFromRequestWithClaims(req *http.Request, keyFunc jwt.Keyfunc, claims jwt.Claims) (token *jwt.Token, err error) {
|
||||
// Look for an Authorization header
|
||||
if ah := req.Header.Get("Authorization"); ah != "" {
|
||||
// Should be a bearer token
|
||||
if len(ah) > 6 && strings.ToUpper(ah[0:6]) == "BEARER" {
|
||||
return jwt.Parse(ah[7:], keyFunc)
|
||||
if len(ah) > 6 && strings.ToUpper(ah[0:7]) == "BEARER " {
|
||||
return jwt.ParseWithClaims(ah[7:], keyFunc, claims)
|
||||
}
|
||||
}
|
||||
|
||||
// Look for "access_token" parameter
|
||||
req.ParseMultipartForm(10e6)
|
||||
if tokStr := req.Form.Get("access_token"); tokStr != "" {
|
||||
return jwt.Parse(tokStr, keyFunc)
|
||||
return jwt.ParseWithClaims(tokStr, keyFunc, claims)
|
||||
}
|
||||
|
||||
return nil, jwt.ErrNoTokenInRequest
|
||||
|
|
|
@ -1,5 +1,13 @@
|
|||
package request
|
||||
|
||||
// import (
|
||||
// "fmt"
|
||||
// "github.com/dgrijalva/jwt-go"
|
||||
// "net/http"
|
||||
// "reflect"
|
||||
// "testing"
|
||||
// )
|
||||
//
|
||||
// func TestParseRequest(t *testing.T) {
|
||||
// // Bearer token request
|
||||
// for _, data := range jwtTestData {
|
||||
|
@ -15,13 +23,13 @@ package request
|
|||
//
|
||||
// r, _ := http.NewRequest("GET", "/", nil)
|
||||
// r.Header.Set("Authorization", fmt.Sprintf("Bearer %v", data.tokenString))
|
||||
// token, err := jwt.ParseFromRequest(r, data.keyfunc)
|
||||
// token, err := ParseFromRequestWithClaims(r, data.keyfunc, &jwt.MapClaims{})
|
||||
//
|
||||
// if token == nil {
|
||||
// t.Errorf("[%v] Token was not found: %v", data.name, err)
|
||||
// continue
|
||||
// }
|
||||
// if !reflect.DeepEqual(data.claims, token.Claims) {
|
||||
// if !reflect.DeepEqual(&data.claims, token.Claims) {
|
||||
// t.Errorf("[%v] Claims mismatch. Expecting: %v Got: %v", data.name, data.claims, token.Claims)
|
||||
// }
|
||||
// if data.valid && err != nil {
|
||||
|
|
28
rsa.go
28
rsa.go
|
@ -44,8 +44,7 @@ func (m *SigningMethodRSA) Alg() string {
|
|||
}
|
||||
|
||||
// Implements the Verify method from SigningMethod
|
||||
// For this signing method, must be either a PEM encoded PKCS1 or PKCS8 RSA public key as
|
||||
// []byte, or an rsa.PublicKey structure.
|
||||
// For this signing method, must be an rsa.PublicKey structure.
|
||||
func (m *SigningMethodRSA) Verify(signingString, signature string, key interface{}) error {
|
||||
var err error
|
||||
|
||||
|
@ -56,15 +55,9 @@ func (m *SigningMethodRSA) Verify(signingString, signature string, key interface
|
|||
}
|
||||
|
||||
var rsaKey *rsa.PublicKey
|
||||
var ok bool
|
||||
|
||||
switch k := key.(type) {
|
||||
case []byte:
|
||||
if rsaKey, err = ParseRSAPublicKeyFromPEM(k); err != nil {
|
||||
return err
|
||||
}
|
||||
case *rsa.PublicKey:
|
||||
rsaKey = k
|
||||
default:
|
||||
if rsaKey, ok = key.(*rsa.PublicKey); !ok {
|
||||
return ErrInvalidKey
|
||||
}
|
||||
|
||||
|
@ -80,20 +73,13 @@ func (m *SigningMethodRSA) Verify(signingString, signature string, key interface
|
|||
}
|
||||
|
||||
// Implements the Sign method from SigningMethod
|
||||
// For this signing method, must be either a PEM encoded PKCS1 or PKCS8 RSA private key as
|
||||
// []byte, or an rsa.PrivateKey structure.
|
||||
// For this signing method, must be an rsa.PrivateKey structure.
|
||||
func (m *SigningMethodRSA) Sign(signingString string, key interface{}) (string, error) {
|
||||
var err error
|
||||
var rsaKey *rsa.PrivateKey
|
||||
var ok bool
|
||||
|
||||
switch k := key.(type) {
|
||||
case []byte:
|
||||
if rsaKey, err = ParseRSAPrivateKeyFromPEM(k); err != nil {
|
||||
return "", err
|
||||
}
|
||||
case *rsa.PrivateKey:
|
||||
rsaKey = k
|
||||
default:
|
||||
// Validate type of key
|
||||
if rsaKey, ok = key.(*rsa.PrivateKey); !ok {
|
||||
return "", ErrInvalidKey
|
||||
}
|
||||
|
||||
|
|
|
@ -45,7 +45,8 @@ var rsaTestData = []struct {
|
|||
}
|
||||
|
||||
func TestRSAVerify(t *testing.T) {
|
||||
key, _ := ioutil.ReadFile("test/sample_key.pub")
|
||||
keyData, _ := ioutil.ReadFile("test/sample_key.pub")
|
||||
key, _ := jwt.ParseRSAPublicKeyFromPEM(keyData)
|
||||
|
||||
for _, data := range rsaTestData {
|
||||
parts := strings.Split(data.tokenString, ".")
|
||||
|
@ -62,7 +63,8 @@ func TestRSAVerify(t *testing.T) {
|
|||
}
|
||||
|
||||
func TestRSASign(t *testing.T) {
|
||||
key, _ := ioutil.ReadFile("test/sample_key")
|
||||
keyData, _ := ioutil.ReadFile("test/sample_key")
|
||||
key, _ := jwt.ParseRSAPrivateKeyFromPEM(keyData)
|
||||
|
||||
for _, data := range rsaTestData {
|
||||
if data.valid {
|
||||
|
|
29
token.go
29
token.go
|
@ -24,19 +24,23 @@ type Token struct {
|
|||
Raw string // The raw token. Populated when you Parse a token
|
||||
Method SigningMethod // The signing method used or to be used
|
||||
Header map[string]interface{} // The first segment of the token
|
||||
Claims map[string]interface{} // The second segment of the token
|
||||
Claims Claims // The second segment of the token
|
||||
Signature string // The third segment of the token. Populated when you Parse a token
|
||||
Valid bool // Is the token valid? Populated when you Parse/Verify a token
|
||||
}
|
||||
|
||||
// Create a new Token. Takes a signing method
|
||||
func New(method SigningMethod) *Token {
|
||||
return NewWithClaims(method, MapClaims{})
|
||||
}
|
||||
|
||||
func NewWithClaims(method SigningMethod, claims Claims) *Token {
|
||||
return &Token{
|
||||
Header: map[string]interface{}{
|
||||
"typ": "JWT",
|
||||
"alg": method.Alg(),
|
||||
},
|
||||
Claims: make(map[string]interface{}),
|
||||
Claims: claims,
|
||||
Method: method,
|
||||
}
|
||||
}
|
||||
|
@ -62,16 +66,15 @@ func (t *Token) SigningString() (string, error) {
|
|||
var err error
|
||||
parts := make([]string, 2)
|
||||
for i, _ := range parts {
|
||||
var source map[string]interface{}
|
||||
if i == 0 {
|
||||
source = t.Header
|
||||
} else {
|
||||
source = t.Claims
|
||||
}
|
||||
|
||||
var jsonValue []byte
|
||||
if jsonValue, err = json.Marshal(source); err != nil {
|
||||
return "", err
|
||||
if i == 0 {
|
||||
if jsonValue, err = json.Marshal(t.Header); err != nil {
|
||||
return "", err
|
||||
}
|
||||
} else {
|
||||
if jsonValue, err = json.Marshal(t.Claims); err != nil {
|
||||
return "", err
|
||||
}
|
||||
}
|
||||
|
||||
parts[i] = EncodeSegment(jsonValue)
|
||||
|
@ -86,6 +89,10 @@ func Parse(tokenString string, keyFunc Keyfunc) (*Token, error) {
|
|||
return new(Parser).Parse(tokenString, keyFunc)
|
||||
}
|
||||
|
||||
func ParseWithClaims(tokenString string, keyFunc Keyfunc, claims Claims) (*Token, error) {
|
||||
return new(Parser).ParseWithClaims(tokenString, keyFunc, claims)
|
||||
}
|
||||
|
||||
// Encode JWT specific base64url encoding with padding stripped
|
||||
func EncodeSegment(seg []byte) string {
|
||||
return strings.TrimRight(base64.URLEncoding.EncodeToString(seg), "=")
|
||||
|
|
Loading…
Reference in New Issue