-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcreate.go
49 lines (41 loc) · 1.19 KB
/
create.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
package jwt
import (
"encoding/base64"
"encoding/json"
"strings"
)
// Create creates a JWT token string from a set of claims and a Signer. An error is
// returned if something goes wrong in the JSON marshalling process for the claims,
// or in the signing process.
func Create(claims any, signer Signer) (string, error) {
// Create the header and marshal to JSON bytes
header := Header{
Alg: signer.Alg(),
Typ: "JWT",
Kid: signer.Kid(),
}
headerBytes, err := json.Marshal(header)
if err != nil {
return "", err
}
// Marshal the claims to JSON bytes
claimsBytes, err := json.Marshal(claims)
if err != nil {
return "", err
}
// Encode the header and claims to base64 URL encoded
headerBase64URL := base64.RawURLEncoding.EncodeToString(headerBytes)
claimsBase64URL := base64.RawURLEncoding.EncodeToString(claimsBytes)
// Sign the joined string of the two
signatureBytes, err := signer.Sign([]byte(headerBase64URL + "." + claimsBase64URL))
if err != nil {
return "", err
}
signatureBase64URL := base64.RawURLEncoding.EncodeToString(signatureBytes)
// Return the joined segments
return strings.Join([]string{
headerBase64URL,
claimsBase64URL,
signatureBase64URL,
}, "."), nil
}