-
Notifications
You must be signed in to change notification settings - Fork 47
/
Copy pathauth0.go
99 lines (81 loc) · 2.3 KB
/
auth0.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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
package auth0
import (
"gopkg.in/square/go-jose.v2"
"gopkg.in/square/go-jose.v2/jwt"
"net/http"
"time"
)
type SecretProvider interface {
GetSecret(req *http.Request) (interface{}, error)
}
type SecretProviderFunc func(req *http.Request) (interface{}, error)
func (f SecretProviderFunc) GetSecret(req *http.Request) (interface{}, error) {
return f(req)
}
func NewKeyProvider(key interface{}) SecretProvider {
return SecretProviderFunc(func(req *http.Request) (interface{}, error) {
return key, nil
})
}
// Configuration contains
// all the informations about the
// Auth0 service.
type Configuration struct {
secretProvider SecretProvider
expectedClaims jwt.Expected
signIn jose.SignatureAlgorithm
exp time.Duration // EXPLeeway
nbf time.Duration // NBFLeeway
}
// NewConfiguration creates a configuration for server
func NewConfiguration(provider SecretProvider, audience, issuer string, method jose.SignatureAlgorithm) Configuration {
var aud []string
if audience != "" {
aud = []string{audience}
}
return Configuration{
secretProvider: provider,
expectedClaims: jwt.Expected{Issuer: issuer, Audience: aud},
signIn: method,
exp: 0,
nbf: 0,
}
}
// JWTValidator helps middleware
// to validate token
type JWTValidator struct {
config Configuration
extractor RequestTokenExtractor
}
// NewValidator creates a new
// validator with the provided configuration.
func NewValidator(config Configuration) *JWTValidator {
return &JWTValidator{config, RequestTokenExtractorFunc(FromHeader)}
}
// ValidateRequest validates the token within
// the http request.
func (v *JWTValidator) ValidateRequest(r *http.Request) (*jwt.JSONWebToken, error) {
token, err := v.extractor.Extract(r)
if err != nil {
return nil, err
}
claims := jwt.Claims{}
key, err := v.config.secretProvider.GetSecret(r)
if err != nil {
return nil, err
}
err = token.Claims(key, &claims)
if err != nil {
return nil, err
}
err = claims.Validate(v.config.expectedClaims)
return token, err
}
// Claims unmarshall the claims of the provided token
func (v *JWTValidator) Claims(req *http.Request, token *jwt.JSONWebToken, values interface{}) error {
key, err := v.config.secretProvider.GetSecret(req)
if err != nil {
return err
}
return token.Claims(key, values)
}