Skip to content

Commit c162da0

Browse files
committed
chore: add kubernetes example
1 parent b4f3bb0 commit c162da0

File tree

3 files changed

+144
-0
lines changed

3 files changed

+144
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@ Here are a few bullet point reasons you might like to try it out:
3535
* provides a mechanism to customize strategies, even enables writing a custom strategy
3636

3737
## Strategies
38+
* [kubernetes (Token Review)](https://pkg.go.dev/github.com/shaj13/go-guardian/auth/strategies/kubernetes?tab=doc)
3839
* [Certificate-Based](https://pkg.go.dev/github.com/shaj13/[email protected]/auth/strategies/x509?tab=doc)
3940
* [Bearer-Token](https://pkg.go.dev/github.com/shaj13/[email protected]/auth/strategies/bearer?tab=doc)
4041
* [Static-Token](https://pkg.go.dev/github.com/shaj13/[email protected]/auth/strategies/bearer?tab=doc)

_examples/kubernetes/main.go

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
// Copyright 2020 The Go-Guardian. All rights reserved.
2+
// Use of this source code is governed by a MIT
3+
// license that can be found in the LICENSE file.
4+
5+
package main
6+
7+
import (
8+
"context"
9+
"fmt"
10+
"log"
11+
"net/http"
12+
"time"
13+
14+
"github.com/gorilla/mux"
15+
16+
"github.com/shaj13/go-guardian/auth"
17+
"github.com/shaj13/go-guardian/auth/strategies/kubernetes"
18+
"github.com/shaj13/go-guardian/auth/strategies/token"
19+
"github.com/shaj13/go-guardian/store"
20+
)
21+
22+
// Usage:
23+
// Run kubernetes mock api and get agent token
24+
// go run mock.go
25+
// Request server to verify token and get book author
26+
// curl -k http://127.0.0.1:8080/v1/book/1449311601 -H "Authorization: Bearer <agent-token-from-mock>"
27+
28+
var authenticator auth.Authenticator
29+
var cache store.Cache
30+
31+
func main() {
32+
setupGoGuardian()
33+
router := mux.NewRouter()
34+
35+
router.HandleFunc("/v1/book/{id}", middleware(http.HandlerFunc(getBookAuthor))).Methods("GET")
36+
log.Println("server started and listening on http://127.0.0.1:8080")
37+
http.ListenAndServe("127.0.0.1:8080", router)
38+
}
39+
40+
func getBookAuthor(w http.ResponseWriter, r *http.Request) {
41+
vars := mux.Vars(r)
42+
id := vars["id"]
43+
books := map[string]string{
44+
"1449311601": "Ryan Boyd",
45+
"148425094X": "Yvonne Wilson",
46+
"1484220498": "Prabath Siriwarden",
47+
}
48+
body := fmt.Sprintf("Author: %s \n", books[id])
49+
w.Write([]byte(body))
50+
}
51+
52+
func setupGoGuardian() {
53+
authenticator = auth.New()
54+
cache = store.NewFIFO(context.Background(), time.Minute*10)
55+
kubeStrategy := kubernetes.New(cache)
56+
authenticator.EnableStrategy(token.CachedStrategyKey, kubeStrategy)
57+
}
58+
59+
func middleware(next http.Handler) http.HandlerFunc {
60+
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
61+
log.Println("Executing Auth Middleware")
62+
user, err := authenticator.Authenticate(r)
63+
if err != nil {
64+
code := http.StatusUnauthorized
65+
http.Error(w, http.StatusText(code), code)
66+
return
67+
}
68+
log.Printf("User %s Authenticated\n", user.UserName())
69+
next.ServeHTTP(w, r)
70+
})
71+
}

_examples/kubernetes/mock.go

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
// Copyright 2020 The Go-Guardian. All rights reserved.
2+
// Use of this source code is governed by a MIT
3+
// license that can be found in the LICENSE file.
4+
5+
package main
6+
7+
import (
8+
"fmt"
9+
"io/ioutil"
10+
"log"
11+
"net/http"
12+
"strings"
13+
14+
"github.com/gorilla/mux"
15+
)
16+
17+
const (
18+
agentJWT = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c"
19+
serviceJWT = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTYiLCJuYW1lIjoic3lzdGVtOnNlcnZpY2U6YWNjb3VudCIsImlhdCI6MTUxNjIzOTAyMn0.4pHu9y6vJvtOnLhpz7M3Znnvcdpm7GCiHPCPYzyxps8"
20+
authenticatedUser = `
21+
{
22+
"metadata":{
23+
"creationTimestamp":null
24+
},
25+
"spec":{
26+
27+
},
28+
"status":{
29+
"authenticated":true,
30+
"user":{
31+
"username":"system:serviceaccount:curl_agent",
32+
"uid":"1"
33+
}
34+
}
35+
}
36+
`
37+
unauthenticatedUser = `
38+
{
39+
"metadata":{
40+
"creationTimestamp":null
41+
},
42+
"spec":{
43+
44+
},
45+
"status":{
46+
"authenticated":false,
47+
}
48+
}
49+
`
50+
)
51+
52+
func main() {
53+
log.Printf("JWT service account For auth startegy: %s \n", serviceJWT)
54+
log.Printf("JWT service account For curl agent: %s \n", agentJWT)
55+
56+
router := mux.NewRouter()
57+
router.HandleFunc("/apis/authentication.k8s.io/v1/tokenreviews", http.HandlerFunc(review)).Methods("POST")
58+
log.Println("Kube Mock API Server started -> http://127.0.0.1:6443")
59+
http.ListenAndServe("127.0.0.1:6443", router)
60+
}
61+
62+
func review(w http.ResponseWriter, r *http.Request) {
63+
body, _ := ioutil.ReadAll(r.Body)
64+
if strings.Contains(string(body), agentJWT) {
65+
w.WriteHeader(200)
66+
w.Write([]byte(authenticatedUser))
67+
return
68+
}
69+
w.WriteHeader(401)
70+
w.Write([]byte(unauthenticatedUser))
71+
return
72+
}

0 commit comments

Comments
 (0)