request.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. package request
  2. import (
  3. "net/http"
  4. "github.com/golang-jwt/jwt/v4"
  5. )
  6. // ParseFromRequest extracts and parses 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. // ParseFromRequestWithClaims is an alias for ParseFromRequest but with custom Claims type.
  35. //
  36. // Deprecated: use ParseFromRequest and the WithClaims option
  37. func ParseFromRequestWithClaims(req *http.Request, extractor Extractor, claims jwt.Claims, keyFunc jwt.Keyfunc) (token *jwt.Token, err error) {
  38. return ParseFromRequest(req, extractor, keyFunc, WithClaims(claims))
  39. }
  40. type fromRequestParser struct {
  41. req *http.Request
  42. extractor Extractor
  43. claims jwt.Claims
  44. parser *jwt.Parser
  45. }
  46. type ParseFromRequestOption func(*fromRequestParser)
  47. // WithClaims parses with custom claims
  48. func WithClaims(claims jwt.Claims) ParseFromRequestOption {
  49. return func(p *fromRequestParser) {
  50. p.claims = claims
  51. }
  52. }
  53. // WithParser parses using a custom parser
  54. func WithParser(parser *jwt.Parser) ParseFromRequestOption {
  55. return func(p *fromRequestParser) {
  56. p.parser = parser
  57. }
  58. }