-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhttp.go
46 lines (42 loc) · 1019 Bytes
/
http.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
package bearerware
import (
"fmt"
"net/http"
"github.com/dgrijalva/jwt-go"
)
/*
JWTFromHeader extracts a valid JWT from an http.Request or returns and error
*/
func JWTFromHeader(
r *http.Request,
keyFunc jwt.Keyfunc,
signingMethod jwt.SigningMethod,
) (*jwt.Token, error) {
authSlice, ok := r.Header[http.CanonicalHeaderKey(authHeader)]
if !ok {
return nil, errRestricted
}
for _, authString := range authSlice {
tokenString, ok := tokenFromBearer(authString)
if !ok {
continue
}
return validJWTFromString(tokenString, keyFunc, signingMethod)
}
return nil, &jwtError{
err: errBearerFormat,
code: invalidRequest,
}
}
/*
WriteAuthError is a convenience function for setting the WWW-Authenticate header
and sending an http.Error()
*/
func WriteAuthError(w http.ResponseWriter, err error) {
w.Header().Set(http.CanonicalHeaderKey("WWW-Authenticate"), err.Error())
http.Error(
w,
fmt.Sprintf("%s: %s", http.StatusText(http.StatusUnauthorized), err),
http.StatusUnauthorized,
)
}