Skip to content

Instantly share code, notes, and snippets.

@Yapcheekian
Created March 4, 2022 00:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Yapcheekian/ebdef2a006579e544ab38e39a2f0d3b2 to your computer and use it in GitHub Desktop.
Save Yapcheekian/ebdef2a006579e544ab38e39a2f0d3b2 to your computer and use it in GitHub Desktop.
authentication webhook is k8s
package authenticate
import (
"encoding/json"
"errors"
"log"
"net/http"
"strings"
authentication "k8s.io/api/authentication/v1beta1"
)
func Authenticate(w http.ResponseWriter, r *http.Request) {
decoder := json.NewDecoder(r.Body)
var tr authentication.TokenReview
err := decoder.Decode(&tr)
if err != nil {
handleError(w, err)
return
}
user, err := logon(tr.Spec.Token)
if err != nil {
handleError(w, err)
return
}
log.Printf("[Success] login as %s", user.username)
w.WriteHeader(http.StatusOK)
trs := authentication.TokenReviewStatus{
Authenticated: true,
User: authentication.UserInfo{
Username: user.username,
Groups: []string{user.group},
},
}
tr.Status = trs
json.NewEncoder(w).Encode(tr)
}
func handleError(w http.ResponseWriter, err error) {
log.Println("[Error]", err.Error())
tr := new(authentication.TokenReview)
trs := authentication.TokenReviewStatus{
Authenticated: false,
Error: err.Error(),
}
tr.Status = trs
w.WriteHeader(http.StatusUnauthorized)
json.NewEncoder(w).Encode(tr)
}
func logon(token string) (*User, error) {
data := strings.Split(token, ";")
if len(data) < 3 {
return nil, errors.New("no token data")
}
for _, u := range allowed {
if u.group == data[0] && u.username == data[1] && u.password == data[2] {
return &u, nil
}
}
return nil, errors.New("no user found")
}
type User struct {
username string
password string
group string
}
var allowed = []User{
{
username: "minikube-user",
group: "system:masters",
password: "mysecret",
},
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment