2016-01-15 01:09:27 +03:00
|
|
|
package request
|
|
|
|
|
|
|
|
import (
|
2016-04-08 23:58:29 +03:00
|
|
|
"errors"
|
2016-01-15 01:09:27 +03:00
|
|
|
"github.com/dgrijalva/jwt-go"
|
|
|
|
"net/http"
|
2016-04-08 21:57:11 +03:00
|
|
|
"strings"
|
2016-01-15 01:09:27 +03:00
|
|
|
)
|
|
|
|
|
2016-04-08 23:58:29 +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) {
|
2016-04-13 02:25:25 +03:00
|
|
|
return ParseFromRequestWithClaims(req, jwt.MapClaims{}, keyFunc)
|
2016-04-08 21:57:11 +03:00
|
|
|
}
|
2016-01-15 01:09:27 +03:00
|
|
|
|
2016-04-13 02:25:25 +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
|
2016-04-08 21:57:11 +03:00
|
|
|
if len(ah) > 6 && strings.ToUpper(ah[0:7]) == "BEARER " {
|
2016-04-13 02:25:25 +03:00
|
|
|
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 != "" {
|
2016-04-13 02:25:25 +03:00
|
|
|
return jwt.ParseWithClaims(tokStr, claims, keyFunc)
|
2016-01-15 01:09:27 +03:00
|
|
|
}
|
|
|
|
|
2016-04-08 23:58:29 +03:00
|
|
|
return nil, ErrNoTokenInRequest
|
2016-01-15 01:09:27 +03:00
|
|
|
}
|