This repository has been archived by the owner on Apr 26, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 72
/
Copy pathauthenticator.go
82 lines (71 loc) · 1.95 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
package auth
import (
"crypto/rand"
"crypto/x509"
"encoding/pem"
"fmt"
"math"
"math/big"
"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) {
block, _ := pem.Decode([]byte(a.apiKey.PrivateKey))
if block == nil {
return "", fmt.Errorf("jwt: Could not decode private key")
}
key, err := x509.ParseECPrivateKey(block.Bytes)
if err != nil {
return "", fmt.Errorf("jwt: %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("jwt: %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("jwt: %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 "", err
}
return r.String(), nil
}