forked from dunglas/mercure
-
Notifications
You must be signed in to change notification settings - Fork 0
/
jwt_keyfunc.go
52 lines (42 loc) · 1.23 KB
/
jwt_keyfunc.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
package mercure
import (
"errors"
"fmt"
"github.com/golang-jwt/jwt/v5"
)
// ErrUnexpectedSigningMethod is returned when the signing JWT method is not supported.
var ErrUnexpectedSigningMethod = errors.New("unexpected signing method")
func createJWTKeyfunc(key []byte, alg string) (jwt.Keyfunc, error) {
signingMethod := jwt.GetSigningMethod(alg)
var k interface{}
switch signingMethod.(type) {
case *jwt.SigningMethodHMAC:
k = key
case *jwt.SigningMethodRSA:
pub, err := jwt.ParseRSAPublicKeyFromPEM(key)
if err != nil {
return nil, fmt.Errorf("unable to parse RSA public key: %w", err)
}
k = pub
case *jwt.SigningMethodECDSA:
pub, err := jwt.ParseECPublicKeyFromPEM(key)
if err != nil {
return nil, fmt.Errorf("unable to parse EC public key: %w", err)
}
k = pub
case *jwt.SigningMethodEd25519:
pub, err := jwt.ParseEdPublicKeyFromPEM(key)
if err != nil {
return nil, fmt.Errorf("unable to parse Ed public key: %w", err)
}
k = pub
default:
return nil, fmt.Errorf("%T: %w", signingMethod, ErrUnexpectedSigningMethod)
}
return func(t *jwt.Token) (interface{}, error) {
if t.Method != signingMethod {
return nil, fmt.Errorf("%T: %w", t.Method, ErrUnexpectedSigningMethod)
}
return k, nil
}, nil
}