request.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. package request
  2. import (
  3. "github.com/dgrijalva/jwt-go"
  4. "net/http"
  5. )
  6. // Extract and parse a JWT token from an HTTP request.
  7. // This behaves the same as Parse, but accepts a request and an extractor
  8. // instead of a token string. The Extractor interface allows you to define
  9. // the logic for extracting a token. Several useful implementations are provided.
  10. //
  11. // You can provide options to modify parsing behavior
  12. func ParseFromRequest(req *http.Request, extractor Extractor, keyFunc jwt.Keyfunc, options ...ParseFromRequestOption) (token *jwt.Token, err error) {
  13. // Create basic parser struct
  14. p := &fromRequestParser{req, extractor, nil, nil}
  15. // Handle options
  16. for _, option := range options {
  17. option(p)
  18. }
  19. // Set defaults
  20. if p.claims == nil {
  21. p.claims = jwt.MapClaims{}
  22. }
  23. if p.parser == nil {
  24. p.parser = &jwt.Parser{}
  25. }
  26. // perform extract
  27. tokenString, err := p.extractor.ExtractToken(req)
  28. if err != nil {
  29. return nil, err
  30. }
  31. // perform parse
  32. return p.parser.ParseWithClaims(tokenString, p.claims, keyFunc)
  33. }
  34. // ParseFromRequest but with custom Claims type
  35. // DEPRECATED: use ParseFromRequest and the WithClaims option
  36. func ParseFromRequestWithClaims(req *http.Request, extractor Extractor, claims jwt.Claims, keyFunc jwt.Keyfunc) (token *jwt.Token, err error) {
  37. return ParseFromRequest(req, extractor, keyFunc, WithClaims(claims))
  38. }
  39. type fromRequestParser struct {
  40. req *http.Request
  41. extractor Extractor
  42. claims jwt.Claims
  43. parser *jwt.Parser
  44. }
  45. type ParseFromRequestOption func(*fromRequestParser)
  46. // Parse with custom claims
  47. func WithClaims(claims jwt.Claims) ParseFromRequestOption {
  48. return func(p *fromRequestParser) {
  49. p.claims = claims
  50. }
  51. }
  52. // Parse using a custom parser
  53. func WithParser(parser *jwt.Parser) ParseFromRequestOption {
  54. return func(p *fromRequestParser) {
  55. p.parser = parser
  56. }
  57. }