-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtoken_handler.go
43 lines (39 loc) · 1.14 KB
/
token_handler.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
package middlewares
import (
"context"
"errors"
"fmt"
"net/http"
"strings"
)
//TokenHandler extracts any Bearer tokens from the request
func TokenHandler(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
token, err := bearer(r.Header)
if err != nil {
fmt.Fprintf(output, "warn: %s\n", err.Error())
next.ServeHTTP(w, r)
return
}
ctx := context.WithValue(r.Context(), tokenContextKey, token)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
//Token returns any Bearer tokens that was found using TokenHandler, if no token is found it returns an error
func Token(ctx context.Context) (token string, err error) {
if t, ok := ctx.Value(tokenContextKey).(string); ok {
return t, nil
}
return "", errors.New("no token found in context")
}
func bearer(h http.Header) (token string, err error) {
auth := h.Get("Authorization")
if !strings.HasPrefix(auth, "Bearer ") {
return "", errors.New("no Authorization header found")
}
token = auth[7:] // The string 'Bearer' and a whitespace "Bearer "
if !(len(token) > 0) {
return "", errors.New("empty bearer token")
}
return token, nil
}