/
jwt.go
84 lines (66 loc) · 1.82 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 authn
import (
"crypto/rsa"
"net/http"
"os"
"strings"
"time"
"github.com/cockroachdb/errors"
"github.com/lestrrat-go/jwx/jwa"
"github.com/lestrrat-go/jwx/jwt"
"golang.org/x/crypto/ssh"
)
type JWTAuthenticator struct {
PublicKey rsa.PublicKey
}
func BuildJWTAuthenticator(publicKey rsa.PublicKey) (*JWTAuthenticator, error) {
return &JWTAuthenticator{
PublicKey: publicKey,
}, nil
}
func LoadSSHPublicKey(fpath string) (*rsa.PublicKey, error) {
sshPublicKey, err := os.ReadFile(fpath)
if err != nil {
return nil, errors.Wrap(err, "failed to read public key file")
}
pubKey, _, _, _, err := ssh.ParseAuthorizedKey(sshPublicKey)
if err != nil {
return nil, errors.Wrap(err, "failed to parse SSH public key")
}
parsedCryptoPublicKey := pubKey.(ssh.CryptoPublicKey)
cryptoPublicKey := parsedCryptoPublicKey.CryptoPublicKey()
rsaPubKey, ok := cryptoPublicKey.(*rsa.PublicKey)
if !ok {
return nil, errors.New("failed to type casting for rsa.PublicKey")
}
return rsaPubKey, nil
}
func (a *JWTAuthenticator) Auth(req *http.Request) (*Result, error) {
token := req.Header.Get("Authorization")
if token == "" {
return nil, errors.New("authorization header is empty value")
}
ts := strings.TrimPrefix(token, "Bearer ")
t, err := a.Verify(ts)
if err != nil {
return nil, errors.Wrap(err, "failed to verify token")
}
return &Result{Requester: t.Subject()}, nil
}
func (a *JWTAuthenticator) Verify(token string) (jwt.Token, error) {
t, err := jwt.ParseString(token, jwt.WithVerify(jwa.RS256, a.PublicKey))
if err != nil {
return nil, errors.Wrap(err, "failed to parse jwt")
}
return t, nil
}
func BuildJWT() jwt.Token {
token := jwt.New()
_ = token.Set(jwt.IssuedAtKey, time.Now())
hostname, err := os.Hostname()
if err != nil {
panic(err)
}
_ = token.Set(jwt.SubjectKey, hostname)
return token
}