-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathjwt.go
84 lines (71 loc) · 1.37 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
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
package apnsapi
import (
"bytes"
"crypto"
"crypto/ecdsa"
"crypto/rand"
"encoding/asn1"
"encoding/base64"
"encoding/json"
"io"
"math/big"
"time"
)
type jwtHeader struct {
Alg string `json:"alg"`
Kid string `json:"kid"`
}
type jwtClaim struct {
Iss string `json:"iss"`
Iat int64 `json:"iat"`
}
type ecdsaSignature struct {
R, S *big.Int
}
func CreateToken(key *ecdsa.PrivateKey, kid string, teamID string) (string, error) {
header := jwtHeader{
Alg: "ES256",
Kid: kid,
}
claim := jwtClaim{
Iss: teamID,
Iat: time.Now().Unix(),
}
var b bytes.Buffer
headerJson, err := json.Marshal(&header)
if err != nil {
return "", err
}
if err := base64Encode(&b, headerJson); err != nil {
return "", err
}
b.WriteString(".")
claimJson, err := json.Marshal(&claim)
if err != nil {
return "", err
}
if err := base64Encode(&b, claimJson); err != nil {
return "", err
}
h := crypto.SHA256.New()
h.Write(b.Bytes())
msg := h.Sum(nil)
r, s, err := ecdsa.Sign(rand.Reader, key, msg)
if err != nil {
return "", err
}
sig, err := asn1.Marshal(ecdsaSignature{r, s})
if err != nil {
return "", err
}
b.WriteString(".")
if err := base64Encode(&b, sig); err != nil {
return "", err
}
return b.String(), nil
}
func base64Encode(w io.Writer, byt []byte) error {
enc := base64.NewEncoder(base64.RawURLEncoding, w)
enc.Write(byt)
return enc.Close()
}