Documentation ¶
Index ¶
- Constants
- Variables
- func DecodeSegment(seg string) ([]byte, error)
- func EncodeSegment(seg []byte) string
- func ParseRSAPrivateKeyFromPEM(key []byte) (*rsa.PrivateKey, error)
- func ParseRSAPrivateKeyFromPEMWithPassword(key []byte, password string) (*rsa.PrivateKey, error)
- func ParseRSAPublicKeyFromPEM(key []byte) (*rsa.PublicKey, error)
- func RegisterSigningMethod(alg string, f func() SigningMethod)
- type Claims
- type Keyfunc
- type MapClaims
- func (m MapClaims) Valid() error
- func (m MapClaims) VerifyAudience(cmp string, req bool) bool
- func (m MapClaims) VerifyExpiresAt(cmp int64, req bool) bool
- func (m MapClaims) VerifyIssuedAt(cmp int64, req bool) bool
- func (m MapClaims) VerifyIssuer(cmp string, req bool) bool
- func (m MapClaims) VerifyNotBefore(cmp int64, req bool) bool
- type Parser
- type SigningMethod
- type SigningMethodHMAC
- type SigningMethodRSA
- type StandardClaims
- func (c StandardClaims) Valid() error
- func (c *StandardClaims) VerifyAudience(cmp string, req bool) bool
- func (c *StandardClaims) VerifyExpiresAt(cmp int64, req bool) bool
- func (c *StandardClaims) VerifyIssuedAt(cmp int64, req bool) bool
- func (c *StandardClaims) VerifyIssuer(cmp string, req bool) bool
- func (c *StandardClaims) VerifyNotBefore(cmp int64, req bool) bool
- type Token
- type ValidationError
Examples ¶
Constants ¶
const ( ValidationErrorMalformed uint32 = 1 << iota // Token is malformed ValidationErrorUnverifiable // Token could not be verified because of signing problems ValidationErrorSignatureInvalid // Signature validation failed // Standard Claim validation errors ValidationErrorAudience // AUD validation failed ValidationErrorExpired // EXP validation failed ValidationErrorIssuedAt // IAT validation failed ValidationErrorIssuer // ISS validation failed ValidationErrorNotValidYet // NBF validation failed ValidationErrorID // JTI validation failed ValidationErrorClaimsInvalid // Generic claims validation error )
The errors that might occur when parsing and validating a token
Variables ¶
var ( ErrInvalidKey = errors.New("key is invalid") ErrInvalidKeyType = errors.New("key is of invalid type") )
Error constants
var ( // ErrKeyMustBePEMEncoded : ErrKeyMustBePEMEncoded = errors.New("Invalid Key: Key must be PEM encoded PKCS1 or PKCS8 private key") // ErrNotRSAPrivateKey : ErrNotRSAPrivateKey = errors.New("Key is not a valid RSA private key") // ErrNotRSAPublicKey : ErrNotRSAPublicKey = errors.New("Key is not a valid RSA public key") )
var TimeFunc = time.Now
TimeFunc provides the current time when parsing token to validate "exp" claim (expiration time). You can override it to use another time value. This is useful for testing or if your server uses a different time zone than your tokens.
Functions ¶
func DecodeSegment ¶
DecodeSegment : Decode JWT specific base64url encoding with padding stripped
func EncodeSegment ¶
EncodeSegment : Encode JWT specific base64url encoding with padding stripped
func ParseRSAPrivateKeyFromPEM ¶
func ParseRSAPrivateKeyFromPEM(key []byte) (*rsa.PrivateKey, error)
ParseRSAPrivateKeyFromPEM : Parse PEM encoded PKCS1 or PKCS8 private key
func ParseRSAPrivateKeyFromPEMWithPassword ¶
func ParseRSAPrivateKeyFromPEMWithPassword(key []byte, password string) (*rsa.PrivateKey, error)
ParseRSAPrivateKeyFromPEMWithPassword : Parse PEM encoded PKCS1 or PKCS8 private key protected with password
func ParseRSAPublicKeyFromPEM ¶
ParseRSAPublicKeyFromPEM : Parse PEM encoded PKCS1 or PKCS8 public key
func RegisterSigningMethod ¶
func RegisterSigningMethod(alg string, f func() SigningMethod)
RegisterSigningMethod : Register the "alg" name and a factory function for signing method. This is typically done during init() in the method's implementation
Types ¶
type Claims ¶
type Claims interface {
Valid() error
}
Claims : 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 Keyfunc ¶
Keyfunc : Parse methods use this callback function to supply the key for verification. The function receives the parsed, but unverified Token. This allows you to use properties in the Header of the token (such as `kid`) to identify which key to use.
type MapClaims ¶
type MapClaims map[string]interface{}
MapClaims : Claims type that uses the map[string]interface{} for JSON decoding This is the default claims type if you don't supply one
func (MapClaims) Valid ¶
Valid : Validates time based claims "exp, iat, nbf". There is no accounting for clock skew. As well, if any of the above claims are not in the token, it will still be considered a valid claim.
func (MapClaims) VerifyAudience ¶
VerifyAudience : Compares the aud claim against cmp. If required is false, this method will return true if the value matches or is unset
func (MapClaims) VerifyExpiresAt ¶
VerifyExpiresAt : Compares the exp claim against cmp. If required is false, this method will return true if the value matches or is unset
func (MapClaims) VerifyIssuedAt ¶
VerifyIssuedAt : Compares the iat claim against cmp. If required is false, this method will return true if the value matches or is unset
func (MapClaims) VerifyIssuer ¶
VerifyIssuer : Compares the iss claim against cmp. If required is false, this method will return true if the value matches or is unset
type Parser ¶
type Parser struct { ValidMethods []string // If populated, only these methods will be considered valid UseJSONNumber bool // Use JSON Number format in JSON decoder SkipClaimsValidation bool // Skip claims validation during token parsing }
Parser :
func (*Parser) Parse ¶
Parse : Parse, validate, and return a token. keyFunc will receive the parsed token and should return the key for validating. If everything is kosher, err will be nil
func (*Parser) ParseUnverified ¶
func (p *Parser) ParseUnverified(tokenString string, claims Claims) (token *Token, parts []string, err error)
ParseUnverified : WARNING: Don't use this method unless you know what you're doing
This method parses the token but doesn't validate the signature. It's only ever useful in cases where you know the signature is valid (because it has been checked previously in the stack) and you want to extract values from it.
type SigningMethod ¶
type SigningMethod interface { Verify(signingString, signature string, key interface{}) error // Returns nil if signature is valid Sign(signingString string, key interface{}) (string, error) // Returns encoded signature or error Alg() string // returns the alg identifier for this method (example: 'HS256') }
SigningMethod : Implement SigningMethod to add new methods for signing or verifying tokens.
func GetSigningMethod ¶
func GetSigningMethod(alg string) (method SigningMethod)
GetSigningMethod : Get a signing method from an "alg" string
type SigningMethodHMAC ¶
SigningMethodHMAC : Implements the HMAC-SHA family of signing methods signing methods Expects key type of []byte for both signing and validation
var ( SigningMethodHS256 *SigningMethodHMAC SigningMethodHS384 *SigningMethodHMAC SigningMethodHS512 *SigningMethodHMAC ErrSignatureInvalid = errors.New("signature is invalid") )
Specific instances for HS256 and company
func (*SigningMethodHMAC) Sign ¶
func (m *SigningMethodHMAC) Sign(signingString string, key interface{}) (string, error)
Sign : Implements the Sign method from SigningMethod for this signing method. Key must be []byte
func (*SigningMethodHMAC) Verify ¶
func (m *SigningMethodHMAC) Verify(signingString, signature string, key interface{}) error
Verify the signature of HSXXX tokens. Returns nil if the signature is valid.
type SigningMethodRSA ¶
SigningMethodRSA : Implements the RSA family of signing methods signing methods Expects *rsa.PrivateKey for signing and *rsa.PublicKey for validation
var ( SigningMethodRS256 *SigningMethodRSA SigningMethodRS384 *SigningMethodRSA SigningMethodRS512 *SigningMethodRSA )
Specific instances for RS256 and company
func (*SigningMethodRSA) Sign ¶
func (m *SigningMethodRSA) Sign(signingString string, key interface{}) (string, error)
Sign : Implements the Sign method from SigningMethod For this signing method, must be an *rsa.PrivateKey structure.
func (*SigningMethodRSA) Verify ¶
func (m *SigningMethodRSA) Verify(signingString, signature string, key interface{}) error
Verify : Implements the Verify method from SigningMethod For this signing method, must be an *rsa.PublicKey structure.
type StandardClaims ¶
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"` }
StandardClaims : Structured version of Claims Section, as referenced at https://tools.ietf.org/html/rfc7519#section-4.1 See examples for how to use this with your own claim types
func (StandardClaims) Valid ¶
func (c StandardClaims) Valid() error
Valid : Validates time based claims "exp, iat, nbf". There is no accounting for clock skew. As well, if any of the above claims are not in the token, it will still be considered a valid claim.
func (*StandardClaims) VerifyAudience ¶
func (c *StandardClaims) VerifyAudience(cmp string, req bool) bool
VerifyAudience : Compares the aud claim against cmp. If required is false, this method will return true if the value matches or is unset
func (*StandardClaims) VerifyExpiresAt ¶
func (c *StandardClaims) VerifyExpiresAt(cmp int64, req bool) bool
VerifyExpiresAt : Compares the exp claim against cmp. If required is false, this method will return true if the value matches or is unset
func (*StandardClaims) VerifyIssuedAt ¶
func (c *StandardClaims) VerifyIssuedAt(cmp int64, req bool) bool
VerifyIssuedAt : Compares the iat claim against cmp. If required is false, this method will return true if the value matches or is unset
func (*StandardClaims) VerifyIssuer ¶
func (c *StandardClaims) VerifyIssuer(cmp string, req bool) bool
VerifyIssuer : Compares the iss claim against cmp. If required is false, this method will return true if the value matches or is unset
func (*StandardClaims) VerifyNotBefore ¶
func (c *StandardClaims) VerifyNotBefore(cmp int64, req bool) bool
VerifyNotBefore : Compares the nbf claim against cmp. If required is false, this method will return true if the value matches or is unset
type Token ¶
type Token struct { Raw string // The raw token. Populated when you Parse a token Method SigningMethod // The signing method used or to be used Header map[string]interface{} // The first segment of the token Claims Claims // The second segment of the token Signature string // The third segment of the token. Populated when you Parse a token Valid bool // Is the token valid? Populated when you Parse/Verify a token }
Token : A JWT Token. Different fields will be used depending on whether you're creating or parsing/verifying a token.
func New ¶
func New(method SigningMethod) *Token
New : Create a new Token. Takes a signing method
Example (Hmac) ¶
Example creating, signing, and encoding a JWT token using the HMAC signing method
// Create a new token object, specifying signing method and the claims // you would like it to contain. token := NewWithClaims(SigningMethodHS256, MapClaims{ "foo": "bar", "nbf": time.Date(2015, 10, 10, 12, 0, 0, 0, time.UTC).Unix(), }) // Sign and get the complete encoded token as a string using the secret tokenString, err := token.SignedString(hmacSampleSecret) fmt.Println(tokenString, err)
Output: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIiLCJuYmYiOjE0NDQ0Nzg0MDB9.u1riaD1rW97opCoAuRCTy4w58Br-Zk-bh7vLiRIsrpU <nil>
func NewWithClaims ¶
func NewWithClaims(method SigningMethod, claims Claims) *Token
NewWithClaims :
Example (CustomClaimsType) ¶
Example creating a token using a custom claims type. The StandardClaim is embedded in the custom type to allow for easy encoding, parsing and validation of standard claims.
mySigningKey := []byte("AllYourBase") type MyCustomClaims struct { Foo string `json:"foo"` StandardClaims } // Create the Claims claims := MyCustomClaims{ "bar", StandardClaims{ ExpiresAt: 15000, Issuer: "test", }, } token := NewWithClaims(SigningMethodHS256, claims) ss, err := token.SignedString(mySigningKey) fmt.Printf("%v %v", ss, err)
Output: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIiLCJleHAiOjE1MDAwLCJpc3MiOiJ0ZXN0In0.HE7fK0xOQwFEr4WDgRWj4teRPZ6i3GLwD5YCm6Pwu_c <nil>
Example (StandardClaims) ¶
Example (atypical) using the StandardClaims type by itself to parse a token. The StandardClaims type is designed to be embedded into your custom types to provide standard validation features. You can use it alone, but there's no way to retrieve other fields after parsing. See the CustomClaimsType example for intended usage.
mySigningKey := []byte("AllYourBase") // Create the Claims claims := &StandardClaims{ ExpiresAt: 15000, Issuer: "test", } token := NewWithClaims(SigningMethodHS256, claims) ss, err := token.SignedString(mySigningKey) fmt.Printf("%v %v", ss, err)
Output: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1MDAwLCJpc3MiOiJ0ZXN0In0.QsODzZu3lUZMVdhbO76u3Jv02iYCvEHcYVUI1kOWEU0 <nil>
func Parse ¶
Parse : Parse, validate, and return a token. keyFunc will receive the parsed token and should return the key for validating. If everything is kosher, err will be nil
Example (ErrorChecking) ¶
An example of parsing the error types using bitfield checks
// Token from another example. This token is expired var tokenString = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIiLCJleHAiOjE1MDAwLCJpc3MiOiJ0ZXN0In0.HE7fK0xOQwFEr4WDgRWj4teRPZ6i3GLwD5YCm6Pwu_c" token, err := Parse(tokenString, func(token *Token) (interface{}, error) { return []byte("AllYourBase"), nil }) if token.Valid { fmt.Println("You look nice today") } else if ve, ok := err.(*ValidationError); ok { if ve.Errors&ValidationErrorMalformed != 0 { fmt.Println("That's not even a token") } else if ve.Errors&(ValidationErrorExpired|ValidationErrorNotValidYet) != 0 { // Token is either expired or not active yet fmt.Println("Timing is everything") } else { fmt.Println("Couldn't handle this token:", err) } } else { fmt.Println("Couldn't handle this token:", err) }
Output: Timing is everything
Example (Hmac) ¶
Example parsing and validating a token using the HMAC signing method
// sample token string taken from the New example tokenString := "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIiLCJuYmYiOjE0NDQ0Nzg0MDB9.u1riaD1rW97opCoAuRCTy4w58Br-Zk-bh7vLiRIsrpU" // Parse takes the token string and a function for looking up the key. The latter is especially // useful if you use multiple keys for your application. The standard is to use 'kid' in the // head of the token to identify which key to use, but the parsed token (head and claims) is provided // to the callback, providing flexibility. token, err := Parse(tokenString, func(token *Token) (interface{}, error) { // Don't forget to validate the alg is what you expect: if _, ok := token.Method.(*SigningMethodHMAC); !ok { return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"]) } // hmacSampleSecret is a []byte containing your secret, e.g. []byte("my_secret_key") return hmacSampleSecret, nil }) if claims, ok := token.Claims.(MapClaims); ok && token.Valid { fmt.Println(claims["foo"], claims["nbf"]) } else { fmt.Println(err) }
Output: bar 1.4444784e+09
func ParseWithClaims ¶
ParseWithClaims :
Example (CustomClaimsType) ¶
Example creating a token using a custom claims type. The StandardClaim is embedded in the custom type to allow for easy encoding, parsing and validation of standard claims.
tokenString := "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIiLCJleHAiOjE1MDAwLCJpc3MiOiJ0ZXN0In0.HE7fK0xOQwFEr4WDgRWj4teRPZ6i3GLwD5YCm6Pwu_c" type MyCustomClaims struct { Foo string `json:"foo"` StandardClaims } // sample token is expired. override time so it parses as valid at(time.Unix(0, 0), func() { token, err := ParseWithClaims(tokenString, &MyCustomClaims{}, func(token *Token) (interface{}, error) { return []byte("AllYourBase"), nil }) if claims, ok := token.Claims.(*MyCustomClaims); ok && token.Valid { fmt.Printf("%v %v", claims.Foo, claims.StandardClaims.ExpiresAt) } else { fmt.Println(err) } })
Output: bar 15000
func (*Token) SignedString ¶
SignedString : Get the complete, signed token
func (*Token) SigningString ¶
SigningString : Generate the signing string. This is the most expensive part of the whole deal. Unless you need this for something special, just go straight for the SignedString.
type ValidationError ¶
type ValidationError struct { Inner error // stores the error returned by external dependencies, i.e.: KeyFunc Errors uint32 // bitfield. see ValidationError... constants // contains filtered or unexported fields }
ValidationError : The error from Parse if token is not valid
func NewValidationError ¶
func NewValidationError(errorText string, errorFlags uint32) *ValidationError
NewValidationError : Helper for constructing a ValidationError with a string error message
func (ValidationError) Error ¶
func (e ValidationError) Error() string
Error : Validation error is an error type