Repository navigation
Expand file tree
/
Copy pathauth.go
More file actions
73 lines (63 loc) · 2.18 KB
/
Copy pathauth.go
File metadata and controls
73 lines (63 loc) · 2.18 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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package sdk
import (
"context"
"encoding/base64"
"errors"
"net/http"
)
// Authenticator sets the credentials on an outgoing request. Implementations
// correspond to the security schemes in the OpenAPI spec: APIKeyAuth for the
// API key (HTTP Basic) and BearerAuth for session tokens.
type Authenticator interface {
Authenticate(ctx context.Context, req *http.Request) error
}
// APIKeyAuth is the developer API key scheme: Authorization: Basic base64(key:secret).
type APIKeyAuth struct {
Key string
Secret string
}
// Authenticate implements Authenticator.
func (a APIKeyAuth) Authenticate(_ context.Context, req *http.Request) error {
if a.Key == "" || a.Secret == "" {
return errors.New("api key and secret are both required")
}
req.Header.Set("Authorization", "Basic "+base64.StdEncoding.EncodeToString([]byte(a.Key+":"+a.Secret)))
return nil
}
// TokenSource yields a bearer token, refreshing it if needed. golang.org/x/oauth2
// token sources satisfy this via a one-line adapter, which is how OIDC will plug in.
type TokenSource interface {
Token(ctx context.Context) (string, error)
}
// RefreshingTokenSource is a TokenSource that can be told its token was
// rejected. A Client whose BearerAuth has one answers a 401 to a request
// that carried a token by calling Invalidate, taking a new token and sending
// the request once more; a request whose body cannot be replayed is not
// resent.
type RefreshingTokenSource interface {
TokenSource
Invalidate()
}
// StaticToken is a TokenSource for a token that is already in hand.
type StaticToken string
// Token implements TokenSource.
func (t StaticToken) Token(context.Context) (string, error) { return string(t), nil }
// BearerAuth is the user-session JWT scheme: Authorization: Bearer <token>.
type BearerAuth struct {
Source TokenSource
}
// Authenticate implements Authenticator.
func (b BearerAuth) Authenticate(ctx context.Context, req *http.Request) error {
if b.Source == nil {
return errors.New("bearer auth has no token source")
}
tok, err := b.Source.Token(ctx)
if err != nil {
return err
}
if tok == "" {
return errors.New("bearer token is empty")
}
req.Header.Set("Authorization", "Bearer "+tok)
return nil
}