-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathissuer.go
68 lines (56 loc) · 1.62 KB
/
issuer.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 token
import (
"errors"
"fmt"
"time"
"github.com/golang-jwt/jwt/v4"
"github.com/google/uuid"
)
// IssuerJWT issues JWT tokens.
type IssuerJWT struct {
privateKey []byte
}
// IssuerName is the expected name of the issuer for any token
// issued by sentinel.
const IssuerName = "myst-sentinel"
// NewIssuerJWT returns a new IssuerJWT object.
func NewIssuerJWT(privateKey []byte) *IssuerJWT {
jwt.TimeFunc = func() time.Time {
return time.Now().UTC()
}
return &IssuerJWT{
privateKey: privateKey,
}
}
const (
CustomClaimIssuerType = "isst"
)
// Issue will issue a new JWT token setting given parameters inside the claims.
func (j *IssuerJWT) Issue(sub string, aud []string, issuertype string, ttl time.Duration, attr string, username string) (string, error) {
if sub == "" || len(aud) < 1 || issuertype == "" {
return "", errors.New("'sub', 'aud', 'issuertype' claims must be set")
}
key, err := jwt.ParseRSAPrivateKeyFromPEM(j.privateKey)
if err != nil {
return "", fmt.Errorf("create: parse key: %w", err)
}
now := jwt.TimeFunc()
id := uuid.New()
claims := jwt.MapClaims{
"exp": now.Add(ttl).Unix(),
"iat": now.Unix(),
"nbf": now.Unix(),
"iss": IssuerName,
"aud": aud,
"sub": sub,
"attr": attr,
"jti": id.String(),
"username": username,
CustomClaimIssuerType: issuertype,
}
token, err := jwt.NewWithClaims(jwt.SigningMethodRS256, claims).SignedString(key)
if err != nil {
return "", fmt.Errorf("create: sign token: %w", err)
}
return token, nil
}