This repository has been archived by the owner on Oct 23, 2024. It is now read-only.
forked from arrikto/oidc-authservice
-
Notifications
You must be signed in to change notification settings - Fork 0
/
authenticator_kubernetes.go
66 lines (54 loc) · 1.91 KB
/
authenticator_kubernetes.go
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
package main
import (
"net/http"
"strings"
"k8s.io/apiserver/pkg/authentication/authenticator"
"k8s.io/apiserver/pkg/authentication/authenticatorfactory"
"k8s.io/apiserver/pkg/authentication/user"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
)
const (
bearerTokenExpiredMsg = "Token has expired"
)
type kubernetesAuthenticator struct {
audiences []string
authenticator authenticator.Request
}
func newKubernetesAuthenticator(c *rest.Config, aud []string) (authenticator.Request, error) {
config := authenticatorfactory.DelegatingAuthenticatorConfig{
Anonymous: false,
TokenAccessReviewClient: kubernetes.NewForConfigOrDie(c).AuthenticationV1().TokenReviews(),
APIAudiences: aud,
}
k8sAuthenticator, _, err := config.New()
return &kubernetesAuthenticator{audiences: aud, authenticator: k8sAuthenticator}, err
}
func (k8sauth *kubernetesAuthenticator) AuthenticateRequest(r *http.Request) (*authenticator.Response, bool, error) {
resp, found, err := k8sauth.authenticator.AuthenticateRequest(
r.WithContext(authenticator.WithAudiences(r.Context(), k8sauth.audiences)),
)
// If the request contains an expired token, we stop trying and return 403
if err != nil && strings.Contains(err.Error(), bearerTokenExpiredMsg) {
return nil, false, &loginExpiredError{Err: err}
}
if found {
// Authentication using header successfully completed
extra := map[string][]string{"auth-method": {"header"}}
resp = &authenticator.Response{
Audiences: resp.Audiences,
User: &user.DefaultInfo{
Name: resp.User.GetName(),
UID: resp.User.GetUID(),
Groups: resp.User.GetGroups(),
Extra: extra,
},
}
}
return resp, found, err
}
// The Kubernetes Authenticator implements the Cacheable
// interface with the getCacheKey().
func (k8sauth *kubernetesAuthenticator) getCacheKey(r *http.Request) (string) {
return getBearerToken(r.Header.Get("Authorization"))
}