jwt/request/request.go

40 lines
1.1 KiB
Go
Raw Normal View History

2016-01-15 01:09:27 +03:00
package request
import (
"errors"
2016-01-15 01:09:27 +03:00
"github.com/dgrijalva/jwt-go"
"net/http"
"strings"
2016-01-15 01:09:27 +03:00
)
// Errors
var (
ErrNoTokenInRequest = errors.New("no token present in request")
)
2016-01-15 01:09:27 +03:00
// Try to find the token in an http.Request.
// This method will call ParseMultipartForm if there's no token in the header.
// Currently, it looks in the Authorization header as well as
// looking for an 'access_token' request parameter in req.Form.
func ParseFromRequest(req *http.Request, keyFunc jwt.Keyfunc) (token *jwt.Token, err error) {
return ParseFromRequestWithClaims(req, jwt.MapClaims{}, keyFunc)
}
2016-01-15 01:09:27 +03:00
func ParseFromRequestWithClaims(req *http.Request, claims jwt.Claims, keyFunc jwt.Keyfunc) (token *jwt.Token, err error) {
2016-01-15 01:09:27 +03:00
// Look for an Authorization header
if ah := req.Header.Get("Authorization"); ah != "" {
// Should be a bearer token
if len(ah) > 6 && strings.ToUpper(ah[0:7]) == "BEARER " {
return jwt.ParseWithClaims(ah[7:], claims, keyFunc)
2016-01-15 01:09:27 +03:00
}
}
// Look for "access_token" parameter
req.ParseMultipartForm(10e6)
if tokStr := req.Form.Get("access_token"); tokStr != "" {
return jwt.ParseWithClaims(tokStr, claims, keyFunc)
2016-01-15 01:09:27 +03:00
}
return nil, ErrNoTokenInRequest
2016-01-15 01:09:27 +03:00
}