...

Source file src/github.com/golang-jwt/jwt/request/request.go

Documentation: github.com/golang-jwt/jwt/request

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

View as plain text