...
1 package request
2
3 import (
4 "net/http"
5
6 "github.com/golang-jwt/jwt/v4"
7 )
8
9
10
11
12
13
14
15 func ParseFromRequest(req *http.Request, extractor Extractor, keyFunc jwt.Keyfunc, options ...ParseFromRequestOption) (token *jwt.Token, err error) {
16
17 p := &fromRequestParser{req, extractor, nil, nil}
18
19
20 for _, option := range options {
21 option(p)
22 }
23
24
25 if p.claims == nil {
26 p.claims = jwt.MapClaims{}
27 }
28 if p.parser == nil {
29 p.parser = &jwt.Parser{}
30 }
31
32
33 tokenString, err := p.extractor.ExtractToken(req)
34 if err != nil {
35 return nil, err
36 }
37
38
39 return p.parser.ParseWithClaims(tokenString, p.claims, keyFunc)
40 }
41
42
43
44
45 func ParseFromRequestWithClaims(req *http.Request, extractor Extractor, claims jwt.Claims, keyFunc jwt.Keyfunc) (token *jwt.Token, err error) {
46 return ParseFromRequest(req, extractor, keyFunc, WithClaims(claims))
47 }
48
49 type fromRequestParser struct {
50 req *http.Request
51 extractor Extractor
52 claims jwt.Claims
53 parser *jwt.Parser
54 }
55
56 type ParseFromRequestOption func(*fromRequestParser)
57
58
59 func WithClaims(claims jwt.Claims) ParseFromRequestOption {
60 return func(p *fromRequestParser) {
61 p.claims = claims
62 }
63 }
64
65
66 func WithParser(parser *jwt.Parser) ParseFromRequestOption {
67 return func(p *fromRequestParser) {
68 p.parser = parser
69 }
70 }
71
View as plain text