Merging changes from master
This commit is contained in:
commit
93dfa67039
|
@ -47,3 +47,8 @@ Vagrantfile
|
|||
.DS_Store
|
||||
.idea
|
||||
|
||||
dist/*
|
||||
|
||||
# Editor backups
|
||||
*~
|
||||
*.sw[a-z]
|
||||
|
|
|
@ -213,8 +213,12 @@
|
|||
"Rev": "9eae18c3681ae3d3c677ac2b80a8fe57de45fc09"
|
||||
},
|
||||
{
|
||||
"ImportPath": "gopkg.in/inf.v0",
|
||||
"Rev": "c85f1217d51339c0fa3a498cc8b2075de695dae6"
|
||||
}
|
||||
"ImportPath": "gopkg.in/inf.v0",
|
||||
"Rev": "c85f1217d51339c0fa3a498cc8b2075de695dae6"
|
||||
},
|
||||
{
|
||||
"ImportPath": "github.com/dgrijalva/jwt-go",
|
||||
"Rev": "e5cb38552fb8426fe9f0f2b3bc8408f238b97b87"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
|
|
@ -0,0 +1,5 @@
|
|||
language: go
|
||||
|
||||
go:
|
||||
- 1.3.3
|
||||
- 1.4.2
|
|
@ -0,0 +1,8 @@
|
|||
Copyright (c) 2012 Dave Grijalva
|
||||
|
||||
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:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
||||
|
||||
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.
|
||||
|
|
@ -0,0 +1,63 @@
|
|||
A [go](http://www.golang.org) (or 'golang' for search engine friendliness) implementation of [JSON Web Tokens](http://self-issued.info/docs/draft-jones-json-web-token.html)
|
||||
|
||||
[![Build Status](https://travis-ci.org/dgrijalva/jwt-go.svg?branch=master)](https://travis-ci.org/dgrijalva/jwt-go)
|
||||
|
||||
**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.
|
||||
|
||||
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.
|
||||
|
||||
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-jones-json-web-token.html) for information about reserved keys and the proper way to add your own.
|
||||
|
||||
## 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.
|
||||
|
||||
## Parse and Verify
|
||||
|
||||
Parsing and verifying tokens is pretty straight forward. You pass in the token and a function for looking up the key. This is done as a callback since you may need to parse the token to find out what signing method and key was used.
|
||||
|
||||
```go
|
||||
token, err := jwt.Parse(myToken, func(token *jwt.Token) (interface{}, error) {
|
||||
// Don't forget to validate the alg is what you expect:
|
||||
if _, ok := token.Method.(*jwt.SigningMethodRSA); !ok {
|
||||
return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
|
||||
}
|
||||
return myLookupKey(token.Header["kid"])
|
||||
})
|
||||
|
||||
if err == nil && token.Valid {
|
||||
deliverGoodness("!")
|
||||
} else {
|
||||
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()
|
||||
// Sign and get the complete encoded token as a string
|
||||
tokenString, err := token.SignedString(mySigningKey)
|
||||
```
|
||||
|
||||
## Project Status & Versioning
|
||||
|
||||
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).
|
||||
|
||||
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).
|
||||
|
||||
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.
|
||||
|
||||
## More
|
||||
|
||||
Documentation can be found [on godoc.org](http://godoc.org/github.com/dgrijalva/jwt-go).
|
||||
|
||||
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. For a more http centric example, see [this gist](https://gist.github.com/cryptix/45c33ecf0ae54828e63b).
|
59
Godeps/_workspace/src/github.com/dgrijalva/jwt-go/VERSION_HISTORY.md
generated
vendored
Normal file
59
Godeps/_workspace/src/github.com/dgrijalva/jwt-go/VERSION_HISTORY.md
generated
vendored
Normal file
|
@ -0,0 +1,59 @@
|
|||
## `jwt-go` Version History
|
||||
|
||||
#### 2.3.0
|
||||
|
||||
* Added support for ECDSA signing methods
|
||||
* Added support for RSA PSS signing methods (requires go v1.4)
|
||||
|
||||
#### 2.2.0
|
||||
|
||||
* Gracefully handle a `nil` `Keyfunc` being passed to `Parse`. Result will now be the parsed token and an error, instead of a panic.
|
||||
|
||||
#### 2.1.0
|
||||
|
||||
Backwards compatible API change that was missed in 2.0.0.
|
||||
|
||||
* The `SignedString` method on `Token` now takes `interface{}` instead of `[]byte`
|
||||
|
||||
#### 2.0.0
|
||||
|
||||
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.
|
||||
|
||||
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`.
|
||||
|
||||
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`.
|
||||
|
||||
* **Compatibility Breaking Changes**
|
||||
* `SigningMethodHS256` is now `*SigningMethodHMAC` instead of `type struct`
|
||||
* `SigningMethodRS256` is now `*SigningMethodRSA` instead of `type struct`
|
||||
* `KeyFunc` now returns `interface{}` instead of `[]byte`
|
||||
* `SigningMethod.Sign` now takes `interface{}` instead of `[]byte` for the key
|
||||
* `SigningMethod.Verify` now takes `interface{}` instead of `[]byte` for the key
|
||||
* Renamed type `SigningMethodHS256` to `SigningMethodHMAC`. Specific sizes are now just instances of this type.
|
||||
* Added public package global `SigningMethodHS256`
|
||||
* Added public package global `SigningMethodHS384`
|
||||
* Added public package global `SigningMethodHS512`
|
||||
* Renamed type `SigningMethodRS256` to `SigningMethodRSA`. Specific sizes are now just instances of this type.
|
||||
* Added public package global `SigningMethodRS256`
|
||||
* Added public package global `SigningMethodRS384`
|
||||
* Added public package global `SigningMethodRS512`
|
||||
* Moved sample private key for HMAC tests from an inline value to a file on disk. Value is unchanged.
|
||||
* Refactored the RSA implementation to be easier to read
|
||||
* Exposed helper methods `ParseRSAPrivateKeyFromPEM` and `ParseRSAPublicKeyFromPEM`
|
||||
|
||||
#### 1.0.2
|
||||
|
||||
* Fixed bug in parsing public keys from certificates
|
||||
* Added more tests around the parsing of keys for RS256
|
||||
* Code refactoring in RS256 implementation. No functional changes
|
||||
|
||||
#### 1.0.1
|
||||
|
||||
* Fixed panic if RS256 signing method was passed an invalid key
|
||||
|
||||
#### 1.0.0
|
||||
|
||||
* First versioned release
|
||||
* API stabilized
|
||||
* Supports creating, signing, parsing, and validating JWT tokens
|
||||
* Supports RS256 and HS256 signing methods
|
|
@ -0,0 +1,186 @@
|
|||
// A useful example app. You can use this to debug your tokens on the command line.
|
||||
// This is also a great place to look at how you might use this library.
|
||||
//
|
||||
// Example usage:
|
||||
// The following will create and sign a token, then verify it and output the original claims.
|
||||
// echo {\"foo\":\"bar\"} | bin/jwt -key test/sample_key -alg RS256 -sign - | bin/jwt -key test/sample_key.pub -verify -
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"flag"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"os"
|
||||
"regexp"
|
||||
|
||||
"github.com/dgrijalva/jwt-go"
|
||||
)
|
||||
|
||||
var (
|
||||
// Options
|
||||
flagAlg = flag.String("alg", "", "signing algorithm identifier")
|
||||
flagKey = flag.String("key", "", "path to key file or '-' to read from stdin")
|
||||
flagCompact = flag.Bool("compact", false, "output compact JSON")
|
||||
flagDebug = flag.Bool("debug", false, "print out all kinds of debug data")
|
||||
|
||||
// Modes - exactly one of these is required
|
||||
flagSign = flag.String("sign", "", "path to claims object to sign or '-' to read from stdin")
|
||||
flagVerify = flag.String("verify", "", "path to JWT token to verify or '-' to read from stdin")
|
||||
)
|
||||
|
||||
func main() {
|
||||
// Usage message if you ask for -help or if you mess up inputs.
|
||||
flag.Usage = func() {
|
||||
fmt.Fprintf(os.Stderr, "Usage of %s:\n", os.Args[0])
|
||||
fmt.Fprintf(os.Stderr, " One of the following flags is required: sign, verify\n")
|
||||
flag.PrintDefaults()
|
||||
}
|
||||
|
||||
// Parse command line options
|
||||
flag.Parse()
|
||||
|
||||
// Do the thing. If something goes wrong, print error to stderr
|
||||
// and exit with a non-zero status code
|
||||
if err := start(); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
// Figure out which thing to do and then do that
|
||||
func start() error {
|
||||
if *flagSign != "" {
|
||||
return signToken()
|
||||
} else if *flagVerify != "" {
|
||||
return verifyToken()
|
||||
} else {
|
||||
flag.Usage()
|
||||
return fmt.Errorf("None of the required flags are present. What do you want me to do?")
|
||||
}
|
||||
}
|
||||
|
||||
// Helper func: Read input from specified file or stdin
|
||||
func loadData(p string) ([]byte, error) {
|
||||
if p == "" {
|
||||
return nil, fmt.Errorf("No path specified")
|
||||
}
|
||||
|
||||
var rdr io.Reader
|
||||
if p == "-" {
|
||||
rdr = os.Stdin
|
||||
} else {
|
||||
if f, err := os.Open(p); err == nil {
|
||||
rdr = f
|
||||
defer f.Close()
|
||||
} else {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return ioutil.ReadAll(rdr)
|
||||
}
|
||||
|
||||
// Print a json object in accordance with the prophecy (or the command line options)
|
||||
func printJSON(j interface{}) error {
|
||||
var out []byte
|
||||
var err error
|
||||
|
||||
if *flagCompact == false {
|
||||
out, err = json.MarshalIndent(j, "", " ")
|
||||
} else {
|
||||
out, err = json.Marshal(j)
|
||||
}
|
||||
|
||||
if err == nil {
|
||||
fmt.Println(string(out))
|
||||
}
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
// Verify a token and output the claims. This is a great example
|
||||
// of how to verify and view a token.
|
||||
func verifyToken() error {
|
||||
// get the token
|
||||
tokData, err := loadData(*flagVerify)
|
||||
if err != nil {
|
||||
return fmt.Errorf("Couldn't read token: %v", err)
|
||||
}
|
||||
|
||||
// trim possible whitespace from token
|
||||
tokData = regexp.MustCompile(`\s*$`).ReplaceAll(tokData, []byte{})
|
||||
if *flagDebug {
|
||||
fmt.Fprintf(os.Stderr, "Token len: %v bytes\n", len(tokData))
|
||||
}
|
||||
|
||||
// Parse the token. Load the key from command line option
|
||||
token, err := jwt.Parse(string(tokData), func(t *jwt.Token) (interface{}, error) {
|
||||
return loadData(*flagKey)
|
||||
})
|
||||
|
||||
// Print some debug data
|
||||
if *flagDebug && token != nil {
|
||||
fmt.Fprintf(os.Stderr, "Header:\n%v\n", token.Header)
|
||||
fmt.Fprintf(os.Stderr, "Claims:\n%v\n", token.Claims)
|
||||
}
|
||||
|
||||
// Print an error if we can't parse for some reason
|
||||
if err != nil {
|
||||
return fmt.Errorf("Couldn't parse token: %v", err)
|
||||
}
|
||||
|
||||
// Is token invalid?
|
||||
if !token.Valid {
|
||||
return fmt.Errorf("Token is invalid")
|
||||
}
|
||||
|
||||
// Print the token details
|
||||
if err := printJSON(token.Claims); err != nil {
|
||||
return fmt.Errorf("Failed to output claims: %v", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Create, sign, and output a token. This is a great, simple example of
|
||||
// how to use this library to create and sign a token.
|
||||
func signToken() error {
|
||||
// get the token data from command line arguments
|
||||
tokData, err := loadData(*flagSign)
|
||||
if err != nil {
|
||||
return fmt.Errorf("Couldn't read token: %v", err)
|
||||
} else if *flagDebug {
|
||||
fmt.Fprintf(os.Stderr, "Token: %v bytes", len(tokData))
|
||||
}
|
||||
|
||||
// parse the JSON of the claims
|
||||
var claims map[string]interface{}
|
||||
if err := json.Unmarshal(tokData, &claims); err != nil {
|
||||
return fmt.Errorf("Couldn't parse claims JSON: %v", err)
|
||||
}
|
||||
|
||||
// get the key
|
||||
keyData, err := loadData(*flagKey)
|
||||
if err != nil {
|
||||
return fmt.Errorf("Couldn't read key: %v", err)
|
||||
}
|
||||
|
||||
// get the signing alg
|
||||
alg := jwt.GetSigningMethod(*flagAlg)
|
||||
if alg == nil {
|
||||
return fmt.Errorf("Couldn't find signing method: %v", *flagAlg)
|
||||
}
|
||||
|
||||
// create a new token
|
||||
token := jwt.New(alg)
|
||||
token.Claims = claims
|
||||
|
||||
if out, err := token.SignedString(keyData); err == nil {
|
||||
fmt.Println(out)
|
||||
} else {
|
||||
return fmt.Errorf("Error signing token: %v", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
|
@ -0,0 +1,4 @@
|
|||
// Package jwt is a Go implementation of JSON Web Tokens: http://self-issued.info/docs/draft-jones-json-web-token.html
|
||||
//
|
||||
// See README.md for more info.
|
||||
package jwt
|
|
@ -0,0 +1,136 @@
|
|||
package jwt
|
||||
|
||||
import (
|
||||
"crypto"
|
||||
"crypto/ecdsa"
|
||||
"crypto/rand"
|
||||
"encoding/asn1"
|
||||
"errors"
|
||||
"math/big"
|
||||
)
|
||||
|
||||
var (
|
||||
// Sadly this is missing from crypto/ecdsa compared to crypto/rsa
|
||||
ErrECDSAVerification = errors.New("crypto/ecdsa: verification error")
|
||||
)
|
||||
|
||||
// Implements the ECDSA family of signing methods signing methods
|
||||
type SigningMethodECDSA struct {
|
||||
Name string
|
||||
Hash crypto.Hash
|
||||
}
|
||||
|
||||
// Marshalling structure for r, s EC point
|
||||
type ECPoint struct {
|
||||
R *big.Int
|
||||
S *big.Int
|
||||
}
|
||||
|
||||
// Specific instances for EC256 and company
|
||||
var (
|
||||
SigningMethodES256 *SigningMethodECDSA
|
||||
SigningMethodES384 *SigningMethodECDSA
|
||||
SigningMethodES512 *SigningMethodECDSA
|
||||
)
|
||||
|
||||
func init() {
|
||||
// ES256
|
||||
SigningMethodES256 = &SigningMethodECDSA{"ES256", crypto.SHA256}
|
||||
RegisterSigningMethod(SigningMethodES256.Alg(), func() SigningMethod {
|
||||
return SigningMethodES256
|
||||
})
|
||||
|
||||
// ES384
|
||||
SigningMethodES384 = &SigningMethodECDSA{"ES384", crypto.SHA384}
|
||||
RegisterSigningMethod(SigningMethodES384.Alg(), func() SigningMethod {
|
||||
return SigningMethodES384
|
||||
})
|
||||
|
||||
// ES512
|
||||
SigningMethodES512 = &SigningMethodECDSA{"ES512", crypto.SHA512}
|
||||
RegisterSigningMethod(SigningMethodES512.Alg(), func() SigningMethod {
|
||||
return SigningMethodES512
|
||||
})
|
||||
}
|
||||
|
||||
func (m *SigningMethodECDSA) Alg() string {
|
||||
return m.Name
|
||||
}
|
||||
|
||||
// Implements the Verify method from SigningMethod
|
||||
// For this verify method, key must be an ecdsa.PublicKey struct
|
||||
func (m *SigningMethodECDSA) Verify(signingString, signature string, key interface{}) error {
|
||||
var err error
|
||||
|
||||
// Decode the signature
|
||||
var sig []byte
|
||||
if sig, err = DecodeSegment(signature); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Get the key
|
||||
var ecdsaKey *ecdsa.PublicKey
|
||||
switch k := key.(type) {
|
||||
case *ecdsa.PublicKey:
|
||||
ecdsaKey = k
|
||||
default:
|
||||
return ErrInvalidKey
|
||||
}
|
||||
|
||||
// Unmarshal asn1 ECPoint
|
||||
var ecpoint = new(ECPoint)
|
||||
if _, err := asn1.Unmarshal(sig, ecpoint); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Create hasher
|
||||
if !m.Hash.Available() {
|
||||
return ErrHashUnavailable
|
||||
}
|
||||
hasher := m.Hash.New()
|
||||
hasher.Write([]byte(signingString))
|
||||
|
||||
// Verify the signature
|
||||
if verifystatus := ecdsa.Verify(ecdsaKey, hasher.Sum(nil), ecpoint.R, ecpoint.S); verifystatus == true {
|
||||
return nil
|
||||
} else {
|
||||
return ErrECDSAVerification
|
||||
}
|
||||
}
|
||||
|
||||
// Implements the Sign method from SigningMethod
|
||||
// For this signing method, key must be an ecdsa.PrivateKey struct
|
||||
func (m *SigningMethodECDSA) Sign(signingString string, key interface{}) (string, error) {
|
||||
// Get the key
|
||||
var ecdsaKey *ecdsa.PrivateKey
|
||||
switch k := key.(type) {
|
||||
case *ecdsa.PrivateKey:
|
||||
ecdsaKey = k
|
||||
default:
|
||||
return "", ErrInvalidKey
|
||||
}
|
||||
|
||||
// Create the hasher
|
||||
if !m.Hash.Available() {
|
||||
return "", ErrHashUnavailable
|
||||
}
|
||||
|
||||
hasher := m.Hash.New()
|
||||
hasher.Write([]byte(signingString))
|
||||
|
||||
// Sign the string and return r, s
|
||||
if r, s, err := ecdsa.Sign(rand.Reader, ecdsaKey, hasher.Sum(nil)); err == nil {
|
||||
// asn1 marhsal r, s using ecPoint as the structure
|
||||
var ecpoint = new(ECPoint)
|
||||
ecpoint.R = r
|
||||
ecpoint.S = s
|
||||
|
||||
if signature, err := asn1.Marshal(*ecpoint); err != nil {
|
||||
return "", err
|
||||
} else {
|
||||
return EncodeSegment(signature), nil
|
||||
}
|
||||
} else {
|
||||
return "", err
|
||||
}
|
||||
}
|
|
@ -0,0 +1,100 @@
|
|||
package jwt_test
|
||||
|
||||
import (
|
||||
"crypto/ecdsa"
|
||||
"io/ioutil"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/dgrijalva/jwt-go"
|
||||
)
|
||||
|
||||
var ecdsaTestData = []struct {
|
||||
name string
|
||||
keys map[string]string
|
||||
tokenString string
|
||||
alg string
|
||||
claims map[string]interface{}
|
||||
valid bool
|
||||
}{
|
||||
{
|
||||
"Basic ES256",
|
||||
map[string]string{"private": "test/ec256-private.pem", "public": "test/ec256-public.pem"},
|
||||
"eyJhbGciOiJFUzI1NiIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIifQ.MEQCIHoSJnmGlPaVQDqacx_2XlXEhhqtWceVopjomc2PJLtdAiAUTeGPoNYxZw0z8mgOnnIcjoxRuNDVZvybRZF3wR1l8w",
|
||||
"ES256",
|
||||
map[string]interface{}{"foo": "bar"},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"Basic ES384",
|
||||
map[string]string{"private": "test/ec384-private.pem", "public": "test/ec384-public.pem"},
|
||||
"eyJhbGciOiJFUzM4NCIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIifQ.MGUCMQCHBr61FXDuFY9xUhyp8iWQAuBIaSgaf1z2j_8XrKcCfzTPzoSa3SZKq-m3L492xe8CMG3kafRMeuaN5Aw8ZJxmOLhkTo4D3-LaGzcaUWINvWvkwFMl7dMC863s0gov6xvXuA",
|
||||
"ES384",
|
||||
map[string]interface{}{"foo": "bar"},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"Basic ES512",
|
||||
map[string]string{"private": "test/ec512-private.pem", "public": "test/ec512-public.pem"},
|
||||
"eyJhbGciOiJFUzUxMiIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIifQ.MIGIAkIAmVKjdJE5lG1byOFgZZVTeNDRp6E7SNvUj0UrvpzoBH6nrleWVTcwfHzbwWuooNpPADDSFR_Ql3ze-Vwwi8hBqQsCQgHn-ZooL8zegkOVeEEsqd7WHWdhb8UekFCYw3X8JnNP-D3wvZQ1-tkkHakt5gZ2-xO29TxfSPun4ViGkMYa7Q4N-Q",
|
||||
"ES512",
|
||||
map[string]interface{}{"foo": "bar"},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"basic ES256 invalid: foo => bar",
|
||||
map[string]string{"private": "test/ec256-private.pem", "public": "test/ec256-public.pem"},
|
||||
"eyJhbGciOiJFUzI1NiIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIifQ.MEQCIHoSJnmGlPaVQDqacx_2XlXEhhqtWceVopjomc2PJLtdAiAUTeGPoNYxZw0z8mgOnnIcjoxRuNDVZvybRZF3wR1l8W",
|
||||
"ES256",
|
||||
map[string]interface{}{"foo": "bar"},
|
||||
false,
|
||||
},
|
||||
}
|
||||
|
||||
func TestECDSAVerify(t *testing.T) {
|
||||
for _, data := range ecdsaTestData {
|
||||
var err error
|
||||
|
||||
key, _ := ioutil.ReadFile(data.keys["public"])
|
||||
|
||||
var ecdsaKey *ecdsa.PublicKey
|
||||
if ecdsaKey, err = jwt.ParseECPublicKeyFromPEM(key); err != nil {
|
||||
t.Errorf("Unable to parse ECDSA public key: %v", err)
|
||||
}
|
||||
|
||||
parts := strings.Split(data.tokenString, ".")
|
||||
|
||||
method := jwt.GetSigningMethod(data.alg)
|
||||
err = method.Verify(strings.Join(parts[0:2], "."), parts[2], ecdsaKey)
|
||||
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 TestECDSASign(t *testing.T) {
|
||||
for _, data := range ecdsaTestData {
|
||||
var err error
|
||||
key, _ := ioutil.ReadFile(data.keys["private"])
|
||||
|
||||
var ecdsaKey *ecdsa.PrivateKey
|
||||
if ecdsaKey, err = jwt.ParseECPrivateKeyFromPEM(key); err != nil {
|
||||
t.Errorf("Unable to parse ECDSA private key: %v", err)
|
||||
}
|
||||
|
||||
if data.valid {
|
||||
parts := strings.Split(data.tokenString, ".")
|
||||
method := jwt.GetSigningMethod(data.alg)
|
||||
sig, err := method.Sign(strings.Join(parts[0:2], "."), ecdsaKey)
|
||||
if err != nil {
|
||||
t.Errorf("[%v] Error signing token: %v", data.name, err)
|
||||
}
|
||||
if sig == parts[2] {
|
||||
t.Errorf("[%v] Identical signatures\nbefore:\n%v\nafter:\n%v", data.name, parts[2], sig)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,67 @@
|
|||
package jwt
|
||||
|
||||
import (
|
||||
"crypto/ecdsa"
|
||||
"crypto/x509"
|
||||
"encoding/pem"
|
||||
"errors"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrNotECPublicKey = errors.New("Key is not a valid ECDSA public key")
|
||||
ErrNotECPrivateKey = errors.New("Key is not a valid ECDSA private key")
|
||||
)
|
||||
|
||||
// Parse PEM encoded Elliptic Curve Private Key Structure
|
||||
func ParseECPrivateKeyFromPEM(key []byte) (*ecdsa.PrivateKey, error) {
|
||||
var err error
|
||||
|
||||
// Parse PEM block
|
||||
var block *pem.Block
|
||||
if block, _ = pem.Decode(key); block == nil {
|
||||
return nil, ErrKeyMustBePEMEncoded
|
||||
}
|
||||
|
||||
// Parse the key
|
||||
var parsedKey interface{}
|
||||
if parsedKey, err = x509.ParseECPrivateKey(block.Bytes); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var pkey *ecdsa.PrivateKey
|
||||
var ok bool
|
||||
if pkey, ok = parsedKey.(*ecdsa.PrivateKey); !ok {
|
||||
return nil, ErrNotECPrivateKey
|
||||
}
|
||||
|
||||
return pkey, nil
|
||||
}
|
||||
|
||||
// Parse PEM encoded PKCS1 or PKCS8 public key
|
||||
func ParseECPublicKeyFromPEM(key []byte) (*ecdsa.PublicKey, error) {
|
||||
var err error
|
||||
|
||||
// Parse PEM block
|
||||
var block *pem.Block
|
||||
if block, _ = pem.Decode(key); block == nil {
|
||||
return nil, ErrKeyMustBePEMEncoded
|
||||
}
|
||||
|
||||
// Parse the key
|
||||
var parsedKey interface{}
|
||||
if parsedKey, err = x509.ParsePKIXPublicKey(block.Bytes); err != nil {
|
||||
if cert, err := x509.ParseCertificate(block.Bytes); err == nil {
|
||||
parsedKey = cert.PublicKey
|
||||
} else {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
var pkey *ecdsa.PublicKey
|
||||
var ok bool
|
||||
if pkey, ok = parsedKey.(*ecdsa.PublicKey); !ok {
|
||||
return nil, ErrNotECPublicKey
|
||||
}
|
||||
|
||||
return pkey, nil
|
||||
}
|
|
@ -0,0 +1,43 @@
|
|||
package jwt
|
||||
|
||||
import (
|
||||
"errors"
|
||||
)
|
||||
|
||||
// Error constants
|
||||
var (
|
||||
ErrInvalidKey = errors.New("key is invalid or of invalid type")
|
||||
ErrHashUnavailable = errors.New("the requested hash function is unavailable")
|
||||
ErrNoTokenInRequest = errors.New("no token present in request")
|
||||
)
|
||||
|
||||
// The errors that might occur when parsing and validating a token
|
||||
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
|
||||
)
|
||||
|
||||
// The error from Parse if token is not valid
|
||||
type ValidationError struct {
|
||||
err string
|
||||
Errors uint32 // bitfield. see ValidationError... constants
|
||||
}
|
||||
|
||||
// Validation error is an error type
|
||||
func (e ValidationError) Error() string {
|
||||
if e.err == "" {
|
||||
return "token is invalid"
|
||||
}
|
||||
return e.err
|
||||
}
|
||||
|
||||
// No errors
|
||||
func (e *ValidationError) valid() bool {
|
||||
if e.Errors > 0 {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
|
@ -0,0 +1,52 @@
|
|||
package jwt_test
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/dgrijalva/jwt-go"
|
||||
"time"
|
||||
)
|
||||
|
||||
func ExampleParse(myToken string, myLookupKey func(interface{}) (interface{}, error)) {
|
||||
token, err := jwt.Parse(myToken, func(token *jwt.Token) (interface{}, error) {
|
||||
return myLookupKey(token.Header["kid"])
|
||||
})
|
||||
|
||||
if err == nil && token.Valid {
|
||||
fmt.Println("Your token is valid. I like your style.")
|
||||
} else {
|
||||
fmt.Println("This token is terrible! I cannot accept this.")
|
||||
}
|
||||
}
|
||||
|
||||
func ExampleNew(mySigningKey []byte) (string, error) {
|
||||
// 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()
|
||||
// Sign and get the complete encoded token as a string
|
||||
tokenString, err := token.SignedString(mySigningKey)
|
||||
return tokenString, err
|
||||
}
|
||||
|
||||
func ExampleParse_errorChecking(myToken string, myLookupKey func(interface{}) (interface{}, error)) {
|
||||
token, err := jwt.Parse(myToken, func(token *jwt.Token) (interface{}, error) {
|
||||
return myLookupKey(token.Header["kid"])
|
||||
})
|
||||
|
||||
if token.Valid {
|
||||
fmt.Println("You look nice today")
|
||||
} else if ve, ok := err.(*jwt.ValidationError); ok {
|
||||
if ve.Errors&jwt.ValidationErrorMalformed != 0 {
|
||||
fmt.Println("That's not even a token")
|
||||
} else if ve.Errors&(jwt.ValidationErrorExpired|jwt.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)
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,84 @@
|
|||
package jwt
|
||||
|
||||
import (
|
||||
"crypto"
|
||||
"crypto/hmac"
|
||||
"errors"
|
||||
)
|
||||
|
||||
// Implements the HMAC-SHA family of signing methods signing methods
|
||||
type SigningMethodHMAC struct {
|
||||
Name string
|
||||
Hash crypto.Hash
|
||||
}
|
||||
|
||||
// Specific instances for HS256 and company
|
||||
var (
|
||||
SigningMethodHS256 *SigningMethodHMAC
|
||||
SigningMethodHS384 *SigningMethodHMAC
|
||||
SigningMethodHS512 *SigningMethodHMAC
|
||||
ErrSignatureInvalid = errors.New("signature is invalid")
|
||||
)
|
||||
|
||||
func init() {
|
||||
// HS256
|
||||
SigningMethodHS256 = &SigningMethodHMAC{"HS256", crypto.SHA256}
|
||||
RegisterSigningMethod(SigningMethodHS256.Alg(), func() SigningMethod {
|
||||
return SigningMethodHS256
|
||||
})
|
||||
|
||||
// HS384
|
||||
SigningMethodHS384 = &SigningMethodHMAC{"HS384", crypto.SHA384}
|
||||
RegisterSigningMethod(SigningMethodHS384.Alg(), func() SigningMethod {
|
||||
return SigningMethodHS384
|
||||
})
|
||||
|
||||
// HS512
|
||||
SigningMethodHS512 = &SigningMethodHMAC{"HS512", crypto.SHA512}
|
||||
RegisterSigningMethod(SigningMethodHS512.Alg(), func() SigningMethod {
|
||||
return SigningMethodHS512
|
||||
})
|
||||
}
|
||||
|
||||
func (m *SigningMethodHMAC) Alg() string {
|
||||
return m.Name
|
||||
}
|
||||
|
||||
func (m *SigningMethodHMAC) Verify(signingString, signature string, key interface{}) error {
|
||||
if keyBytes, ok := key.([]byte); ok {
|
||||
var sig []byte
|
||||
var err error
|
||||
if sig, err = DecodeSegment(signature); err == nil {
|
||||
if !m.Hash.Available() {
|
||||
return ErrHashUnavailable
|
||||
}
|
||||
|
||||
hasher := hmac.New(m.Hash.New, keyBytes)
|
||||
hasher.Write([]byte(signingString))
|
||||
|
||||
if !hmac.Equal(sig, hasher.Sum(nil)) {
|
||||
err = ErrSignatureInvalid
|
||||
}
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
return ErrInvalidKey
|
||||
}
|
||||
|
||||
// Implements the Sign method from SigningMethod for this signing method.
|
||||
// Key must be []byte
|
||||
func (m *SigningMethodHMAC) Sign(signingString string, key interface{}) (string, error) {
|
||||
if keyBytes, ok := key.([]byte); ok {
|
||||
if !m.Hash.Available() {
|
||||
return "", ErrHashUnavailable
|
||||
}
|
||||
|
||||
hasher := hmac.New(m.Hash.New, keyBytes)
|
||||
hasher.Write([]byte(signingString))
|
||||
|
||||
return EncodeSegment(hasher.Sum(nil)), nil
|
||||
}
|
||||
|
||||
return "", ErrInvalidKey
|
||||
}
|
|
@ -0,0 +1,91 @@
|
|||
package jwt_test
|
||||
|
||||
import (
|
||||
"github.com/dgrijalva/jwt-go"
|
||||
"io/ioutil"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
var hmacTestData = []struct {
|
||||
name string
|
||||
tokenString string
|
||||
alg string
|
||||
claims map[string]interface{}
|
||||
valid bool
|
||||
}{
|
||||
{
|
||||
"web sample",
|
||||
"eyJ0eXAiOiJKV1QiLA0KICJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJqb2UiLA0KICJleHAiOjEzMDA4MTkzODAsDQogImh0dHA6Ly9leGFtcGxlLmNvbS9pc19yb290Ijp0cnVlfQ.dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk",
|
||||
"HS256",
|
||||
map[string]interface{}{"iss": "joe", "exp": 1300819380, "http://example.com/is_root": true},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"HS384",
|
||||
"eyJhbGciOiJIUzM4NCIsInR5cCI6IkpXVCJ9.eyJleHAiOjEuMzAwODE5MzhlKzA5LCJodHRwOi8vZXhhbXBsZS5jb20vaXNfcm9vdCI6dHJ1ZSwiaXNzIjoiam9lIn0.KWZEuOD5lbBxZ34g7F-SlVLAQ_r5KApWNWlZIIMyQVz5Zs58a7XdNzj5_0EcNoOy",
|
||||
"HS384",
|
||||
map[string]interface{}{"iss": "joe", "exp": 1300819380, "http://example.com/is_root": true},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"HS512",
|
||||
"eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJleHAiOjEuMzAwODE5MzhlKzA5LCJodHRwOi8vZXhhbXBsZS5jb20vaXNfcm9vdCI6dHJ1ZSwiaXNzIjoiam9lIn0.CN7YijRX6Aw1n2jyI2Id1w90ja-DEMYiWixhYCyHnrZ1VfJRaFQz1bEbjjA5Fn4CLYaUG432dEYmSbS4Saokmw",
|
||||
"HS512",
|
||||
map[string]interface{}{"iss": "joe", "exp": 1300819380, "http://example.com/is_root": true},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"web sample: invalid",
|
||||
"eyJ0eXAiOiJKV1QiLA0KICJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJqb2UiLA0KICJleHAiOjEzMDA4MTkzODAsDQogImh0dHA6Ly9leGFtcGxlLmNvbS9pc19yb290Ijp0cnVlfQ.dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXo",
|
||||
"HS256",
|
||||
map[string]interface{}{"iss": "joe", "exp": 1300819380, "http://example.com/is_root": true},
|
||||
false,
|
||||
},
|
||||
}
|
||||
|
||||
// Sample data from http://tools.ietf.org/html/draft-jones-json-web-signature-04#appendix-A.1
|
||||
var hmacTestKey, _ = ioutil.ReadFile("test/hmacTestKey")
|
||||
|
||||
func TestHMACVerify(t *testing.T) {
|
||||
for _, data := range hmacTestData {
|
||||
parts := strings.Split(data.tokenString, ".")
|
||||
|
||||
method := jwt.GetSigningMethod(data.alg)
|
||||
err := method.Verify(strings.Join(parts[0:2], "."), parts[2], hmacTestKey)
|
||||
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 TestHMACSign(t *testing.T) {
|
||||
for _, data := range hmacTestData {
|
||||
if data.valid {
|
||||
parts := strings.Split(data.tokenString, ".")
|
||||
method := jwt.GetSigningMethod(data.alg)
|
||||
sig, err := method.Sign(strings.Join(parts[0:2], "."), hmacTestKey)
|
||||
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])
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkHS256Signing(b *testing.B) {
|
||||
benchmarkSigning(b, jwt.SigningMethodHS256, hmacTestKey)
|
||||
}
|
||||
|
||||
func BenchmarkHS384Signing(b *testing.B) {
|
||||
benchmarkSigning(b, jwt.SigningMethodHS384, hmacTestKey)
|
||||
}
|
||||
|
||||
func BenchmarkHS512Signing(b *testing.B) {
|
||||
benchmarkSigning(b, jwt.SigningMethodHS512, hmacTestKey)
|
||||
}
|
|
@ -0,0 +1,198 @@
|
|||
package jwt
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// 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.
|
||||
var TimeFunc = time.Now
|
||||
|
||||
// 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 propries in the
|
||||
// Header of the token (such as `kid`) to identify which key to use.
|
||||
type Keyfunc func(*Token) (interface{}, error)
|
||||
|
||||
// A JWT Token. Different fields will be used depending on whether you're
|
||||
// creating or parsing/verifying a 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 map[string]interface{} // 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 &Token{
|
||||
Header: map[string]interface{}{
|
||||
"typ": "JWT",
|
||||
"alg": method.Alg(),
|
||||
},
|
||||
Claims: make(map[string]interface{}),
|
||||
Method: method,
|
||||
}
|
||||
}
|
||||
|
||||
// Get the complete, signed token
|
||||
func (t *Token) SignedString(key interface{}) (string, error) {
|
||||
var sig, sstr string
|
||||
var err error
|
||||
if sstr, err = t.SigningString(); err != nil {
|
||||
return "", err
|
||||
}
|
||||
if sig, err = t.Method.Sign(sstr, key); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return strings.Join([]string{sstr, sig}, "."), nil
|
||||
}
|
||||
|
||||
// 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.
|
||||
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
|
||||
}
|
||||
|
||||
parts[i] = EncodeSegment(jsonValue)
|
||||
}
|
||||
return strings.Join(parts, "."), nil
|
||||
}
|
||||
|
||||
// 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 Parse(tokenString string, keyFunc Keyfunc) (*Token, error) {
|
||||
parts := strings.Split(tokenString, ".")
|
||||
if len(parts) != 3 {
|
||||
return nil, &ValidationError{err: "token contains an invalid number of segments", Errors: ValidationErrorMalformed}
|
||||
}
|
||||
|
||||
var err error
|
||||
token := &Token{Raw: tokenString}
|
||||
// parse Header
|
||||
var headerBytes []byte
|
||||
if headerBytes, err = DecodeSegment(parts[0]); err != nil {
|
||||
return token, &ValidationError{err: err.Error(), Errors: ValidationErrorMalformed}
|
||||
}
|
||||
if err = json.Unmarshal(headerBytes, &token.Header); err != nil {
|
||||
return token, &ValidationError{err: err.Error(), Errors: ValidationErrorMalformed}
|
||||
}
|
||||
|
||||
// parse Claims
|
||||
var claimBytes []byte
|
||||
if claimBytes, err = DecodeSegment(parts[1]); err != nil {
|
||||
return token, &ValidationError{err: err.Error(), Errors: ValidationErrorMalformed}
|
||||
}
|
||||
if err = json.Unmarshal(claimBytes, &token.Claims); err != nil {
|
||||
return token, &ValidationError{err: err.Error(), Errors: ValidationErrorMalformed}
|
||||
}
|
||||
|
||||
// Lookup signature method
|
||||
if method, ok := token.Header["alg"].(string); ok {
|
||||
if token.Method = GetSigningMethod(method); token.Method == nil {
|
||||
return token, &ValidationError{err: "signing method (alg) is unavailable.", Errors: ValidationErrorUnverifiable}
|
||||
}
|
||||
} else {
|
||||
return token, &ValidationError{err: "signing method (alg) is unspecified.", Errors: ValidationErrorUnverifiable}
|
||||
}
|
||||
|
||||
// Lookup key
|
||||
var key interface{}
|
||||
if keyFunc == nil {
|
||||
// keyFunc was not provided. short circuiting validation
|
||||
return token, &ValidationError{err: "no Keyfunc was provided.", Errors: ValidationErrorUnverifiable}
|
||||
}
|
||||
if key, err = keyFunc(token); err != nil {
|
||||
// keyFunc returned an 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
|
||||
}
|
||||
}
|
||||
|
||||
// Perform validation
|
||||
if err = token.Method.Verify(strings.Join(parts[0:2], "."), parts[2], key); err != nil {
|
||||
vErr.err = err.Error()
|
||||
vErr.Errors |= ValidationErrorSignatureInvalid
|
||||
}
|
||||
|
||||
if vErr.valid() {
|
||||
token.Valid = true
|
||||
return token, nil
|
||||
}
|
||||
|
||||
return token, vErr
|
||||
}
|
||||
|
||||
// Try to find the token in an http.Request.
|
||||
// This method will call ParseMultipartForm if there's no token in the header.
|
||||
// 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 Keyfunc) (token *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 Parse(ah[7:], keyFunc)
|
||||
}
|
||||
}
|
||||
|
||||
// Look for "access_token" parameter
|
||||
req.ParseMultipartForm(10e6)
|
||||
if tokStr := req.Form.Get("access_token"); tokStr != "" {
|
||||
return Parse(tokStr, keyFunc)
|
||||
}
|
||||
|
||||
return nil, ErrNoTokenInRequest
|
||||
|
||||
}
|
||||
|
||||
// Encode JWT specific base64url encoding with padding stripped
|
||||
func EncodeSegment(seg []byte) string {
|
||||
return strings.TrimRight(base64.URLEncoding.EncodeToString(seg), "=")
|
||||
}
|
||||
|
||||
// Decode JWT specific base64url encoding with padding stripped
|
||||
func DecodeSegment(seg string) ([]byte, error) {
|
||||
if l := len(seg) % 4; l > 0 {
|
||||
seg += strings.Repeat("=", 4-l)
|
||||
}
|
||||
|
||||
return base64.URLEncoding.DecodeString(seg)
|
||||
}
|
|
@ -0,0 +1,187 @@
|
|||
package jwt_test
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/dgrijalva/jwt-go"
|
||||
"io/ioutil"
|
||||
"net/http"
|
||||
"reflect"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
var (
|
||||
jwtTestDefaultKey []byte
|
||||
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") }
|
||||
nilKeyFunc jwt.Keyfunc = nil
|
||||
)
|
||||
|
||||
var jwtTestData = []struct {
|
||||
name string
|
||||
tokenString string
|
||||
keyfunc jwt.Keyfunc
|
||||
claims map[string]interface{}
|
||||
valid bool
|
||||
errors uint32
|
||||
}{
|
||||
{
|
||||
"basic",
|
||||
"eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJmb28iOiJiYXIifQ.FhkiHkoESI_cG3NPigFrxEk9Z60_oXrOT2vGm9Pn6RDgYNovYORQmmA0zs1AoAOf09ly2Nx2YAg6ABqAYga1AcMFkJljwxTT5fYphTuqpWdy4BELeSYJx5Ty2gmr8e7RonuUztrdD5WfPqLKMm1Ozp_T6zALpRmwTIW0QPnaBXaQD90FplAg46Iy1UlDKr-Eupy0i5SLch5Q-p2ZpaL_5fnTIUDlxC3pWhJTyx_71qDI-mAA_5lE_VdroOeflG56sSmDxopPEG3bFlSu1eowyBfxtu0_CuVd-M42RU75Zc4Gsj6uV77MBtbMrf4_7M_NUTSgoIF3fRqxrj0NzihIBg",
|
||||
defaultKeyFunc,
|
||||
map[string]interface{}{"foo": "bar"},
|
||||
true,
|
||||
0,
|
||||
},
|
||||
{
|
||||
"basic expired",
|
||||
"", // autogen
|
||||
defaultKeyFunc,
|
||||
map[string]interface{}{"foo": "bar", "exp": float64(time.Now().Unix() - 100)},
|
||||
false,
|
||||
jwt.ValidationErrorExpired,
|
||||
},
|
||||
{
|
||||
"basic nbf",
|
||||
"", // autogen
|
||||
defaultKeyFunc,
|
||||
map[string]interface{}{"foo": "bar", "nbf": float64(time.Now().Unix() + 100)},
|
||||
false,
|
||||
jwt.ValidationErrorNotValidYet,
|
||||
},
|
||||
{
|
||||
"expired and nbf",
|
||||
"", // autogen
|
||||
defaultKeyFunc,
|
||||
map[string]interface{}{"foo": "bar", "nbf": float64(time.Now().Unix() + 100), "exp": float64(time.Now().Unix() - 100)},
|
||||
false,
|
||||
jwt.ValidationErrorNotValidYet | jwt.ValidationErrorExpired,
|
||||
},
|
||||
{
|
||||
"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"},
|
||||
false,
|
||||
jwt.ValidationErrorSignatureInvalid,
|
||||
},
|
||||
{
|
||||
"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"},
|
||||
false,
|
||||
jwt.ValidationErrorUnverifiable,
|
||||
},
|
||||
{
|
||||
"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"},
|
||||
false,
|
||||
jwt.ValidationErrorSignatureInvalid,
|
||||
},
|
||||
{
|
||||
"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"},
|
||||
false,
|
||||
jwt.ValidationErrorUnverifiable,
|
||||
},
|
||||
}
|
||||
|
||||
func init() {
|
||||
var e error
|
||||
if jwtTestDefaultKey, e = ioutil.ReadFile("test/sample_key.pub"); e != nil {
|
||||
panic(e)
|
||||
}
|
||||
}
|
||||
|
||||
func makeSample(c map[string]interface{}) string {
|
||||
key, e := ioutil.ReadFile("test/sample_key")
|
||||
if e != nil {
|
||||
panic(e.Error())
|
||||
}
|
||||
|
||||
token := jwt.New(jwt.SigningMethodRS256)
|
||||
token.Claims = c
|
||||
s, e := token.SignedString(key)
|
||||
|
||||
if e != nil {
|
||||
panic(e.Error())
|
||||
}
|
||||
|
||||
return s
|
||||
}
|
||||
|
||||
func TestJWT(t *testing.T) {
|
||||
for _, data := range jwtTestData {
|
||||
if data.tokenString == "" {
|
||||
data.tokenString = makeSample(data.claims)
|
||||
}
|
||||
token, err := jwt.Parse(data.tokenString, data.keyfunc)
|
||||
|
||||
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)
|
||||
} else {
|
||||
// compare the bitfield part of the error
|
||||
if err.(*jwt.ValidationError).Errors != data.errors {
|
||||
t.Errorf("[%v] Errors don't match expectation", data.name)
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseRequest(t *testing.T) {
|
||||
// Bearer token request
|
||||
for _, data := range jwtTestData {
|
||||
if data.tokenString == "" {
|
||||
data.tokenString = makeSample(data.claims)
|
||||
}
|
||||
|
||||
r, _ := http.NewRequest("GET", "/", nil)
|
||||
r.Header.Set("Authorization", fmt.Sprintf("Bearer %v", data.tokenString))
|
||||
token, err := jwt.ParseFromRequest(r, data.keyfunc)
|
||||
|
||||
if token == nil {
|
||||
t.Errorf("[%v] Token was not found: %v", data.name, err)
|
||||
continue
|
||||
}
|
||||
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: %v", data.name, err)
|
||||
}
|
||||
if !data.valid && err == nil {
|
||||
t.Errorf("[%v] Invalid token passed validation", data.name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Helper method for benchmarking various methods
|
||||
func benchmarkSigning(b *testing.B, method jwt.SigningMethod, key interface{}) {
|
||||
t := jwt.New(method)
|
||||
b.RunParallel(func(pb *testing.PB) {
|
||||
for pb.Next() {
|
||||
if _, err := t.SignedString(key); err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
}
|
|
@ -0,0 +1,114 @@
|
|||
package jwt
|
||||
|
||||
import (
|
||||
"crypto"
|
||||
"crypto/rand"
|
||||
"crypto/rsa"
|
||||
)
|
||||
|
||||
// Implements the RSA family of signing methods signing methods
|
||||
type SigningMethodRSA struct {
|
||||
Name string
|
||||
Hash crypto.Hash
|
||||
}
|
||||
|
||||
// Specific instances for RS256 and company
|
||||
var (
|
||||
SigningMethodRS256 *SigningMethodRSA
|
||||
SigningMethodRS384 *SigningMethodRSA
|
||||
SigningMethodRS512 *SigningMethodRSA
|
||||
)
|
||||
|
||||
func init() {
|
||||
// RS256
|
||||
SigningMethodRS256 = &SigningMethodRSA{"RS256", crypto.SHA256}
|
||||
RegisterSigningMethod(SigningMethodRS256.Alg(), func() SigningMethod {
|
||||
return SigningMethodRS256
|
||||
})
|
||||
|
||||
// RS384
|
||||
SigningMethodRS384 = &SigningMethodRSA{"RS384", crypto.SHA384}
|
||||
RegisterSigningMethod(SigningMethodRS384.Alg(), func() SigningMethod {
|
||||
return SigningMethodRS384
|
||||
})
|
||||
|
||||
// RS512
|
||||
SigningMethodRS512 = &SigningMethodRSA{"RS512", crypto.SHA512}
|
||||
RegisterSigningMethod(SigningMethodRS512.Alg(), func() SigningMethod {
|
||||
return SigningMethodRS512
|
||||
})
|
||||
}
|
||||
|
||||
func (m *SigningMethodRSA) Alg() string {
|
||||
return m.Name
|
||||
}
|
||||
|
||||
// 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.
|
||||
func (m *SigningMethodRSA) Verify(signingString, signature string, key interface{}) error {
|
||||
var err error
|
||||
|
||||
// Decode the signature
|
||||
var sig []byte
|
||||
if sig, err = DecodeSegment(signature); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var rsaKey *rsa.PublicKey
|
||||
|
||||
switch k := key.(type) {
|
||||
case []byte:
|
||||
if rsaKey, err = ParseRSAPublicKeyFromPEM(k); err != nil {
|
||||
return err
|
||||
}
|
||||
case *rsa.PublicKey:
|
||||
rsaKey = k
|
||||
default:
|
||||
return ErrInvalidKey
|
||||
}
|
||||
|
||||
// Create hasher
|
||||
if !m.Hash.Available() {
|
||||
return ErrHashUnavailable
|
||||
}
|
||||
hasher := m.Hash.New()
|
||||
hasher.Write([]byte(signingString))
|
||||
|
||||
// Verify the signature
|
||||
return rsa.VerifyPKCS1v15(rsaKey, m.Hash, hasher.Sum(nil), sig)
|
||||
}
|
||||
|
||||
// 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.
|
||||
func (m *SigningMethodRSA) Sign(signingString string, key interface{}) (string, error) {
|
||||
var err error
|
||||
var rsaKey *rsa.PrivateKey
|
||||
|
||||
switch k := key.(type) {
|
||||
case []byte:
|
||||
if rsaKey, err = ParseRSAPrivateKeyFromPEM(k); err != nil {
|
||||
return "", err
|
||||
}
|
||||
case *rsa.PrivateKey:
|
||||
rsaKey = k
|
||||
default:
|
||||
return "", ErrInvalidKey
|
||||
}
|
||||
|
||||
// Create the hasher
|
||||
if !m.Hash.Available() {
|
||||
return "", ErrHashUnavailable
|
||||
}
|
||||
|
||||
hasher := m.Hash.New()
|
||||
hasher.Write([]byte(signingString))
|
||||
|
||||
// Sign the string and return the encoded bytes
|
||||
if sigBytes, err := rsa.SignPKCS1v15(rand.Reader, rsaKey, m.Hash, hasher.Sum(nil)); err == nil {
|
||||
return EncodeSegment(sigBytes), nil
|
||||
} else {
|
||||
return "", err
|
||||
}
|
||||
}
|
|
@ -0,0 +1,126 @@
|
|||
// +build go1.4
|
||||
|
||||
package jwt
|
||||
|
||||
import (
|
||||
"crypto"
|
||||
"crypto/rand"
|
||||
"crypto/rsa"
|
||||
)
|
||||
|
||||
// Implements the RSAPSS family of signing methods signing methods
|
||||
type SigningMethodRSAPSS struct {
|
||||
*SigningMethodRSA
|
||||
Options *rsa.PSSOptions
|
||||
}
|
||||
|
||||
// Specific instances for RS/PS and company
|
||||
var (
|
||||
SigningMethodPS256 *SigningMethodRSAPSS
|
||||
SigningMethodPS384 *SigningMethodRSAPSS
|
||||
SigningMethodPS512 *SigningMethodRSAPSS
|
||||
)
|
||||
|
||||
func init() {
|
||||
// PS256
|
||||
SigningMethodPS256 = &SigningMethodRSAPSS{
|
||||
&SigningMethodRSA{
|
||||
Name: "PS256",
|
||||
Hash: crypto.SHA256,
|
||||
},
|
||||
&rsa.PSSOptions{
|
||||
SaltLength: rsa.PSSSaltLengthAuto,
|
||||
Hash: crypto.SHA256,
|
||||
},
|
||||
}
|
||||
RegisterSigningMethod(SigningMethodPS256.Alg(), func() SigningMethod {
|
||||
return SigningMethodPS256
|
||||
})
|
||||
|
||||
// PS384
|
||||
SigningMethodPS384 = &SigningMethodRSAPSS{
|
||||
&SigningMethodRSA{
|
||||
Name: "PS384",
|
||||
Hash: crypto.SHA384,
|
||||
},
|
||||
&rsa.PSSOptions{
|
||||
SaltLength: rsa.PSSSaltLengthAuto,
|
||||
Hash: crypto.SHA384,
|
||||
},
|
||||
}
|
||||
RegisterSigningMethod(SigningMethodPS384.Alg(), func() SigningMethod {
|
||||
return SigningMethodPS384
|
||||
})
|
||||
|
||||
// PS512
|
||||
SigningMethodPS512 = &SigningMethodRSAPSS{
|
||||
&SigningMethodRSA{
|
||||
Name: "PS512",
|
||||
Hash: crypto.SHA512,
|
||||
},
|
||||
&rsa.PSSOptions{
|
||||
SaltLength: rsa.PSSSaltLengthAuto,
|
||||
Hash: crypto.SHA512,
|
||||
},
|
||||
}
|
||||
RegisterSigningMethod(SigningMethodPS512.Alg(), func() SigningMethod {
|
||||
return SigningMethodPS512
|
||||
})
|
||||
}
|
||||
|
||||
// Implements the Verify method from SigningMethod
|
||||
// For this verify method, key must be an rsa.PrivateKey struct
|
||||
func (m *SigningMethodRSAPSS) Verify(signingString, signature string, key interface{}) error {
|
||||
var err error
|
||||
|
||||
// Decode the signature
|
||||
var sig []byte
|
||||
if sig, err = DecodeSegment(signature); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var rsaKey *rsa.PublicKey
|
||||
switch k := key.(type) {
|
||||
case *rsa.PublicKey:
|
||||
rsaKey = k
|
||||
default:
|
||||
return ErrInvalidKey
|
||||
}
|
||||
|
||||
// Create hasher
|
||||
if !m.Hash.Available() {
|
||||
return ErrHashUnavailable
|
||||
}
|
||||
hasher := m.Hash.New()
|
||||
hasher.Write([]byte(signingString))
|
||||
|
||||
return rsa.VerifyPSS(rsaKey, m.Hash, hasher.Sum(nil), sig, m.Options)
|
||||
}
|
||||
|
||||
// Implements the Sign method from SigningMethod
|
||||
// For this signing method, key must be an rsa.PublicKey struct
|
||||
func (m *SigningMethodRSAPSS) Sign(signingString string, key interface{}) (string, error) {
|
||||
var rsaKey *rsa.PrivateKey
|
||||
|
||||
switch k := key.(type) {
|
||||
case *rsa.PrivateKey:
|
||||
rsaKey = k
|
||||
default:
|
||||
return "", ErrInvalidKey
|
||||
}
|
||||
|
||||
// Create the hasher
|
||||
if !m.Hash.Available() {
|
||||
return "", ErrHashUnavailable
|
||||
}
|
||||
|
||||
hasher := m.Hash.New()
|
||||
hasher.Write([]byte(signingString))
|
||||
|
||||
// Sign the string and return the encoded bytes
|
||||
if sigBytes, err := rsa.SignPSS(rand.Reader, rsaKey, m.Hash, hasher.Sum(nil), m.Options); err == nil {
|
||||
return EncodeSegment(sigBytes), nil
|
||||
} else {
|
||||
return "", err
|
||||
}
|
||||
}
|
|
@ -0,0 +1,96 @@
|
|||
// +build go1.4
|
||||
|
||||
package jwt_test
|
||||
|
||||
import (
|
||||
"crypto/rsa"
|
||||
"io/ioutil"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/dgrijalva/jwt-go"
|
||||
)
|
||||
|
||||
var rsaPSSTestData = []struct {
|
||||
name string
|
||||
tokenString string
|
||||
alg string
|
||||
claims map[string]interface{}
|
||||
valid bool
|
||||
}{
|
||||
{
|
||||
"Basic PS256",
|
||||
"eyJhbGciOiJQUzI1NiIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIifQ.PPG4xyDVY8ffp4CcxofNmsTDXsrVG2npdQuibLhJbv4ClyPTUtR5giNSvuxo03kB6I8VXVr0Y9X7UxhJVEoJOmULAwRWaUsDnIewQa101cVhMa6iR8X37kfFoiZ6NkS-c7henVkkQWu2HtotkEtQvN5hFlk8IevXXPmvZlhQhwzB1sGzGYnoi1zOfuL98d3BIjUjtlwii5w6gYG2AEEzp7HnHCsb3jIwUPdq86Oe6hIFjtBwduIK90ca4UqzARpcfwxHwVLMpatKask00AgGVI0ysdk0BLMjmLutquD03XbThHScC2C2_Pp4cHWgMzvbgLU2RYYZcZRKr46QeNgz9w",
|
||||
"PS256",
|
||||
map[string]interface{}{"foo": "bar"},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"Basic PS384",
|
||||
"eyJhbGciOiJQUzM4NCIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIifQ.w7-qqgj97gK4fJsq_DCqdYQiylJjzWONvD0qWWWhqEOFk2P1eDULPnqHRnjgTXoO4HAw4YIWCsZPet7nR3Xxq4ZhMqvKW8b7KlfRTb9cH8zqFvzMmybQ4jv2hKc3bXYqVow3AoR7hN_CWXI3Dv6Kd2X5xhtxRHI6IL39oTVDUQ74LACe-9t4c3QRPuj6Pq1H4FAT2E2kW_0KOc6EQhCLWEhm2Z2__OZskDC8AiPpP8Kv4k2vB7l0IKQu8Pr4RcNBlqJdq8dA5D3hk5TLxP8V5nG1Ib80MOMMqoS3FQvSLyolFX-R_jZ3-zfq6Ebsqr0yEb0AH2CfsECF7935Pa0FKQ",
|
||||
"PS384",
|
||||
map[string]interface{}{"foo": "bar"},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"Basic PS512",
|
||||
"eyJhbGciOiJQUzUxMiIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIifQ.GX1HWGzFaJevuSLavqqFYaW8_TpvcjQ8KfC5fXiSDzSiT9UD9nB_ikSmDNyDILNdtjZLSvVKfXxZJqCfefxAtiozEDDdJthZ-F0uO4SPFHlGiXszvKeodh7BuTWRI2wL9-ZO4mFa8nq3GMeQAfo9cx11i7nfN8n2YNQ9SHGovG7_T_AvaMZB_jT6jkDHpwGR9mz7x1sycckEo6teLdHRnH_ZdlHlxqknmyTu8Odr5Xh0sJFOL8BepWbbvIIn-P161rRHHiDWFv6nhlHwZnVzjx7HQrWSGb6-s2cdLie9QL_8XaMcUpjLkfOMKkDOfHo6AvpL7Jbwi83Z2ZTHjJWB-A",
|
||||
"PS512",
|
||||
map[string]interface{}{"foo": "bar"},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"basic PS256 invalid: foo => bar",
|
||||
"eyJhbGciOiJQUzI1NiIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIifQ.PPG4xyDVY8ffp4CcxofNmsTDXsrVG2npdQuibLhJbv4ClyPTUtR5giNSvuxo03kB6I8VXVr0Y9X7UxhJVEoJOmULAwRWaUsDnIewQa101cVhMa6iR8X37kfFoiZ6NkS-c7henVkkQWu2HtotkEtQvN5hFlk8IevXXPmvZlhQhwzB1sGzGYnoi1zOfuL98d3BIjUjtlwii5w6gYG2AEEzp7HnHCsb3jIwUPdq86Oe6hIFjtBwduIK90ca4UqzARpcfwxHwVLMpatKask00AgGVI0ysdk0BLMjmLutquD03XbThHScC2C2_Pp4cHWgMzvbgLU2RYYZcZRKr46QeNgz9W",
|
||||
"PS256",
|
||||
map[string]interface{}{"foo": "bar"},
|
||||
false,
|
||||
},
|
||||
}
|
||||
|
||||
func TestRSAPSSVerify(t *testing.T) {
|
||||
var err error
|
||||
|
||||
key, _ := ioutil.ReadFile("test/sample_key.pub")
|
||||
var rsaPSSKey *rsa.PublicKey
|
||||
if rsaPSSKey, err = jwt.ParseRSAPublicKeyFromPEM(key); err != nil {
|
||||
t.Errorf("Unable to parse RSA public key: %v", err)
|
||||
}
|
||||
|
||||
for _, data := range rsaPSSTestData {
|
||||
parts := strings.Split(data.tokenString, ".")
|
||||
|
||||
method := jwt.GetSigningMethod(data.alg)
|
||||
err := method.Verify(strings.Join(parts[0:2], "."), parts[2], rsaPSSKey)
|
||||
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 TestRSAPSSSign(t *testing.T) {
|
||||
var err error
|
||||
|
||||
key, _ := ioutil.ReadFile("test/sample_key")
|
||||
var rsaPSSKey *rsa.PrivateKey
|
||||
if rsaPSSKey, err = jwt.ParseRSAPrivateKeyFromPEM(key); err != nil {
|
||||
t.Errorf("Unable to parse RSA private key: %v", err)
|
||||
}
|
||||
|
||||
for _, data := range rsaPSSTestData {
|
||||
if data.valid {
|
||||
parts := strings.Split(data.tokenString, ".")
|
||||
method := jwt.GetSigningMethod(data.alg)
|
||||
sig, err := method.Sign(strings.Join(parts[0:2], "."), rsaPSSKey)
|
||||
if err != nil {
|
||||
t.Errorf("[%v] Error signing token: %v", data.name, err)
|
||||
}
|
||||
if sig == parts[2] {
|
||||
t.Errorf("[%v] Signatures shouldn't match\nnew:\n%v\noriginal:\n%v", data.name, sig, parts[2])
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,174 @@
|
|||
package jwt_test
|
||||
|
||||
import (
|
||||
"github.com/dgrijalva/jwt-go"
|
||||
"io/ioutil"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
var rsaTestData = []struct {
|
||||
name string
|
||||
tokenString string
|
||||
alg string
|
||||
claims map[string]interface{}
|
||||
valid bool
|
||||
}{
|
||||
{
|
||||
"Basic RS256",
|
||||
"eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJmb28iOiJiYXIifQ.FhkiHkoESI_cG3NPigFrxEk9Z60_oXrOT2vGm9Pn6RDgYNovYORQmmA0zs1AoAOf09ly2Nx2YAg6ABqAYga1AcMFkJljwxTT5fYphTuqpWdy4BELeSYJx5Ty2gmr8e7RonuUztrdD5WfPqLKMm1Ozp_T6zALpRmwTIW0QPnaBXaQD90FplAg46Iy1UlDKr-Eupy0i5SLch5Q-p2ZpaL_5fnTIUDlxC3pWhJTyx_71qDI-mAA_5lE_VdroOeflG56sSmDxopPEG3bFlSu1eowyBfxtu0_CuVd-M42RU75Zc4Gsj6uV77MBtbMrf4_7M_NUTSgoIF3fRqxrj0NzihIBg",
|
||||
"RS256",
|
||||
map[string]interface{}{"foo": "bar"},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"Basic RS384",
|
||||
"eyJhbGciOiJSUzM4NCIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIifQ.W-jEzRfBigtCWsinvVVuldiuilzVdU5ty0MvpLaSaqK9PlAWWlDQ1VIQ_qSKzwL5IXaZkvZFJXT3yL3n7OUVu7zCNJzdwznbC8Z-b0z2lYvcklJYi2VOFRcGbJtXUqgjk2oGsiqUMUMOLP70TTefkpsgqDxbRh9CDUfpOJgW-dU7cmgaoswe3wjUAUi6B6G2YEaiuXC0XScQYSYVKIzgKXJV8Zw-7AN_DBUI4GkTpsvQ9fVVjZM9csQiEXhYekyrKu1nu_POpQonGd8yqkIyXPECNmmqH5jH4sFiF67XhD7_JpkvLziBpI-uh86evBUadmHhb9Otqw3uV3NTaXLzJw",
|
||||
"RS384",
|
||||
map[string]interface{}{"foo": "bar"},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"Basic RS512",
|
||||
"eyJhbGciOiJSUzUxMiIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIifQ.zBlLlmRrUxx4SJPUbV37Q1joRcI9EW13grnKduK3wtYKmDXbgDpF1cZ6B-2Jsm5RB8REmMiLpGms-EjXhgnyh2TSHE-9W2gA_jvshegLWtwRVDX40ODSkTb7OVuaWgiy9y7llvcknFBTIg-FnVPVpXMmeV_pvwQyhaz1SSwSPrDyxEmksz1hq7YONXhXPpGaNbMMeDTNP_1oj8DZaqTIL9TwV8_1wb2Odt_Fy58Ke2RVFijsOLdnyEAjt2n9Mxihu9i3PhNBkkxa2GbnXBfq3kzvZ_xxGGopLdHhJjcGWXO-NiwI9_tiu14NRv4L2xC0ItD9Yz68v2ZIZEp_DuzwRQ",
|
||||
"RS512",
|
||||
map[string]interface{}{"foo": "bar"},
|
||||
true,
|
||||
},
|
||||
{
|
||||
"basic invalid: foo => bar",
|
||||
"eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJmb28iOiJiYXIifQ.EhkiHkoESI_cG3NPigFrxEk9Z60_oXrOT2vGm9Pn6RDgYNovYORQmmA0zs1AoAOf09ly2Nx2YAg6ABqAYga1AcMFkJljwxTT5fYphTuqpWdy4BELeSYJx5Ty2gmr8e7RonuUztrdD5WfPqLKMm1Ozp_T6zALpRmwTIW0QPnaBXaQD90FplAg46Iy1UlDKr-Eupy0i5SLch5Q-p2ZpaL_5fnTIUDlxC3pWhJTyx_71qDI-mAA_5lE_VdroOeflG56sSmDxopPEG3bFlSu1eowyBfxtu0_CuVd-M42RU75Zc4Gsj6uV77MBtbMrf4_7M_NUTSgoIF3fRqxrj0NzihIBg",
|
||||
"RS256",
|
||||
map[string]interface{}{"foo": "bar"},
|
||||
false,
|
||||
},
|
||||
}
|
||||
|
||||
func TestRSAVerify(t *testing.T) {
|
||||
key, _ := ioutil.ReadFile("test/sample_key.pub")
|
||||
|
||||
for _, data := range rsaTestData {
|
||||
parts := strings.Split(data.tokenString, ".")
|
||||
|
||||
method := jwt.GetSigningMethod(data.alg)
|
||||
err := method.Verify(strings.Join(parts[0:2], "."), parts[2], 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 TestRSASign(t *testing.T) {
|
||||
key, _ := ioutil.ReadFile("test/sample_key")
|
||||
|
||||
for _, data := range rsaTestData {
|
||||
if data.valid {
|
||||
parts := strings.Split(data.tokenString, ".")
|
||||
method := jwt.GetSigningMethod(data.alg)
|
||||
sig, err := method.Sign(strings.Join(parts[0:2], "."), 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])
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestRSAVerifyWithPreParsedPrivateKey(t *testing.T) {
|
||||
key, _ := ioutil.ReadFile("test/sample_key.pub")
|
||||
parsedKey, err := jwt.ParseRSAPublicKeyFromPEM(key)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
testData := rsaTestData[0]
|
||||
parts := strings.Split(testData.tokenString, ".")
|
||||
err = jwt.SigningMethodRS256.Verify(strings.Join(parts[0:2], "."), parts[2], parsedKey)
|
||||
if err != nil {
|
||||
t.Errorf("[%v] Error while verifying key: %v", testData.name, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRSAWithPreParsedPrivateKey(t *testing.T) {
|
||||
key, _ := ioutil.ReadFile("test/sample_key")
|
||||
parsedKey, err := jwt.ParseRSAPrivateKeyFromPEM(key)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
testData := rsaTestData[0]
|
||||
parts := strings.Split(testData.tokenString, ".")
|
||||
sig, err := jwt.SigningMethodRS256.Sign(strings.Join(parts[0:2], "."), parsedKey)
|
||||
if err != nil {
|
||||
t.Errorf("[%v] Error signing token: %v", testData.name, err)
|
||||
}
|
||||
if sig != parts[2] {
|
||||
t.Errorf("[%v] Incorrect signature.\nwas:\n%v\nexpecting:\n%v", testData.name, sig, parts[2])
|
||||
}
|
||||
}
|
||||
|
||||
func TestRSAKeyParsing(t *testing.T) {
|
||||
key, _ := ioutil.ReadFile("test/sample_key")
|
||||
pubKey, _ := ioutil.ReadFile("test/sample_key.pub")
|
||||
badKey := []byte("All your base are belong to key")
|
||||
|
||||
// Test parsePrivateKey
|
||||
if _, e := jwt.ParseRSAPrivateKeyFromPEM(key); e != nil {
|
||||
t.Errorf("Failed to parse valid private key: %v", e)
|
||||
}
|
||||
|
||||
if k, e := jwt.ParseRSAPrivateKeyFromPEM(pubKey); e == nil {
|
||||
t.Errorf("Parsed public key as valid private key: %v", k)
|
||||
}
|
||||
|
||||
if k, e := jwt.ParseRSAPrivateKeyFromPEM(badKey); e == nil {
|
||||
t.Errorf("Parsed invalid key as valid private key: %v", k)
|
||||
}
|
||||
|
||||
// Test parsePublicKey
|
||||
if _, e := jwt.ParseRSAPublicKeyFromPEM(pubKey); e != nil {
|
||||
t.Errorf("Failed to parse valid public key: %v", e)
|
||||
}
|
||||
|
||||
if k, e := jwt.ParseRSAPublicKeyFromPEM(key); e == nil {
|
||||
t.Errorf("Parsed private key as valid public key: %v", k)
|
||||
}
|
||||
|
||||
if k, e := jwt.ParseRSAPublicKeyFromPEM(badKey); e == nil {
|
||||
t.Errorf("Parsed invalid key as valid private key: %v", k)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func BenchmarkRS256Signing(b *testing.B) {
|
||||
key, _ := ioutil.ReadFile("test/sample_key")
|
||||
parsedKey, err := jwt.ParseRSAPrivateKeyFromPEM(key)
|
||||
if err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
|
||||
benchmarkSigning(b, jwt.SigningMethodRS256, parsedKey)
|
||||
}
|
||||
|
||||
func BenchmarkRS384Signing(b *testing.B) {
|
||||
key, _ := ioutil.ReadFile("test/sample_key")
|
||||
parsedKey, err := jwt.ParseRSAPrivateKeyFromPEM(key)
|
||||
if err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
|
||||
benchmarkSigning(b, jwt.SigningMethodRS384, parsedKey)
|
||||
}
|
||||
|
||||
func BenchmarkRS512Signing(b *testing.B) {
|
||||
key, _ := ioutil.ReadFile("test/sample_key")
|
||||
parsedKey, err := jwt.ParseRSAPrivateKeyFromPEM(key)
|
||||
if err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
|
||||
benchmarkSigning(b, jwt.SigningMethodRS512, parsedKey)
|
||||
}
|
|
@ -0,0 +1,68 @@
|
|||
package jwt
|
||||
|
||||
import (
|
||||
"crypto/rsa"
|
||||
"crypto/x509"
|
||||
"encoding/pem"
|
||||
"errors"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrKeyMustBePEMEncoded = errors.New("Invalid Key: Key must be PEM encoded PKCS1 or PKCS8 private key")
|
||||
ErrNotRSAPrivateKey = errors.New("Key is not a valid RSA private key")
|
||||
)
|
||||
|
||||
// Parse PEM encoded PKCS1 or PKCS8 private key
|
||||
func ParseRSAPrivateKeyFromPEM(key []byte) (*rsa.PrivateKey, error) {
|
||||
var err error
|
||||
|
||||
// Parse PEM block
|
||||
var block *pem.Block
|
||||
if block, _ = pem.Decode(key); block == nil {
|
||||
return nil, ErrKeyMustBePEMEncoded
|
||||
}
|
||||
|
||||
var parsedKey interface{}
|
||||
if parsedKey, err = x509.ParsePKCS1PrivateKey(block.Bytes); err != nil {
|
||||
if parsedKey, err = x509.ParsePKCS8PrivateKey(block.Bytes); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
var pkey *rsa.PrivateKey
|
||||
var ok bool
|
||||
if pkey, ok = parsedKey.(*rsa.PrivateKey); !ok {
|
||||
return nil, ErrNotRSAPrivateKey
|
||||
}
|
||||
|
||||
return pkey, nil
|
||||
}
|
||||
|
||||
// Parse PEM encoded PKCS1 or PKCS8 public key
|
||||
func ParseRSAPublicKeyFromPEM(key []byte) (*rsa.PublicKey, error) {
|
||||
var err error
|
||||
|
||||
// Parse PEM block
|
||||
var block *pem.Block
|
||||
if block, _ = pem.Decode(key); block == nil {
|
||||
return nil, ErrKeyMustBePEMEncoded
|
||||
}
|
||||
|
||||
// Parse the key
|
||||
var parsedKey interface{}
|
||||
if parsedKey, err = x509.ParsePKIXPublicKey(block.Bytes); err != nil {
|
||||
if cert, err := x509.ParseCertificate(block.Bytes); err == nil {
|
||||
parsedKey = cert.PublicKey
|
||||
} else {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
var pkey *rsa.PublicKey
|
||||
var ok bool
|
||||
if pkey, ok = parsedKey.(*rsa.PublicKey); !ok {
|
||||
return nil, ErrNotRSAPrivateKey
|
||||
}
|
||||
|
||||
return pkey, nil
|
||||
}
|
24
Godeps/_workspace/src/github.com/dgrijalva/jwt-go/signing_method.go
generated
vendored
Normal file
24
Godeps/_workspace/src/github.com/dgrijalva/jwt-go/signing_method.go
generated
vendored
Normal file
|
@ -0,0 +1,24 @@
|
|||
package jwt
|
||||
|
||||
var signingMethods = map[string]func() SigningMethod{}
|
||||
|
||||
// Signing method
|
||||
type SigningMethod interface {
|
||||
Verify(signingString, signature string, key interface{}) error
|
||||
Sign(signingString string, key interface{}) (string, error)
|
||||
Alg() string
|
||||
}
|
||||
|
||||
// Register the "alg" name and a factory function for signing method.
|
||||
// This is typically done during init() in the method's implementation
|
||||
func RegisterSigningMethod(alg string, f func() SigningMethod) {
|
||||
signingMethods[alg] = f
|
||||
}
|
||||
|
||||
// Get a signing method from an "alg" string
|
||||
func GetSigningMethod(alg string) (method SigningMethod) {
|
||||
if methodF, ok := signingMethods[alg]; ok {
|
||||
method = methodF()
|
||||
}
|
||||
return
|
||||
}
|
5
Godeps/_workspace/src/github.com/dgrijalva/jwt-go/test/ec256-private.pem
generated
vendored
Normal file
5
Godeps/_workspace/src/github.com/dgrijalva/jwt-go/test/ec256-private.pem
generated
vendored
Normal file
|
@ -0,0 +1,5 @@
|
|||
-----BEGIN EC PRIVATE KEY-----
|
||||
MHcCAQEEIAh5qA3rmqQQuu0vbKV/+zouz/y/Iy2pLpIcWUSyImSwoAoGCCqGSM49
|
||||
AwEHoUQDQgAEYD54V/vp+54P9DXarYqx4MPcm+HKRIQzNasYSoRQHQ/6S6Ps8tpM
|
||||
cT+KvIIC8W/e9k0W7Cm72M1P9jU7SLf/vg==
|
||||
-----END EC PRIVATE KEY-----
|
4
Godeps/_workspace/src/github.com/dgrijalva/jwt-go/test/ec256-public.pem
generated
vendored
Normal file
4
Godeps/_workspace/src/github.com/dgrijalva/jwt-go/test/ec256-public.pem
generated
vendored
Normal file
|
@ -0,0 +1,4 @@
|
|||
-----BEGIN PUBLIC KEY-----
|
||||
MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEYD54V/vp+54P9DXarYqx4MPcm+HK
|
||||
RIQzNasYSoRQHQ/6S6Ps8tpMcT+KvIIC8W/e9k0W7Cm72M1P9jU7SLf/vg==
|
||||
-----END PUBLIC KEY-----
|
6
Godeps/_workspace/src/github.com/dgrijalva/jwt-go/test/ec384-private.pem
generated
vendored
Normal file
6
Godeps/_workspace/src/github.com/dgrijalva/jwt-go/test/ec384-private.pem
generated
vendored
Normal file
|
@ -0,0 +1,6 @@
|
|||
-----BEGIN EC PRIVATE KEY-----
|
||||
MIGkAgEBBDCaCvMHKhcG/qT7xsNLYnDT7sE/D+TtWIol1ROdaK1a564vx5pHbsRy
|
||||
SEKcIxISi1igBwYFK4EEACKhZANiAATYa7rJaU7feLMqrAx6adZFNQOpaUH/Uylb
|
||||
ZLriOLON5YFVwtVUpO1FfEXZUIQpptRPtc5ixIPY658yhBSb6irfIJUSP9aYTflJ
|
||||
GKk/mDkK4t8mWBzhiD5B6jg9cEGhGgA=
|
||||
-----END EC PRIVATE KEY-----
|
5
Godeps/_workspace/src/github.com/dgrijalva/jwt-go/test/ec384-public.pem
generated
vendored
Normal file
5
Godeps/_workspace/src/github.com/dgrijalva/jwt-go/test/ec384-public.pem
generated
vendored
Normal file
|
@ -0,0 +1,5 @@
|
|||
-----BEGIN PUBLIC KEY-----
|
||||
MHYwEAYHKoZIzj0CAQYFK4EEACIDYgAE2Gu6yWlO33izKqwMemnWRTUDqWlB/1Mp
|
||||
W2S64jizjeWBVcLVVKTtRXxF2VCEKabUT7XOYsSD2OufMoQUm+oq3yCVEj/WmE35
|
||||
SRipP5g5CuLfJlgc4Yg+Qeo4PXBBoRoA
|
||||
-----END PUBLIC KEY-----
|
7
Godeps/_workspace/src/github.com/dgrijalva/jwt-go/test/ec512-private.pem
generated
vendored
Normal file
7
Godeps/_workspace/src/github.com/dgrijalva/jwt-go/test/ec512-private.pem
generated
vendored
Normal file
|
@ -0,0 +1,7 @@
|
|||
-----BEGIN EC PRIVATE KEY-----
|
||||
MIHcAgEBBEIB0pE4uFaWRx7t03BsYlYvF1YvKaBGyvoakxnodm9ou0R9wC+sJAjH
|
||||
QZZJikOg4SwNqgQ/hyrOuDK2oAVHhgVGcYmgBwYFK4EEACOhgYkDgYYABAAJXIuw
|
||||
12MUzpHggia9POBFYXSxaOGKGbMjIyDI+6q7wi7LMw3HgbaOmgIqFG72o8JBQwYN
|
||||
4IbXHf+f86CRY1AA2wHzbHvt6IhkCXTNxBEffa1yMUgu8n9cKKF2iLgyQKcKqW33
|
||||
8fGOw/n3Rm2Yd/EB56u2rnD29qS+nOM9eGS+gy39OQ==
|
||||
-----END EC PRIVATE KEY-----
|
6
Godeps/_workspace/src/github.com/dgrijalva/jwt-go/test/ec512-public.pem
generated
vendored
Normal file
6
Godeps/_workspace/src/github.com/dgrijalva/jwt-go/test/ec512-public.pem
generated
vendored
Normal file
|
@ -0,0 +1,6 @@
|
|||
-----BEGIN PUBLIC KEY-----
|
||||
MIGbMBAGByqGSM49AgEGBSuBBAAjA4GGAAQACVyLsNdjFM6R4IImvTzgRWF0sWjh
|
||||
ihmzIyMgyPuqu8IuyzMNx4G2jpoCKhRu9qPCQUMGDeCG1x3/n/OgkWNQANsB82x7
|
||||
7eiIZAl0zcQRH32tcjFILvJ/XCihdoi4MkCnCqlt9/HxjsP590ZtmHfxAeertq5w
|
||||
9vakvpzjPXhkvoMt/Tk=
|
||||
-----END PUBLIC KEY-----
|
|
@ -0,0 +1 @@
|
|||
#5K+・シミew{ヲ住ウ(跼Tノ(ゥ┫メP.ソモ燾辻G<>感テwb="=.!r.Oタヘ奎gミ」
|
|
@ -0,0 +1,27 @@
|
|||
-----BEGIN RSA PRIVATE KEY-----
|
||||
MIIEowIBAAKCAQEA4f5wg5l2hKsTeNem/V41fGnJm6gOdrj8ym3rFkEU/wT8RDtn
|
||||
SgFEZOQpHEgQ7JL38xUfU0Y3g6aYw9QT0hJ7mCpz9Er5qLaMXJwZxzHzAahlfA0i
|
||||
cqabvJOMvQtzD6uQv6wPEyZtDTWiQi9AXwBpHssPnpYGIn20ZZuNlX2BrClciHhC
|
||||
PUIIZOQn/MmqTD31jSyjoQoV7MhhMTATKJx2XrHhR+1DcKJzQBSTAGnpYVaqpsAR
|
||||
ap+nwRipr3nUTuxyGohBTSmjJ2usSeQXHI3bODIRe1AuTyHceAbewn8b462yEWKA
|
||||
Rdpd9AjQW5SIVPfdsz5B6GlYQ5LdYKtznTuy7wIDAQABAoIBAQCwia1k7+2oZ2d3
|
||||
n6agCAbqIE1QXfCmh41ZqJHbOY3oRQG3X1wpcGH4Gk+O+zDVTV2JszdcOt7E5dAy
|
||||
MaomETAhRxB7hlIOnEN7WKm+dGNrKRvV0wDU5ReFMRHg31/Lnu8c+5BvGjZX+ky9
|
||||
POIhFFYJqwCRlopGSUIxmVj5rSgtzk3iWOQXr+ah1bjEXvlxDOWkHN6YfpV5ThdE
|
||||
KdBIPGEVqa63r9n2h+qazKrtiRqJqGnOrHzOECYbRFYhexsNFz7YT02xdfSHn7gM
|
||||
IvabDDP/Qp0PjE1jdouiMaFHYnLBbgvlnZW9yuVf/rpXTUq/njxIXMmvmEyyvSDn
|
||||
FcFikB8pAoGBAPF77hK4m3/rdGT7X8a/gwvZ2R121aBcdPwEaUhvj/36dx596zvY
|
||||
mEOjrWfZhF083/nYWE2kVquj2wjs+otCLfifEEgXcVPTnEOPO9Zg3uNSL0nNQghj
|
||||
FuD3iGLTUBCtM66oTe0jLSslHe8gLGEQqyMzHOzYxNqibxcOZIe8Qt0NAoGBAO+U
|
||||
I5+XWjWEgDmvyC3TrOSf/KCGjtu0TSv30ipv27bDLMrpvPmD/5lpptTFwcxvVhCs
|
||||
2b+chCjlghFSWFbBULBrfci2FtliClOVMYrlNBdUSJhf3aYSG2Doe6Bgt1n2CpNn
|
||||
/iu37Y3NfemZBJA7hNl4dYe+f+uzM87cdQ214+jrAoGAXA0XxX8ll2+ToOLJsaNT
|
||||
OvNB9h9Uc5qK5X5w+7G7O998BN2PC/MWp8H+2fVqpXgNENpNXttkRm1hk1dych86
|
||||
EunfdPuqsX+as44oCyJGFHVBnWpm33eWQw9YqANRI+pCJzP08I5WK3osnPiwshd+
|
||||
hR54yjgfYhBFNI7B95PmEQkCgYBzFSz7h1+s34Ycr8SvxsOBWxymG5zaCsUbPsL0
|
||||
4aCgLScCHb9J+E86aVbbVFdglYa5Id7DPTL61ixhl7WZjujspeXZGSbmq0Kcnckb
|
||||
mDgqkLECiOJW2NHP/j0McAkDLL4tysF8TLDO8gvuvzNC+WQ6drO2ThrypLVZQ+ry
|
||||
eBIPmwKBgEZxhqa0gVvHQG/7Od69KWj4eJP28kq13RhKay8JOoN0vPmspXJo1HY3
|
||||
CKuHRG+AP579dncdUnOMvfXOtkdM4vk0+hWASBQzM9xzVcztCa+koAugjVaLS9A+
|
||||
9uQoqEeVNTckxx0S2bYevRy7hGQmUJTyQm3j1zEUR5jpdbL83Fbq
|
||||
-----END RSA PRIVATE KEY-----
|
9
Godeps/_workspace/src/github.com/dgrijalva/jwt-go/test/sample_key.pub
generated
vendored
Normal file
9
Godeps/_workspace/src/github.com/dgrijalva/jwt-go/test/sample_key.pub
generated
vendored
Normal file
|
@ -0,0 +1,9 @@
|
|||
-----BEGIN PUBLIC KEY-----
|
||||
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA4f5wg5l2hKsTeNem/V41
|
||||
fGnJm6gOdrj8ym3rFkEU/wT8RDtnSgFEZOQpHEgQ7JL38xUfU0Y3g6aYw9QT0hJ7
|
||||
mCpz9Er5qLaMXJwZxzHzAahlfA0icqabvJOMvQtzD6uQv6wPEyZtDTWiQi9AXwBp
|
||||
HssPnpYGIn20ZZuNlX2BrClciHhCPUIIZOQn/MmqTD31jSyjoQoV7MhhMTATKJx2
|
||||
XrHhR+1DcKJzQBSTAGnpYVaqpsARap+nwRipr3nUTuxyGohBTSmjJ2usSeQXHI3b
|
||||
ODIRe1AuTyHceAbewn8b462yEWKARdpd9AjQW5SIVPfdsz5B6GlYQ5LdYKtznTuy
|
||||
7wIDAQAB
|
||||
-----END PUBLIC KEY-----
|
|
@ -1,32 +0,0 @@
|
|||
package api
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
)
|
||||
|
||||
// Login performs the /sys/login API call.
|
||||
//
|
||||
// This API call is stateful: it will set the access token on the client
|
||||
// for future API calls to be authenticated. The access token can be retrieved
|
||||
// at any time from the client using `client.Token()` and it can be cleared
|
||||
// with `sys.Logout()`.
|
||||
func (c *Sys) Login(vars map[string]string) error {
|
||||
r := c.c.NewRequest("PUT", "/v1/sys/login")
|
||||
if err := r.SetJSONBody(vars); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
resp, err := c.c.RawRequest(r)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if c.c.Token() == "" {
|
||||
return fmt.Errorf(
|
||||
"Login had status code %d, but token cookie was not set!",
|
||||
resp.StatusCode)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
|
@ -39,7 +39,9 @@ func (h *CLIHandler) Help() string {
|
|||
The "cert" credential provider allows you to authenticate with a
|
||||
client certificate. No other authentication materials are needed.
|
||||
|
||||
Example: vault auth -method=cert
|
||||
Example: vault auth -method=cert \
|
||||
-client-cert=/path/to/cert.pem \
|
||||
-client-key=/path/to/key.pem
|
||||
|
||||
`
|
||||
|
||||
|
|
|
@ -103,6 +103,9 @@ func (b *backend) pathLogin(
|
|||
|
||||
// Append the names so we can get the policies
|
||||
teamNames = append(teamNames, *t.Name)
|
||||
if *t.Name != *t.Slug {
|
||||
teamNames = append(teamNames, *t.Slug)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
|
|
@ -0,0 +1,30 @@
|
|||
package jwt
|
||||
|
||||
import (
|
||||
"github.com/hashicorp/vault/logical"
|
||||
"github.com/hashicorp/vault/logical/framework"
|
||||
)
|
||||
|
||||
// Factory creates a new backend implementing the logical.Backend interface
|
||||
func Factory(conf *logical.BackendConfig) (logical.Backend, error) {
|
||||
return Backend().Setup(conf)
|
||||
}
|
||||
|
||||
// Backend returns a new Backend framework struct
|
||||
func Backend() *framework.Backend {
|
||||
var b backend
|
||||
b.Backend = &framework.Backend{
|
||||
|
||||
Paths: []*framework.Path{
|
||||
pathRoles(&b),
|
||||
pathIssue(&b),
|
||||
},
|
||||
|
||||
}
|
||||
|
||||
return b.Backend
|
||||
}
|
||||
|
||||
type backend struct {
|
||||
*framework.Backend
|
||||
}
|
|
@ -0,0 +1,162 @@
|
|||
package jwt
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
|
||||
jwt "github.com/dgrijalva/jwt-go"
|
||||
|
||||
"github.com/hashicorp/vault/logical"
|
||||
logicaltest "github.com/hashicorp/vault/logical/testing"
|
||||
"github.com/mitchellh/mapstructure"
|
||||
)
|
||||
|
||||
func TestBackend_basic(t *testing.T) {
|
||||
tokenClaims := map[string]interface{}{
|
||||
"iss": "Test Issuer",
|
||||
"sub": "Test Subject",
|
||||
"aud": "Test Audience",
|
||||
"iat": 1438898720,
|
||||
"nbf": 1438898720,
|
||||
"exp": 1538898720,
|
||||
"jti": "jti",
|
||||
"ran": "random",
|
||||
}
|
||||
|
||||
logicaltest.Test(t, logicaltest.TestCase{
|
||||
Backend: Backend(),
|
||||
Steps: []logicaltest.TestStep{
|
||||
testAccStepWriteRole(t, "test", "HS256", "test"),
|
||||
testAccStepReadRole(t, "test", "HS256", "test"),
|
||||
testAccStepSignToken(t, "test", tokenClaims, false),
|
||||
testAccStepDeleteRole(t, "test"),
|
||||
testAccStepReadRole(t, "test", "HS256", "test"),
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func TestBackend_defaults(t *testing.T) {
|
||||
tokenClaims := map[string]interface{}{
|
||||
"iat": 1438898720,
|
||||
"nbf": 1438898720,
|
||||
"exp": 1538898720,
|
||||
"jti": "9fe94d93-7bb4-434c-b197-731b4b4c70d3",
|
||||
"ran": "random",
|
||||
}
|
||||
|
||||
logicaltest.Test(t, logicaltest.TestCase{
|
||||
Backend: Backend(),
|
||||
Steps: []logicaltest.TestStep{
|
||||
testAccStepWriteRole(t, "test", "HS256", "test"),
|
||||
testAccStepReadRole(t, "test", "HS256", "test"),
|
||||
testAccStepSignToken(t, "test", tokenClaims, true),
|
||||
testAccStepDeleteRole(t, "test"),
|
||||
testAccStepReadRole(t, "test", "HS256", "test"),
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func testAccStepWriteRole(t *testing.T, name string, algorithm string, key string) logicaltest.TestStep {
|
||||
return logicaltest.TestStep{
|
||||
Operation: logical.WriteOperation,
|
||||
Path: "roles/" + name,
|
||||
Data: map[string]interface{}{
|
||||
"algorithm": algorithm,
|
||||
"key": key,
|
||||
"default_issuer": "Test Default Issuer",
|
||||
"default_subject": "Test Default Subject",
|
||||
"default_audience": "Test Default Audience",
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func testAccStepDeleteRole(t *testing.T, name string) logicaltest.TestStep {
|
||||
return logicaltest.TestStep{
|
||||
Operation: logical.DeleteOperation,
|
||||
Path: "roles/" + name,
|
||||
}
|
||||
}
|
||||
|
||||
func testAccStepReadRole(t *testing.T, name string, algorithm string, key string) logicaltest.TestStep {
|
||||
return logicaltest.TestStep{
|
||||
Operation: logical.ReadOperation,
|
||||
Path: "roles/" + name,
|
||||
Check: func(resp *logical.Response) error {
|
||||
if resp == nil {
|
||||
return fmt.Errorf("missing response")
|
||||
}
|
||||
var d struct {
|
||||
Name string `json:"name" mapstructure:"name"`
|
||||
Algorithm string `json:"algorithm" structs:"algorithm" mapstructure:"algorithm"`
|
||||
Key string `json:"key" structs:"key" mapstructure:"key"`
|
||||
Issuer string `json:"iss" structs:"iss" mapstructure:"iss"`
|
||||
Subject string `json:"sub" structs:"sub" mapstructure:"sub"`
|
||||
Audience string `json:"aud" structs:"aud" mapstructure:"aud"`
|
||||
}
|
||||
if err := mapstructure.Decode(resp.Data, &d); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if d.Name != name {
|
||||
return fmt.Errorf("bad: %#v", d)
|
||||
}
|
||||
if d.Algorithm != algorithm {
|
||||
return fmt.Errorf("bad: %#v", d)
|
||||
}
|
||||
if d.Key != key {
|
||||
return fmt.Errorf("bad: %#v", d)
|
||||
}
|
||||
|
||||
return nil
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func testAccStepSignToken(t *testing.T, name string, tokenClaims map[string]interface{}, defaults bool) logicaltest.TestStep {
|
||||
return logicaltest.TestStep{
|
||||
Operation: logical.WriteOperation,
|
||||
Path: "issue/" + name,
|
||||
Data: tokenClaims,
|
||||
Check: func(resp *logical.Response) error {
|
||||
var d struct {
|
||||
JTI string `mapstructure:"jti"`
|
||||
Token string `mapstructure:"token"`
|
||||
}
|
||||
if err := mapstructure.Decode(resp.Data, &d); err != nil {
|
||||
return err
|
||||
}
|
||||
if d.Token == "" {
|
||||
return fmt.Errorf("missing token")
|
||||
}
|
||||
|
||||
token, err := jwt.Parse(d.Token, func(token *jwt.Token) (interface{}, error) {
|
||||
return token, nil
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf("error parsing token")
|
||||
}
|
||||
|
||||
if d.JTI != token.Claims["jti"] {
|
||||
return fmt.Errorf("bad: %#v", d)
|
||||
}
|
||||
|
||||
if token.Claims["ran"] != "random" {
|
||||
return fmt.Errorf("bad: %#v", d)
|
||||
}
|
||||
|
||||
if defaults == true {
|
||||
if token.Claims["sub"] != "Test Default Subject" {
|
||||
return fmt.Errorf("bad: %#v", d)
|
||||
}
|
||||
if token.Claims["aud"] != "Test Default Audience" {
|
||||
return fmt.Errorf("bad: %#v", d)
|
||||
}
|
||||
if token.Claims["iss"] != "Test Default Issuer" {
|
||||
return fmt.Errorf("bad: %#v", d)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
},
|
||||
}
|
||||
}
|
|
@ -0,0 +1,153 @@
|
|||
package jwt
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"time"
|
||||
"encoding/json"
|
||||
|
||||
jwt "github.com/dgrijalva/jwt-go"
|
||||
|
||||
"github.com/hashicorp/vault/helper/uuid"
|
||||
"github.com/hashicorp/vault/logical"
|
||||
"github.com/hashicorp/vault/logical/framework"
|
||||
)
|
||||
|
||||
func pathIssue(b *backend) *framework.Path {
|
||||
return &framework.Path{
|
||||
Pattern: `issue/(?P<role>\w[\w-]+\w)`,
|
||||
Fields: map[string]*framework.FieldSchema{
|
||||
"role": &framework.FieldSchema{
|
||||
Type: framework.TypeString,
|
||||
Description: "The desired role with configuration for this request",
|
||||
},
|
||||
"issuer": &framework.FieldSchema{
|
||||
Type: framework.TypeString,
|
||||
Description: "The issuer of the token",
|
||||
},
|
||||
"subject": &framework.FieldSchema{
|
||||
Type: framework.TypeString,
|
||||
Description: "The subject of the token",
|
||||
},
|
||||
"audience": &framework.FieldSchema{
|
||||
Type: framework.TypeString,
|
||||
Description: "The audience of the token",
|
||||
},
|
||||
"expiration": &framework.FieldSchema{
|
||||
Type: framework.TypeInt,
|
||||
Description: "This will define the expiration in NumericDate value",
|
||||
},
|
||||
"not_before": &framework.FieldSchema{
|
||||
Type: framework.TypeInt,
|
||||
Description: "Defines the time before which the JWT MUST NOT be accepted for processing",
|
||||
},
|
||||
"issued_at": &framework.FieldSchema{
|
||||
Type: framework.TypeInt,
|
||||
Description: "The time the JWT was issued",
|
||||
},
|
||||
"jti": &framework.FieldSchema{
|
||||
Type: framework.TypeString,
|
||||
Description: "Unique identifier for the JWT",
|
||||
},
|
||||
"claims": &framework.FieldSchema{
|
||||
Type: framework.TypeString,
|
||||
Description: "JSON Object of Claims for the JWT Token",
|
||||
},
|
||||
},
|
||||
|
||||
Callbacks: map[logical.Operation]framework.OperationFunc{
|
||||
logical.WriteOperation: b.pathIssueWrite,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func (b *backend) pathIssueWrite(
|
||||
req *logical.Request, data *framework.FieldData) (*logical.Response, error) {
|
||||
roleName := data.Get("role").(string)
|
||||
|
||||
// Get the role
|
||||
role, err := b.getRole(req.Storage, roleName)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if role == nil {
|
||||
return logical.ErrorResponse(fmt.Sprintf("Unknown role: %s", roleName)), nil
|
||||
}
|
||||
|
||||
claims := map[string]interface{}{
|
||||
"initial": "ok",
|
||||
}
|
||||
|
||||
if role.Issuer != "" {
|
||||
claims["iss"] = role.Issuer
|
||||
}
|
||||
if role.Subject != "" {
|
||||
claims["sub"] = role.Subject
|
||||
}
|
||||
if role.Audience != "" {
|
||||
claims["aud"] = role.Audience
|
||||
}
|
||||
|
||||
if data.Get("not_before") == 0 {
|
||||
claims["nbf"] = int(time.Now().Unix())
|
||||
}
|
||||
if data.Get("issued_at") == 0 {
|
||||
claims["iat"] = int(time.Now().Unix())
|
||||
}
|
||||
if data.Get("jti") == "" {
|
||||
claims["jti"] = uuid.GenerateUUID()
|
||||
}
|
||||
|
||||
if data.Get("issuer") != "" {
|
||||
claims["iss"] = data.Get("issuer").(string)
|
||||
}
|
||||
if data.Get("subject") != "" {
|
||||
claims["sub"] = data.Get("subject").(string)
|
||||
}
|
||||
if data.Get("audience") != "" {
|
||||
claims["aud"] = data.Get("audience").(string)
|
||||
}
|
||||
if data.Get("expiration").(int) > 0 {
|
||||
claims["exp"] = data.Get("expiration").(int)
|
||||
}
|
||||
if data.Get("not_before").(int) > 0 {
|
||||
claims["nbf"] = data.Get("not_before").(int)
|
||||
}
|
||||
if data.Get("issued_at").(int) > 0 {
|
||||
claims["iat"] = data.Get("issued_at").(int)
|
||||
}
|
||||
if data.Get("jti") != "" {
|
||||
claims["jti"] = data.Get("jti").(string)
|
||||
}
|
||||
|
||||
if data.Get("claims").(string) != "" {
|
||||
// Parse JSON using unmarshal
|
||||
var uc map[string]interface{}
|
||||
err := json.Unmarshal([]byte(data.Get("claims").(string)), &uc)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
for k, v := range uc {
|
||||
claims[k] = v
|
||||
}
|
||||
}
|
||||
|
||||
delete(claims, "initial")
|
||||
|
||||
token := jwt.New(jwt.GetSigningMethod(role.Algorithm))
|
||||
token.Claims = claims
|
||||
|
||||
tokenString, err := token.SignedString([]byte(role.Key))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
resp := &logical.Response{
|
||||
Data: map[string]interface{}{
|
||||
"jti": claims["jti"].(string),
|
||||
"token": tokenString,
|
||||
},
|
||||
}
|
||||
|
||||
return resp, nil
|
||||
}
|
|
@ -0,0 +1,188 @@
|
|||
package jwt
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"crypto/x509"
|
||||
"encoding/pem"
|
||||
"strings"
|
||||
|
||||
"github.com/fatih/structs"
|
||||
jwt "github.com/dgrijalva/jwt-go"
|
||||
|
||||
"github.com/hashicorp/vault/logical"
|
||||
"github.com/hashicorp/vault/logical/framework"
|
||||
)
|
||||
|
||||
func pathRoles(b *backend) *framework.Path {
|
||||
return &framework.Path{
|
||||
Pattern: `roles/(?P<name>\w+)`,
|
||||
Fields: map[string]*framework.FieldSchema{
|
||||
"name": &framework.FieldSchema{
|
||||
Type: framework.TypeString,
|
||||
Description: "Name of the Role",
|
||||
},
|
||||
"algorithm": &framework.FieldSchema{
|
||||
Type: framework.TypeString,
|
||||
Default: "RS256",
|
||||
Description: "Algorithm for JWT Signing",
|
||||
},
|
||||
"key": &framework.FieldSchema{
|
||||
Type: framework.TypeString,
|
||||
Description: "Private Key (RSA or EC) or String for HMAC Algorithm",
|
||||
},
|
||||
"default_issuer": &framework.FieldSchema{
|
||||
Type: framework.TypeString,
|
||||
Description: "Default Issuer for the Role for the JWT Tokens",
|
||||
},
|
||||
"default_subject": &framework.FieldSchema{
|
||||
Type: framework.TypeString,
|
||||
Description: "Default Subject for the Role for the JWT Token",
|
||||
},
|
||||
"default_audience": &framework.FieldSchema{
|
||||
Type: framework.TypeString,
|
||||
Description: "Default Audience for the Role for the JWT Token",
|
||||
},
|
||||
},
|
||||
|
||||
Callbacks: map[logical.Operation]framework.OperationFunc{
|
||||
logical.ReadOperation: b.pathRoleRead,
|
||||
logical.WriteOperation: b.pathRoleCreate,
|
||||
logical.DeleteOperation: b.pathRoleDelete,
|
||||
},
|
||||
|
||||
HelpSynopsis: pathRolesHelpSyn,
|
||||
HelpDescription: pathRolesHelpDesc,
|
||||
}
|
||||
}
|
||||
|
||||
func (b *backend) getRole(s logical.Storage, n string) (*roleEntry, error) {
|
||||
entry, err := s.Get("role/" + n)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if entry == nil {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
var result roleEntry
|
||||
if err := entry.DecodeJSON(&result); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &result, nil
|
||||
}
|
||||
|
||||
func (b *backend) pathRoleDelete(
|
||||
req *logical.Request, data *framework.FieldData) (*logical.Response, error) {
|
||||
err := req.Storage.Delete("role/" + data.Get("name").(string))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (b *backend) pathRoleRead(
|
||||
req *logical.Request, data *framework.FieldData) (*logical.Response, error) {
|
||||
role, err := b.getRole(req.Storage, data.Get("name").(string))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if role == nil {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
var r = structs.New(role).Map()
|
||||
|
||||
delete(r, "key")
|
||||
|
||||
resp := &logical.Response{
|
||||
Data: r,
|
||||
}
|
||||
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
func (b *backend) pathRoleCreate(
|
||||
req *logical.Request, data *framework.FieldData) (*logical.Response, error) {
|
||||
name := data.Get("name").(string)
|
||||
key := data.Get("key").(string)
|
||||
alg := data.Get("algorithm").(string)
|
||||
|
||||
signingMethod := jwt.GetSigningMethod(data.Get("algorithm").(string))
|
||||
if signingMethod == nil {
|
||||
return nil, fmt.Errorf("Invalid Signing Algorithm")
|
||||
}
|
||||
|
||||
if key == "" {
|
||||
return nil, fmt.Errorf("Key is Required")
|
||||
}
|
||||
|
||||
if strings.HasPrefix(alg, "RS") {
|
||||
// need RSA Private Key
|
||||
if strings.Contains(key, "RSA PRIVATE KEY") == false {
|
||||
return nil, fmt.Errorf("Key is not a PEM formatted RSA Private Key")
|
||||
}
|
||||
|
||||
block, _ := pem.Decode([]byte(key))
|
||||
_, err := x509.ParsePKCS1PrivateKey(block.Bytes)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("Failed to parse the private key: %s", err)
|
||||
}
|
||||
} else if strings.HasPrefix(alg, "HS") {
|
||||
// need a string
|
||||
if key == "" {
|
||||
return nil, fmt.Errorf("Key must not be blank")
|
||||
}
|
||||
} else if strings.HasPrefix(alg, "EC") {
|
||||
// need EC Private Key
|
||||
if strings.Contains(key, "EC PRIVATE KEY") == false {
|
||||
return nil, fmt.Errorf("Key is not a PEM formatted EC Private Key")
|
||||
}
|
||||
|
||||
block, _ := pem.Decode([]byte(key))
|
||||
_, err := x509.ParseECPrivateKey(block.Bytes)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("Failed to parse the private key: %s", err)
|
||||
}
|
||||
}
|
||||
|
||||
entry := &roleEntry{
|
||||
Algorithm: alg,
|
||||
Key: key,
|
||||
Issuer: data.Get("default_issuer").(string),
|
||||
Subject: data.Get("default_subject").(string),
|
||||
Audience: data.Get("default_audience").(string),
|
||||
}
|
||||
|
||||
// Store it
|
||||
jsonEntry, err := logical.StorageEntryJSON("role/" + name, entry)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := req.Storage.Put(jsonEntry); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
type roleEntry struct {
|
||||
Algorithm string `json:"algorithm" structs:"algorithm" mapstructure:"algorithm"`
|
||||
Key string `json:"key" structs:"key" mapstructure:"key"`
|
||||
Issuer string `json:"iss" structs:"iss" mapstructure:"iss"`
|
||||
Subject string `json:"sub" structs:"sub" mapstructure:"sub"`
|
||||
Audience string `json:"aud" structs:"aud" mapstructure:"aud"`
|
||||
}
|
||||
|
||||
const pathRolesHelpSyn = `
|
||||
Read and write basic configuration for generating signed JWT Tokens.
|
||||
`
|
||||
|
||||
const pathRolesHelpDesc = `
|
||||
This path allows you to read and write roles that are used to
|
||||
create JWT tokens. These roles have a few settings that dictated
|
||||
what signing algorithm is used for the JWT token. For example,
|
||||
if the backend is mounted at "jwt" and you create a role at
|
||||
"jwt/roles/auth" then a user can request a JWT token at "jwt/issue/auth".
|
||||
`
|
|
@ -17,6 +17,7 @@ import (
|
|||
"github.com/hashicorp/vault/builtin/logical/aws"
|
||||
"github.com/hashicorp/vault/builtin/logical/cassandra"
|
||||
"github.com/hashicorp/vault/builtin/logical/consul"
|
||||
"github.com/hashicorp/vault/builtin/logical/jwt"
|
||||
"github.com/hashicorp/vault/builtin/logical/mysql"
|
||||
"github.com/hashicorp/vault/builtin/logical/pki"
|
||||
"github.com/hashicorp/vault/builtin/logical/postgresql"
|
||||
|
@ -75,6 +76,7 @@ func Commands(metaPtr *command.Meta) map[string]cli.CommandFactory {
|
|||
"transit": transit.Factory,
|
||||
"mysql": mysql.Factory,
|
||||
"ssh": ssh.Factory,
|
||||
"jwt": jwt.Factory,
|
||||
},
|
||||
ShutdownCh: makeShutdownCh(),
|
||||
}, nil
|
||||
|
|
|
@ -315,23 +315,30 @@ func (m *Meta) loadCertFromPEM(path string) ([]*x509.Certificate, error) {
|
|||
func generalOptionsUsage() string {
|
||||
general := `
|
||||
-address=addr The address of the Vault server.
|
||||
Overrides the VAULT_ADDR environment variable if set.
|
||||
|
||||
-ca-cert=path Path to a PEM encoded CA cert file to use to
|
||||
verify the Vault server SSL certificate.
|
||||
Overrides the VAULT_CACERT environment variable if set.
|
||||
|
||||
-ca-path=path Path to a directory of PEM encoded CA cert files
|
||||
to verify the Vault server SSL certificate. If both
|
||||
-ca-cert and -ca-path are specified, -ca-path is used.
|
||||
Overrides the VAULT_CAPATH environment variable if set.
|
||||
|
||||
-client-cert=path Path to a PEM encoded client certificate for TLS
|
||||
authentication to the Vault server. Must also specify
|
||||
-client-key.
|
||||
-client-key. Overrides the VAULT_CLIENT_CERT
|
||||
environment variable if set.
|
||||
|
||||
-client-key=path Path to an unencrypted PEM encoded private key
|
||||
matching the client certificate from -client-cert.
|
||||
Overrides the VAULT_CLIENT_KEY environment variable
|
||||
if set.
|
||||
|
||||
-tls-skip-verify Do not verify TLS certificate. This is highly
|
||||
not recommended.
|
||||
not recommended. Verification will also be skipped
|
||||
if VAULT_SKIP_VERIFY is set.
|
||||
`
|
||||
return strings.TrimSpace(general)
|
||||
}
|
||||
|
|
|
@ -16,7 +16,7 @@ type TokenCreateCommand struct {
|
|||
|
||||
func (c *TokenCreateCommand) Run(args []string) int {
|
||||
var format string
|
||||
var displayName, lease string
|
||||
var id, displayName, lease string
|
||||
var orphan bool
|
||||
var metadata map[string]string
|
||||
var numUses int
|
||||
|
@ -24,6 +24,7 @@ func (c *TokenCreateCommand) Run(args []string) int {
|
|||
flags := c.Meta.FlagSet("mount", FlagSetDefault)
|
||||
flags.StringVar(&format, "format", "table", "")
|
||||
flags.StringVar(&displayName, "display-name", "", "")
|
||||
flags.StringVar(&id, "id", "", "")
|
||||
flags.StringVar(&lease, "lease", "", "")
|
||||
flags.BoolVar(&orphan, "orphan", false, "")
|
||||
flags.IntVar(&numUses, "use-limit", 0, "")
|
||||
|
@ -50,6 +51,7 @@ func (c *TokenCreateCommand) Run(args []string) int {
|
|||
}
|
||||
|
||||
secret, err := client.Auth().Token().Create(&api.TokenCreateRequest{
|
||||
ID: id,
|
||||
Policies: policies,
|
||||
Metadata: metadata,
|
||||
Lease: lease,
|
||||
|
@ -92,6 +94,11 @@ General Options:
|
|||
|
||||
Token Options:
|
||||
|
||||
-id="7699125c-d8...." The token value that clients will use to authenticate
|
||||
with vault. If not provided this defaults to a 36
|
||||
character UUID. A root token is required to specify
|
||||
the ID of a token.
|
||||
|
||||
-display-name="name" A display name to associate with this token. This
|
||||
is a non-security sensitive value used to help
|
||||
identify created secrets, i.e. prefixes.
|
||||
|
|
|
@ -156,6 +156,11 @@ func respondError(w http.ResponseWriter, status int, err error) {
|
|||
status = http.StatusServiceUnavailable
|
||||
}
|
||||
|
||||
// Allow HTTPCoded error passthrough to specify a code
|
||||
if t, ok := err.(logical.HTTPCodedError); ok {
|
||||
status = t.Code()
|
||||
}
|
||||
|
||||
w.Header().Add("Content-Type", "application/json")
|
||||
w.WriteHeader(status)
|
||||
|
||||
|
|
|
@ -1,10 +1,13 @@
|
|||
package http
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"reflect"
|
||||
"testing"
|
||||
|
||||
"github.com/hashicorp/vault/logical"
|
||||
"github.com/hashicorp/vault/vault"
|
||||
)
|
||||
|
||||
|
@ -57,3 +60,34 @@ func TestHandler_sealed(t *testing.T) {
|
|||
}
|
||||
testResponseStatus(t, resp, 503)
|
||||
}
|
||||
|
||||
func TestHandler_error(t *testing.T) {
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
respondError(w, 500, errors.New("Test Error"))
|
||||
|
||||
if w.Code != 500 {
|
||||
t.Fatalf("expected 500, got %d", w.Code)
|
||||
}
|
||||
|
||||
// The code inside of the error should override
|
||||
// the argument to respondError
|
||||
w2 := httptest.NewRecorder()
|
||||
e := logical.CodedError(403, "error text")
|
||||
|
||||
respondError(w2, 500, e)
|
||||
|
||||
if w2.Code != 403 {
|
||||
t.Fatalf("expected 403, got %d", w2.Code)
|
||||
}
|
||||
|
||||
// vault.ErrSealed is a special case
|
||||
w3 := httptest.NewRecorder()
|
||||
|
||||
respondError(w3, 400, vault.ErrSealed)
|
||||
|
||||
if w3.Code != 503 {
|
||||
t.Fatalf("expected 503, got %d", w3.Code)
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -131,6 +131,7 @@ func handleSysMount(
|
|||
"description": req.Description,
|
||||
},
|
||||
}))
|
||||
|
||||
if err != nil {
|
||||
respondError(w, http.StatusInternalServerError, err)
|
||||
return
|
||||
|
@ -149,6 +150,7 @@ func handleSysUnmount(
|
|||
Path: "sys/mounts/" + path,
|
||||
Connection: getConnection(r),
|
||||
}))
|
||||
|
||||
if err != nil {
|
||||
respondError(w, http.StatusInternalServerError, err)
|
||||
return
|
||||
|
|
|
@ -0,0 +1,24 @@
|
|||
package logical
|
||||
|
||||
type HTTPCodedError interface {
|
||||
Error() string
|
||||
Code() int
|
||||
}
|
||||
|
||||
func CodedError(c int, s string) HTTPCodedError {
|
||||
return &codedError{s,c}
|
||||
}
|
||||
|
||||
type codedError struct {
|
||||
s string
|
||||
code int
|
||||
}
|
||||
|
||||
func (e *codedError) Error() string {
|
||||
return e.s
|
||||
}
|
||||
|
||||
func (e *codedError) Code() int {
|
||||
return e.code
|
||||
}
|
||||
|
|
@ -118,12 +118,20 @@ func (b *Backend) HandleRequest(req *logical.Request) (*logical.Response, error)
|
|||
if !ok {
|
||||
return nil, logical.ErrUnsupportedOperation
|
||||
}
|
||||
|
||||
fd := FieldData{
|
||||
Raw: raw,
|
||||
Schema: path.Fields}
|
||||
|
||||
if req.Operation != logical.HelpOperation {
|
||||
err := fd.Validate()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
// Call the callback with the request and the data
|
||||
return callback(req, &FieldData{
|
||||
Raw: raw,
|
||||
Schema: path.Fields,
|
||||
})
|
||||
return callback(req, &fd)
|
||||
}
|
||||
|
||||
// logical.Backend impl.
|
||||
|
|
|
@ -77,6 +77,42 @@ func TestBackendHandleRequest(t *testing.T) {
|
|||
}
|
||||
}
|
||||
|
||||
func TestBackendHandleRequest_badwrite(t *testing.T) {
|
||||
callback := func(req *logical.Request, data *FieldData) (*logical.Response, error) {
|
||||
return &logical.Response{
|
||||
Data: map[string]interface{}{
|
||||
"value": data.Get("value").(bool),
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
|
||||
b := &Backend{
|
||||
Paths: []*Path{
|
||||
&Path{
|
||||
Pattern: "foo/bar",
|
||||
Fields: map[string]*FieldSchema{
|
||||
"value": &FieldSchema{Type: TypeBool},
|
||||
},
|
||||
Callbacks: map[logical.Operation]OperationFunc{
|
||||
logical.WriteOperation: callback,
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
_, err := b.HandleRequest(&logical.Request{
|
||||
Operation: logical.WriteOperation,
|
||||
Path: "foo/bar",
|
||||
Data: map[string]interface{}{"value": "3false3"},
|
||||
})
|
||||
|
||||
|
||||
if err == nil {
|
||||
t.Fatalf("should have thrown a conversion error")
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func TestBackendHandleRequest_404(t *testing.T) {
|
||||
callback := func(req *logical.Request, data *FieldData) (*logical.Response, error) {
|
||||
return &logical.Response{
|
||||
|
|
|
@ -18,6 +18,33 @@ type FieldData struct {
|
|||
Schema map[string]*FieldSchema
|
||||
}
|
||||
|
||||
// Cycle through raw data and validate conversions in
|
||||
// the schema, so we don't get an error/panic later when
|
||||
// trying to get data out. Data not in the schema is not
|
||||
// an error at this point, so we don't worry about it.
|
||||
func (d *FieldData) Validate() error {
|
||||
for field, value := range d.Raw {
|
||||
|
||||
schema, ok := d.Schema[field]
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
|
||||
switch schema.Type {
|
||||
case TypeBool, TypeInt, TypeMap, TypeDurationSecond, TypeString:
|
||||
_, _, err := d.getPrimitive(field, schema)
|
||||
if err != nil {
|
||||
return fmt.Errorf("Error converting input %v for field %s", value, field)
|
||||
}
|
||||
default:
|
||||
return fmt.Errorf("unknown field type %s for field %s",
|
||||
schema.Type, field)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Get gets the value for the given field. If the key is an invalid field,
|
||||
// FieldData will panic. If you want a safer version of this method, use
|
||||
// GetOk. If the field k is not set, the default value (if set) will be
|
||||
|
|
|
@ -145,6 +145,6 @@ var (
|
|||
// ErrInvalidRequest is returned if the request is invalid
|
||||
ErrInvalidRequest = errors.New("invalid request")
|
||||
|
||||
// ErrPermissionDeneid is returned if the client is not authorized
|
||||
// ErrPermissionDenied is returned if the client is not authorized
|
||||
ErrPermissionDenied = errors.New("permission denied")
|
||||
)
|
||||
|
|
|
@ -13,7 +13,7 @@ const (
|
|||
// avoided like the HTTPContentType. The value must be a byte slice.
|
||||
HTTPRawBody = "http_raw_body"
|
||||
|
||||
// HTTPStatusCode is the response code the HTTP body that goes with the HTTPContentType.
|
||||
// HTTPStatusCode is the response code of the HTTP body that goes with the HTTPContentType.
|
||||
// This can only be specified for non-secrets, and should should be similarly
|
||||
// avoided like the HTTPContentType. The value must be an integer.
|
||||
HTTPStatusCode = "http_status_code"
|
||||
|
|
|
@ -371,9 +371,21 @@ func (b *SystemBackend) handleMount(
|
|||
// Attempt mount
|
||||
if err := b.Core.mount(me); err != nil {
|
||||
b.Backend.Logger().Printf("[ERR] sys: mount %#v failed: %v", me, err)
|
||||
return handleError(err)
|
||||
}
|
||||
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
// used to intercept an HTTPCodedError so it goes back to callee
|
||||
func handleError(
|
||||
err error) (*logical.Response, error) {
|
||||
switch err.(type) {
|
||||
case logical.HTTPCodedError:
|
||||
return logical.ErrorResponse(err.Error()), err
|
||||
default:
|
||||
return logical.ErrorResponse(err.Error()), logical.ErrInvalidRequest
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
// handleUnmount is used to unmount a path
|
||||
|
@ -387,7 +399,7 @@ func (b *SystemBackend) handleUnmount(
|
|||
// Attempt unmount
|
||||
if err := b.Core.unmount(suffix); err != nil {
|
||||
b.Backend.Logger().Printf("[ERR] sys: unmount '%s' failed: %v", suffix, err)
|
||||
return logical.ErrorResponse(err.Error()), logical.ErrInvalidRequest
|
||||
return handleError(err)
|
||||
}
|
||||
|
||||
return nil, nil
|
||||
|
@ -408,7 +420,7 @@ func (b *SystemBackend) handleRemount(
|
|||
// Attempt remount
|
||||
if err := b.Core.remount(fromPath, toPath); err != nil {
|
||||
b.Backend.Logger().Printf("[ERR] sys: remount '%s' to '%s' failed: %v", fromPath, toPath, err)
|
||||
return logical.ErrorResponse(err.Error()), logical.ErrInvalidRequest
|
||||
return handleError(err)
|
||||
}
|
||||
|
||||
return nil, nil
|
||||
|
@ -428,7 +440,7 @@ func (b *SystemBackend) handleRenew(
|
|||
resp, err := b.Core.expiration.Renew(leaseID, increment)
|
||||
if err != nil {
|
||||
b.Backend.Logger().Printf("[ERR] sys: renew '%s' failed: %v", leaseID, err)
|
||||
return logical.ErrorResponse(err.Error()), logical.ErrInvalidRequest
|
||||
return handleError(err)
|
||||
}
|
||||
return resp, err
|
||||
}
|
||||
|
@ -442,7 +454,7 @@ func (b *SystemBackend) handleRevoke(
|
|||
// Invoke the expiration manager directly
|
||||
if err := b.Core.expiration.Revoke(leaseID); err != nil {
|
||||
b.Backend.Logger().Printf("[ERR] sys: revoke '%s' failed: %v", leaseID, err)
|
||||
return logical.ErrorResponse(err.Error()), logical.ErrInvalidRequest
|
||||
return handleError(err)
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
|
@ -456,7 +468,7 @@ func (b *SystemBackend) handleRevokePrefix(
|
|||
// Invoke the expiration manager directly
|
||||
if err := b.Core.expiration.RevokePrefix(prefix); err != nil {
|
||||
b.Backend.Logger().Printf("[ERR] sys: revoke prefix '%s' failed: %v", prefix, err)
|
||||
return logical.ErrorResponse(err.Error()), logical.ErrInvalidRequest
|
||||
return handleError(err)
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
|
@ -504,7 +516,7 @@ func (b *SystemBackend) handleEnableAuth(
|
|||
// Attempt enabling
|
||||
if err := b.Core.enableCredential(me); err != nil {
|
||||
b.Backend.Logger().Printf("[ERR] sys: enable auth %#v failed: %v", me, err)
|
||||
return logical.ErrorResponse(err.Error()), logical.ErrInvalidRequest
|
||||
return handleError(err)
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
|
@ -520,7 +532,7 @@ func (b *SystemBackend) handleDisableAuth(
|
|||
// Attempt disable
|
||||
if err := b.Core.disableCredential(suffix); err != nil {
|
||||
b.Backend.Logger().Printf("[ERR] sys: disable auth '%s' failed: %v", suffix, err)
|
||||
return logical.ErrorResponse(err.Error()), logical.ErrInvalidRequest
|
||||
return handleError(err)
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
|
@ -543,7 +555,7 @@ func (b *SystemBackend) handlePolicyRead(
|
|||
|
||||
policy, err := b.Core.policy.GetPolicy(name)
|
||||
if err != nil {
|
||||
return logical.ErrorResponse(err.Error()), logical.ErrInvalidRequest
|
||||
return handleError(err)
|
||||
}
|
||||
|
||||
if policy == nil {
|
||||
|
@ -567,7 +579,7 @@ func (b *SystemBackend) handlePolicySet(
|
|||
// Validate the rules parse
|
||||
parse, err := Parse(rules)
|
||||
if err != nil {
|
||||
return logical.ErrorResponse(err.Error()), logical.ErrInvalidRequest
|
||||
return handleError(err)
|
||||
}
|
||||
|
||||
// Override the name
|
||||
|
@ -575,7 +587,7 @@ func (b *SystemBackend) handlePolicySet(
|
|||
|
||||
// Update the policy
|
||||
if err := b.Core.policy.SetPolicy(parse); err != nil {
|
||||
return logical.ErrorResponse(err.Error()), logical.ErrInvalidRequest
|
||||
return handleError(err)
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
|
@ -585,7 +597,7 @@ func (b *SystemBackend) handlePolicyDelete(
|
|||
req *logical.Request, data *framework.FieldData) (*logical.Response, error) {
|
||||
name := data.Get("name").(string)
|
||||
if err := b.Core.policy.DeletePolicy(name); err != nil {
|
||||
return logical.ErrorResponse(err.Error()), logical.ErrInvalidRequest
|
||||
return handleError(err)
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
|
@ -640,7 +652,7 @@ func (b *SystemBackend) handleEnableAudit(
|
|||
// Attempt enabling
|
||||
if err := b.Core.enableAudit(me); err != nil {
|
||||
b.Backend.Logger().Printf("[ERR] sys: enable audit %#v failed: %v", me, err)
|
||||
return logical.ErrorResponse(err.Error()), logical.ErrInvalidRequest
|
||||
return handleError(err)
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
|
@ -653,7 +665,7 @@ func (b *SystemBackend) handleDisableAudit(
|
|||
// Attempt disable
|
||||
if err := b.Core.disableAudit(path); err != nil {
|
||||
b.Backend.Logger().Printf("[ERR] sys: disable audit '%s' failed: %v", path, err)
|
||||
return logical.ErrorResponse(err.Error()), logical.ErrInvalidRequest
|
||||
return handleError(err)
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
|
@ -673,7 +685,7 @@ func (b *SystemBackend) handleRawRead(
|
|||
|
||||
entry, err := b.Core.barrier.Get(path)
|
||||
if err != nil {
|
||||
return logical.ErrorResponse(err.Error()), logical.ErrInvalidRequest
|
||||
return handleError(err)
|
||||
}
|
||||
if entry == nil {
|
||||
return nil, nil
|
||||
|
@ -724,7 +736,7 @@ func (b *SystemBackend) handleRawDelete(
|
|||
}
|
||||
|
||||
if err := b.Core.barrier.Delete(path); err != nil {
|
||||
return logical.ErrorResponse(err.Error()), logical.ErrInvalidRequest
|
||||
return handleError(err)
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
|
@ -754,7 +766,7 @@ func (b *SystemBackend) handleRotate(
|
|||
newTerm, err := b.Core.barrier.Rotate()
|
||||
if err != nil {
|
||||
b.Backend.Logger().Printf("[ERR] sys: failed to create new encryption key: %v", err)
|
||||
return logical.ErrorResponse(err.Error()), logical.ErrInvalidRequest
|
||||
return handleError(err)
|
||||
}
|
||||
b.Backend.Logger().Printf("[INFO] sys: installed new encryption key")
|
||||
|
||||
|
|
|
@ -22,7 +22,7 @@ const (
|
|||
// barrier view for the backends.
|
||||
backendBarrierPrefix = "logical/"
|
||||
|
||||
// systemBarrierPrefix is sthe prefix used for the
|
||||
// systemBarrierPrefix is the prefix used for the
|
||||
// system logical backend.
|
||||
systemBarrierPrefix = "sys/"
|
||||
)
|
||||
|
@ -139,16 +139,16 @@ func (c *Core) mount(me *MountEntry) error {
|
|||
me.Path += "/"
|
||||
}
|
||||
|
||||
// Prevent protected paths from being unmounted
|
||||
// Prevent protected paths from being mounted
|
||||
for _, p := range protectedMounts {
|
||||
if strings.HasPrefix(me.Path, p) {
|
||||
return fmt.Errorf("cannot mount '%s'", me.Path)
|
||||
return logical.CodedError(403, fmt.Sprintf("cannot mount '%s'", me.Path))
|
||||
}
|
||||
}
|
||||
|
||||
// Verify there is no conflicting mount
|
||||
if match := c.router.MatchingMount(me.Path); match != "" {
|
||||
return fmt.Errorf("existing mount at '%s'", match)
|
||||
return logical.CodedError(409, fmt.Sprintf("existing mount at %s", match))
|
||||
}
|
||||
|
||||
// Generate a new UUID and view
|
||||
|
|
|
@ -0,0 +1,259 @@
|
|||
# JWT Secret Backend
|
||||
|
||||
Name: `jwt`
|
||||
|
||||
The JWT secret backend for Vault generates JSON Web Tokens dynamically based on configured roles. This means services can get tokens needed for authentication without going through the usual manual process of generating a private key and signing the token and maintaining the private key's security. Vault's built-in authentication and authorization mechanisms provide the verification functionality.
|
||||
|
||||
This page will show a quick start for this backend. For detailed documentation on every path, use `vault path-help` after mounting the backend.
|
||||
|
||||
The JWT secret backend acts like the `transit` backend, it does not store any information.
|
||||
|
||||
## Algorithms
|
||||
|
||||
### RSA
|
||||
* RS256
|
||||
* RS384
|
||||
* RS512
|
||||
|
||||
These require a RSA private/public keypair for signing and verification.
|
||||
|
||||
### ECDSA
|
||||
* EC256
|
||||
* EC384
|
||||
* EC512
|
||||
|
||||
These require an ECDSA private/public keypair for signing and verification.
|
||||
|
||||
### HMAC
|
||||
* HS256
|
||||
* HS384
|
||||
* HS512
|
||||
|
||||
These require a shared secret for signing and verification.
|
||||
|
||||
## Roles
|
||||
|
||||
Roles are defined with the signing algorithm, the secret key or private key to be used, as well as allowing for default but optional JWT Token claims. Once you write a private key or a secret to the role, it CANNOT be read back out.
|
||||
|
||||
## Quick Start
|
||||
|
||||
The first step to using the jwt backend is to mount it.
|
||||
Unlike the `generic` backend, the `jwt` backend is not mounted by default.
|
||||
|
||||
```text
|
||||
$ vault mount jwt
|
||||
Successfully mounted 'jwt' at 'jwt'!
|
||||
```
|
||||
|
||||
The next step is to configure a role. A role is a logical name that maps
|
||||
to a few settings used to generated the tokens. For example, lets create
|
||||
a "webauth" role:
|
||||
|
||||
```text
|
||||
$ vault write jwt/roles/webauth \
|
||||
algorithm=RS256 \
|
||||
key=@/path/to/private.key
|
||||
```
|
||||
|
||||
Each role requires a secret or a private key to be associated against it.
|
||||
|
||||
Generating a token requires passing of additional information so we use the
|
||||
"jwt/issue/ROLE" path.
|
||||
|
||||
```text
|
||||
$ vault write jwt/issue/webauth \
|
||||
issuer="Vault" \
|
||||
audience="Vault Client" \
|
||||
expiration="1538096292" \
|
||||
claims=@extra.json
|
||||
```
|
||||
|
||||
|
||||
## API
|
||||
|
||||
### /jwt/roles/
|
||||
#### POST
|
||||
|
||||
<dl class="api">
|
||||
<dt>Description</dt>
|
||||
<dd>
|
||||
Creates or updates a named role.
|
||||
</dd>
|
||||
|
||||
<dt>Method</dt>
|
||||
<dd>POST</dd>
|
||||
|
||||
<dt>URL</dt>
|
||||
<dd>`/jwt/roles/<name>`</dd>
|
||||
|
||||
<dt>Parameters</dt>
|
||||
<dd>
|
||||
<ul>
|
||||
<li>
|
||||
<span class="param">algorithm</span>
|
||||
<span class="param-flags">required</span>
|
||||
The algorithm used by JWT to sign the token.
|
||||
</li>
|
||||
<li>
|
||||
<span class="param">key</span>
|
||||
<span class="param-flags">required</span>
|
||||
The private key or string used to sign the token.
|
||||
</li>
|
||||
<li>
|
||||
<span class="param">default_issuer</span>
|
||||
<span class="param-flags">required</span>
|
||||
The default issuer claim for the role, can be overridden at issue time.
|
||||
</li>
|
||||
<li>
|
||||
<span class="param">default_subject</span>
|
||||
<span class="param-flags">required</span>
|
||||
The default subject claim for the role, can be overridden at issue time.
|
||||
</li>
|
||||
<li>
|
||||
<span class="param">default_audience</span>
|
||||
<span class="param-flags">required</span>
|
||||
The default audience claim for the role, can be overridden at issue time.
|
||||
</li>
|
||||
</ul>
|
||||
</dd>
|
||||
|
||||
<dt>Returns</dt>
|
||||
<dd>
|
||||
A `204` response code.
|
||||
</dd>
|
||||
</dl>
|
||||
|
||||
#### GET
|
||||
|
||||
<dl class="api">
|
||||
<dt>Description</dt>
|
||||
<dd>
|
||||
Queries a named role.
|
||||
</dd>
|
||||
|
||||
<dt>Method</dt>
|
||||
<dd>GET</dd>
|
||||
|
||||
<dt>URL</dt>
|
||||
<dd>`/jwt/roles/<name>`</dd>
|
||||
|
||||
<dt>Parameters</dt>
|
||||
<dd>
|
||||
None
|
||||
</dd>
|
||||
|
||||
<dt>Returns</dt>
|
||||
<dd>
|
||||
|
||||
```javascript
|
||||
{
|
||||
"data": {
|
||||
"algorithm": "..."
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
</dd>
|
||||
</dl>
|
||||
|
||||
#### DELETE
|
||||
|
||||
<dl class="api">
|
||||
<dt>Description</dt>
|
||||
<dd>
|
||||
Deletes a named role.
|
||||
</dd>
|
||||
|
||||
<dt>Method</dt>
|
||||
<dd>DELETE</dd>
|
||||
|
||||
<dt>URL</dt>
|
||||
<dd>`/jwt/roles/<name>`</dd>
|
||||
|
||||
<dt>Parameters</dt>
|
||||
<dd>
|
||||
None
|
||||
</dd>
|
||||
|
||||
<dt>Returns</dt>
|
||||
<dd>
|
||||
A `204` response code.
|
||||
</dd>
|
||||
</dl>
|
||||
|
||||
|
||||
### /jwt/issue/
|
||||
#### POST
|
||||
|
||||
<dl class="api">
|
||||
<dt>Description</dt>
|
||||
<dd>
|
||||
Generates a JWT token based on the named role.
|
||||
</dd>
|
||||
|
||||
<dt>Method</dt>
|
||||
<dd>GET</dd>
|
||||
|
||||
<dt>URL</dt>
|
||||
<dd>`/jwt/issue/<role>`</dd>
|
||||
|
||||
<dt>Parameters</dt>
|
||||
<dd>
|
||||
<ul>
|
||||
<li>
|
||||
<span class="param">issuer</span>
|
||||
<span class="param-flags">optional</span>
|
||||
The Issuer of the token.
|
||||
</li>
|
||||
<li>
|
||||
<span class="param">audience</span>
|
||||
<span class="param-flags">optional</span>
|
||||
The Audience of the token.
|
||||
</li>
|
||||
<li>
|
||||
<span class="param">subject</span>
|
||||
<span class="param-flags">optional</span>
|
||||
The Subject of the token.
|
||||
</li>
|
||||
<li>
|
||||
<span class="param">expiration</span>
|
||||
<span class="param-flags">optional</span>
|
||||
The expiration of the token, expressed in seconds (unix time).
|
||||
</li>
|
||||
<li>
|
||||
<span class="param">issued_at</span>
|
||||
<span class="param-flags">optional</span>
|
||||
The issued at time of the token, expressed in seconds (unix time). (Default: current time)
|
||||
</li>
|
||||
<li>
|
||||
<span class="param">not_before</span>
|
||||
<span class="param-flags">optional</span>
|
||||
Not Before: the time at which the token is not useful before. Expressed as seconds, unix time. (Default: current time)
|
||||
</li>
|
||||
<li>
|
||||
<span class="param">jti</span>
|
||||
<span class="param-flags">optional</span>
|
||||
JSONWebToken Identifier. Unique ID useful for preventing replay attacks. (Default: Random UUID)
|
||||
</li>
|
||||
<li>
|
||||
<span class="param">claims</span>
|
||||
<span class="param-flags">optional</span>
|
||||
Should be a JSON Object of additional key/values you want in the token.
|
||||
</li>
|
||||
</ul>
|
||||
</dd>
|
||||
|
||||
<dt>Returns</dt>
|
||||
<dd>
|
||||
|
||||
```javascript
|
||||
{
|
||||
"data": {
|
||||
"jti": "...",
|
||||
"token": "..."
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
</dd>
|
||||
</dl>
|
Loading…
Reference in New Issue