-
Notifications
You must be signed in to change notification settings - Fork 0
/
verifier.go
61 lines (50 loc) · 1.47 KB
/
verifier.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 mjwt
import (
"crypto/rsa"
"crypto/x509"
"encoding/pem"
"github.com/golang-jwt/jwt/v4"
"os"
)
// defaultMJwtVerifier implements Verifier and uses a rsa.PublicKey to validate
// MJWT tokens
type defaultMJwtVerifier struct {
pub *rsa.PublicKey
}
var _ Verifier = &defaultMJwtVerifier{}
// NewMJwtVerifier creates a new defaultMJwtVerifier using the rsa.PublicKey
func NewMJwtVerifier(key *rsa.PublicKey) Verifier {
return newMJwtVerifier(key)
}
func newMJwtVerifier(key *rsa.PublicKey) *defaultMJwtVerifier {
return &defaultMJwtVerifier{pub: key}
}
// NewMJwtVerifierFromFile creates a new defaultMJwtVerifier using the path of a
// rsa.PublicKey file
func NewMJwtVerifierFromFile(file string) (Verifier, error) {
// read file
f, err := os.ReadFile(file)
if err != nil {
return nil, err
}
// decode pem block
block, _ := pem.Decode(f)
// parse public key from pem block
pub, err := x509.ParsePKCS1PublicKey(block.Bytes)
if err != nil {
return nil, err
}
// create verifier using rsa.PublicKey
return NewMJwtVerifier(pub), nil
}
// VerifyJwt validates and parses MJWT tokens and returns the claims
func (d *defaultMJwtVerifier) VerifyJwt(token string, claims baseTypeClaim) (*jwt.Token, error) {
withClaims, err := jwt.ParseWithClaims(token, claims, func(token *jwt.Token) (interface{}, error) {
return d.pub, nil
})
if err != nil {
return nil, err
}
return withClaims, claims.Valid()
}
func (d *defaultMJwtVerifier) PublicKey() *rsa.PublicKey { return d.pub }