...
1 package request
2
3 import (
4 "net/http"
5
6 "github.com/golang-jwt/jwt"
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 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
58 func WithClaims(claims jwt.Claims) ParseFromRequestOption {
59 return func(p *fromRequestParser) {
60 p.claims = claims
61 }
62 }
63
64
65 func WithParser(parser *jwt.Parser) ParseFromRequestOption {
66 return func(p *fromRequestParser) {
67 p.parser = parser
68 }
69 }
70
View as plain text