-
Notifications
You must be signed in to change notification settings - Fork 4
/
publickey.go
76 lines (67 loc) · 1.76 KB
/
publickey.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
package publickey
import (
"crypto/rsa"
"fmt"
"io/ioutil"
"strings"
"time"
jwt "github.com/dgrijalva/jwt-go"
"github.com/pkg/errors"
"go.uber.org/zap"
)
// Publickey struct
type Publickey struct {
publicKeyFile string
verifyKey *rsa.PublicKey
freshnessTime time.Duration
}
// New publickey reader/checker
func New(publicKeyFile string, freshnessTime time.Duration, logger *zap.Logger) (*Publickey, error) {
var verifyKey *rsa.PublicKey
if publicKeyFile != "" {
verifyBytes, err := ioutil.ReadFile(publicKeyFile)
if err != nil {
return nil, errors.Wrap(err, "Failed read pubkey")
}
verifyKey, err = jwt.ParseRSAPublicKeyFromPEM(verifyBytes)
if err != nil {
return nil, errors.Wrap(err, "Failed parse pubkey")
}
}
return &Publickey{
publicKeyFile: publicKeyFile,
verifyKey: verifyKey,
freshnessTime: freshnessTime,
}, nil
}
// Enabled publickey is enabled
func (pk Publickey) Enabled() bool {
return pk.publicKeyFile != ""
}
// Verify verify auth header
func (pk Publickey) Verify(t string) (string, error) {
if t == "" {
return "", fmt.Errorf("no tokenString")
}
t = strings.TrimPrefix(t, "Bearer ")
claims := &jwt.StandardClaims{}
jwp := &jwt.Parser{
ValidMethods: []string{"RS256", "RS384", "RS512"},
SkipClaimsValidation: false,
}
_, err := jwp.ParseWithClaims(t, claims, func(token *jwt.Token) (interface{}, error) {
return pk.verifyKey, nil
})
if err != nil {
return "", fmt.Errorf("Token is invalid: %v", err)
}
now := time.Now()
iat := now.Add(-pk.freshnessTime)
if claims.ExpiresAt == 0 || claims.ExpiresAt < now.Unix() {
return "", fmt.Errorf("Token is expired")
}
if claims.IssuedAt == 0 || claims.IssuedAt < iat.Unix() {
return "", fmt.Errorf("Token is too old")
}
return claims.Subject, nil
}