/
authenticator.go
91 lines (75 loc) 路 2.18 KB
/
authenticator.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
package auth
import (
"crypto/rand"
"crypto/x509"
"encoding/pem"
"fmt"
"math"
"math/big"
"strings"
"time"
"gopkg.in/square/go-jose.v2"
"gopkg.in/square/go-jose.v2/jwt"
)
// Authenticator builds a JWT based on the APIKey.
type Authenticator struct {
apiKey *APIKey
}
// APIKeyClaims holds public claim values for a JWT, as well as a URI.
type APIKeyClaims struct {
*jwt.Claims
URI string `json:"uri"`
}
// NewAuthenticator returns a new Authenticator.
func NewAuthenticator(apiKey *APIKey) *Authenticator {
return &Authenticator{
apiKey: apiKey,
}
}
// BuildJWT constructs and returns the JWT as a string along with an error, if any.
func (a *Authenticator) BuildJWT(service, uri string) (string, error) {
privateKey := a.apiKey.PrivateKey
// Replace escaped newline sequence
privateKey = strings.ReplaceAll(privateKey, "\\n", "\n")
block, _ := pem.Decode([]byte(privateKey))
if block == nil {
return "", fmt.Errorf("could not decode private key")
}
key, err := x509.ParseECPrivateKey(block.Bytes)
if err != nil {
return "", fmt.Errorf("could not parse private key: %w", err)
}
sig, err := jose.NewSigner(
jose.SigningKey{Algorithm: jose.ES256, Key: key},
(&jose.SignerOptions{NonceSource: nonceSource{}}).WithType("JWT").WithHeader("kid", a.apiKey.Name),
)
if err != nil {
return "", fmt.Errorf("could not create signer: %w", err)
}
cl := &APIKeyClaims{
Claims: &jwt.Claims{
Subject: a.apiKey.Name,
Issuer: "coinbase-cloud",
NotBefore: jwt.NewNumericDate(time.Now()),
Expiry: jwt.NewNumericDate(time.Now().Add(1 * time.Minute)),
Audience: jwt.Audience{service},
},
URI: uri,
}
jwtString, err := jwt.Signed(sig).Claims(cl).CompactSerialize()
if err != nil {
return "", fmt.Errorf("could not sign: %w", err)
}
return jwtString, nil
}
// nonceSource implements the jose.NonceSource interface. It is used for building
// the JWT.
type nonceSource struct{}
// Nonce calculates and returns nonce as a string and an error, if any.
func (n nonceSource) Nonce() (string, error) {
r, err := rand.Int(rand.Reader, big.NewInt(math.MaxInt64))
if err != nil {
return "", fmt.Errorf("could not generate nonce: %w", err)
}
return r.String(), nil
}