forked from lestrrat-go/jwx
-
Notifications
You must be signed in to change notification settings - Fork 0
/
verifier.go
68 lines (57 loc) · 1.99 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
62
63
64
65
66
67
68
package jws
import (
"github.com/lestrrat-go/jwx/jwa"
"github.com/pkg/errors"
)
type VerifierFactory interface {
Create() (Verifier, error)
}
type VerifierFactoryFn func() (Verifier, error)
func (fn VerifierFactoryFn) Create() (Verifier, error) {
return fn()
}
var verifierDB map[jwa.SignatureAlgorithm]VerifierFactory
// RegisterVerifier is used to register a factory object that creates
// Verifier objects based on the given algorithm.
//
// For example, if you would like to provide a custom verifier for
// jwa.EdDSA, use this function to register a `VerifierFactory`
// (probably in your `init()`)
func RegisterVerifier(alg jwa.SignatureAlgorithm, f VerifierFactory) {
verifierDB[alg] = f
}
func init() {
verifierDB = make(map[jwa.SignatureAlgorithm]VerifierFactory)
for _, alg := range []jwa.SignatureAlgorithm{jwa.RS256, jwa.RS384, jwa.RS512, jwa.PS256, jwa.PS384, jwa.PS512} {
RegisterVerifier(alg, func(alg jwa.SignatureAlgorithm) VerifierFactory {
return VerifierFactoryFn(func() (Verifier, error) {
return newRSAVerifier(alg), nil
})
}(alg))
}
for _, alg := range []jwa.SignatureAlgorithm{jwa.ES256, jwa.ES384, jwa.ES512, jwa.ES256K} {
RegisterVerifier(alg, func(alg jwa.SignatureAlgorithm) VerifierFactory {
return VerifierFactoryFn(func() (Verifier, error) {
return newECDSAVerifier(alg), nil
})
}(alg))
}
for _, alg := range []jwa.SignatureAlgorithm{jwa.HS256, jwa.HS384, jwa.HS512} {
RegisterVerifier(alg, func(alg jwa.SignatureAlgorithm) VerifierFactory {
return VerifierFactoryFn(func() (Verifier, error) {
return newHMACVerifier(alg), nil
})
}(alg))
}
RegisterVerifier(jwa.EdDSA, VerifierFactoryFn(func() (Verifier, error) {
return newEdDSAVerifier(), nil
}))
}
// NewVerifier creates a verifier that signs payloads using the given signature algorithm.
func NewVerifier(alg jwa.SignatureAlgorithm) (Verifier, error) {
f, ok := verifierDB[alg]
if ok {
return f.Create()
}
return nil, errors.Errorf(`unsupported signature algorithm "%s"`, alg)
}