forked from stellar/go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sep10.go
89 lines (81 loc) · 2.23 KB
/
sep10.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
package auth
import (
"errors"
"net/http"
"time"
"github.com/stellar/go/keypair"
"github.com/stellar/go/support/http/httpauthz"
"github.com/stellar/go/support/log"
"gopkg.in/square/go-jose.v2"
"gopkg.in/square/go-jose.v2/jwt"
)
// SEP10Middleware provides middleware for handling an authentication SEP-10 JWT.
func SEP10Middleware(issuer string, ks jose.JSONWebKeySet) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if address, k, ok := sep10ClaimsFromRequest(r, issuer, ks); ok {
ctx := r.Context()
auth, _ := FromContext(ctx)
auth.Address = address
log.Ctx(ctx).
WithField("jwkkid", k.KeyID).
WithField("address", address).
Info("SEP-10 JWT verified.")
ctx = NewContext(ctx, auth)
r = r.WithContext(ctx)
}
next.ServeHTTP(w, r)
})
}
}
type sep10JWTClaims struct {
jwt.Claims
}
func (c sep10JWTClaims) Validate(issuer string) error {
if c.Claims.IssuedAt == nil {
return errors.New("validation failed, no issued at (iat) in token")
}
if c.Claims.Expiry == nil {
return errors.New("validation failed, no expiry (exp) in token")
}
expectedClaims := jwt.Expected{
Issuer: issuer,
Time: time.Now(),
}
return c.Claims.Validate(expectedClaims)
}
func sep10ClaimsFromRequest(r *http.Request, issuer string, ks jose.JSONWebKeySet) (address string, k jose.JSONWebKey, ok bool) {
authHeader := r.Header.Get("Authorization")
tokenEncoded := httpauthz.ParseBearerToken(authHeader)
if tokenEncoded == "" {
return "", jose.JSONWebKey{}, false
}
token, err := jwt.ParseSigned(tokenEncoded)
if err != nil {
return "", jose.JSONWebKey{}, false
}
tokenClaims := sep10JWTClaims{}
verified := false
verifiedWithKey := jose.JSONWebKey{}
for _, k := range ks.Keys {
err = token.Claims(k, &tokenClaims)
if err == nil {
verified = true
verifiedWithKey = k
break
}
}
if !verified {
return "", jose.JSONWebKey{}, false
}
err = tokenClaims.Validate(issuer)
if err != nil {
return "", jose.JSONWebKey{}, false
}
address = tokenClaims.Subject
_, err = keypair.ParseAddress(address)
if err != nil {
return "", jose.JSONWebKey{}, false
}
return address, verifiedWithKey, true
}