-
Notifications
You must be signed in to change notification settings - Fork 2
/
jwt.go
43 lines (38 loc) · 1.47 KB
/
jwt.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
package toolslib
import (
"github.com/btcsuite/btcd/btcec"
"github.com/fatih/structs"
"github.com/golang-jwt/jwt/v4"
"github.com/pkg/errors"
)
// Generate a JWT Token for the provided private key.
// This can be added to the payload for requests that require JWT token authentication.
func GenerateJWTToken(privKey *btcec.PrivateKey) (_JWT string, _err error) {
// Create the ecdsa keys
ecdsaPrivKey := privKey.ToECDSA()
// Create a new JWT Token
token := jwt.New(jwt.SigningMethodES256)
// Sign using the ECDSA private key
jwtToken, err := token.SignedString(ecdsaPrivKey)
if err != nil {
return "", errors.Wrap(err, "GenerateJWTToken() failed to sign token")
}
return jwtToken, nil
}
// Add a JWT token to the specified request payload interface using a provided private key.
//
// Here's an example on how this can be used to execute a request as an admin:
// payload := routes.AdminUpdateUserGlobalMetadataRequest{ ... }
// mPayload, _ := toolslib.AddJWT(payload, adminPrivKey)
// postBody, _ := json.Marshal(mPayload)
// postBuffer := bytes.NewBuffer(postBody)
// resp, _ := http.Post(endpoint, "application/json", postBuffer)
func AddJWT(requestPayload interface{}, privKey *btcec.PrivateKey) (_jwtPayload interface{}, _err error) {
jwtToken, err := GenerateJWTToken(privKey)
if err != nil {
return nil, errors.Wrap(err, "AddJWT() failed to generate jwtToken for private key")
}
mPayload := structs.Map(requestPayload)
mPayload["JWT"] = jwtToken
return mPayload, nil
}