-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathencoder.go
61 lines (57 loc) · 1.51 KB
/
encoder.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
package jwt
import (
"encoding/base64"
"encoding/json"
)
type Encoder struct {
secret []byte
headers headers
encodedHeader string
algorithm Algorithm
}
func NewEncoder(options ...EncoderOption) *Encoder {
this := &Encoder{headers: headers{Type: "JWT"}}
this.setOptions(options)
this.setDefaultAlgorithm()
this.encodedHeader = this.header()
return this
}
func (this *Encoder) setOptions(options []EncoderOption) {
for _, option := range options {
option(this)
}
}
func (this *Encoder) setDefaultAlgorithm() {
if this.algorithm == nil {
WithEncodingAlgorithm(HS256{})(this)
}
}
func (this *Encoder) Encode(claims interface{}) (token string, err error) {
serialized, err := json.Marshal(claims)
if err != nil {
return "", err
}
return this.composeToken(serialized), nil
}
func (this *Encoder) composeToken(serialized []byte) (token string) {
token += this.encodedHeader
token += this.payload(serialized)
token += this.signature(token)
return token
}
func (this *Encoder) header() string {
serialized, _ := json.Marshal(this.headers)
return base64Encode(serialized)
}
func (this *Encoder) payload(serialized []byte) string {
return "." + base64Encode(serialized)
}
func (this *Encoder) signature(token string) string {
return "." + base64Encode(this.calculateSignature(token))
}
func (this *Encoder) calculateSignature(token string) []byte {
return this.algorithm.ComputeHash([]byte(token), this.secret)
}
func base64Encode(in []byte) string {
return base64.RawURLEncoding.EncodeToString(in)
}