-
Notifications
You must be signed in to change notification settings - Fork 4
/
builder.go
68 lines (59 loc) · 1.6 KB
/
builder.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
package atlas_claims
import (
"fmt"
"strings"
"time"
"github.com/golang-jwt/jwt/v4"
)
const (
STKAudience = "ib-stk"
DefaultIssuer = "atlas-claims"
DefaultAudience = STKAudience
DefaultService = "all"
DefaultSubjectType = "s2s"
DefaultSubjectAuthType = "bearer"
)
func BuildJwt(claims *Claims, hmacKey string, expires_duration time.Duration) (string, error) {
if len(strings.TrimSpace(hmacKey)) < 1 {
return "", fmt.Errorf("non-empty hmac key is required")
}
// standard claims
if claims.Issuer == "" {
claims.Issuer = DefaultIssuer
}
if claims.Audience == "" {
claims.Audience = DefaultAudience
}
if claims.IssuedAt == 0 {
claims.IssuedAt = time.Now().Unix()
}
if claims.NotBefore == 0 {
claims.NotBefore = claims.IssuedAt
}
if claims.ExpiresAt == 0 {
claims.ExpiresAt = time.Unix(claims.IssuedAt, 0).Add(expires_duration).Unix()
}
// non-standard claims
if claims.AccountId == "" && claims.Audience != STKAudience {
claims.AccountId = "0"
}
if claims.Service == "" {
claims.Service = DefaultService
}
if claims.Subject.Id == "" {
claims.Subject.Id = fmt.Sprintf("service.%s.%d", claims.Service, claims.IssuedAt)
}
if claims.Subject.SubjectType == "" {
claims.Subject.SubjectType = DefaultSubjectType
}
if claims.Subject.AuthenticationType == "" {
claims.Subject.AuthenticationType = DefaultSubjectAuthType
}
// sign the jwt
token := jwt.NewWithClaims(jwt.SigningMethodHS512, claims)
tokenString, err := token.SignedString([]byte(hmacKey))
if err != nil {
return "", fmt.Errorf("failed to sign claim: %v", err)
}
return tokenString, nil
}