Repository navigation
Expand file tree
/
Copy pathrequest.go
More file actions
58 lines (52 loc) · 1.44 KB
/
Copy pathrequest.go
File metadata and controls
58 lines (52 loc) · 1.44 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
// Tideland Go JSON Web Token
//
// Copyright (C) 2016-2025 Frank Mueller / Tideland / Germany
//
// All rights reserved. Use of this source code is governed
// by the new BSD license.
package jwt
import (
"fmt"
"net/http"
"strings"
)
// RequestAdd adds a token as header to a request for
// usage by a client.
func RequestAdd(req *http.Request, jwt *JWT) *http.Request {
req.Header.Add("Authorization", "Bearer "+jwt.String())
return req
}
// RequestDecode tries to retrieve a token from a request header.
func RequestDecode(req *http.Request) (*JWT, error) {
return decode(req, nil)
}
// RequestVerify retrieves a possible token from a request.
// The JWT then will be verified.
func RequestVerify(req *http.Request, key Key) (*JWT, error) {
return decode(req, key)
}
// decodeFromRequest is the generic decoder with possible
// caching and verification.
func decode(req *http.Request, key Key) (*JWT, error) {
// Retrieve token from header.
authorization := req.Header.Get("Authorization")
if authorization == "" {
return nil, fmt.Errorf("request contains no authorization header")
}
fields := strings.Fields(authorization)
if len(fields) != 2 || fields[0] != "Bearer" {
return nil, fmt.Errorf("invalid authorization header: %q", authorization)
}
// Decode or verify.
var jwt *JWT
var err error
if key == nil {
jwt, err = Decode(fields[1])
} else {
jwt, err = Verify(fields[1], key)
}
if err != nil {
return nil, err
}
return jwt, nil
}