Skip to content

Commit

Permalink
chore: add kubernetes example
Browse files Browse the repository at this point in the history
  • Loading branch information
shaj13 committed Aug 22, 2020
1 parent b4f3bb0 commit c162da0
Show file tree
Hide file tree
Showing 3 changed files with 144 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ Here are a few bullet point reasons you might like to try it out:
* provides a mechanism to customize strategies, even enables writing a custom strategy

## Strategies
* [kubernetes (Token Review)](https://pkg.go.dev/github.com/shaj13/go-guardian/auth/strategies/kubernetes?tab=doc)
* [Certificate-Based](https://pkg.go.dev/github.com/shaj13/[email protected]/auth/strategies/x509?tab=doc)
* [Bearer-Token](https://pkg.go.dev/github.com/shaj13/[email protected]/auth/strategies/bearer?tab=doc)
* [Static-Token](https://pkg.go.dev/github.com/shaj13/[email protected]/auth/strategies/bearer?tab=doc)
Expand Down
71 changes: 71 additions & 0 deletions _examples/kubernetes/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
// Copyright 2020 The Go-Guardian. All rights reserved.
// Use of this source code is governed by a MIT
// license that can be found in the LICENSE file.

package main

import (
"context"
"fmt"
"log"
"net/http"
"time"

"github.com/gorilla/mux"

"github.com/shaj13/go-guardian/auth"
"github.com/shaj13/go-guardian/auth/strategies/kubernetes"
"github.com/shaj13/go-guardian/auth/strategies/token"
"github.com/shaj13/go-guardian/store"
)

// Usage:
// Run kubernetes mock api and get agent token
// go run mock.go
// Request server to verify token and get book author
// curl -k http://127.0.0.1:8080/v1/book/1449311601 -H "Authorization: Bearer <agent-token-from-mock>"

var authenticator auth.Authenticator
var cache store.Cache

func main() {
setupGoGuardian()
router := mux.NewRouter()

router.HandleFunc("/v1/book/{id}", middleware(http.HandlerFunc(getBookAuthor))).Methods("GET")
log.Println("server started and listening on http://127.0.0.1:8080")
http.ListenAndServe("127.0.0.1:8080", router)
}

func getBookAuthor(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
id := vars["id"]
books := map[string]string{
"1449311601": "Ryan Boyd",
"148425094X": "Yvonne Wilson",
"1484220498": "Prabath Siriwarden",
}
body := fmt.Sprintf("Author: %s \n", books[id])
w.Write([]byte(body))
}

func setupGoGuardian() {
authenticator = auth.New()
cache = store.NewFIFO(context.Background(), time.Minute*10)
kubeStrategy := kubernetes.New(cache)
authenticator.EnableStrategy(token.CachedStrategyKey, kubeStrategy)
}

func middleware(next http.Handler) http.HandlerFunc {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log.Println("Executing Auth Middleware")
user, err := authenticator.Authenticate(r)
if err != nil {
code := http.StatusUnauthorized
http.Error(w, http.StatusText(code), code)
return
}
log.Printf("User %s Authenticated\n", user.UserName())
next.ServeHTTP(w, r)
})
}
72 changes: 72 additions & 0 deletions _examples/kubernetes/mock.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
// Copyright 2020 The Go-Guardian. All rights reserved.
// Use of this source code is governed by a MIT
// license that can be found in the LICENSE file.

package main

import (
"fmt"
"io/ioutil"
"log"
"net/http"
"strings"

"github.com/gorilla/mux"
)

const (
agentJWT = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c"
serviceJWT = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTYiLCJuYW1lIjoic3lzdGVtOnNlcnZpY2U6YWNjb3VudCIsImlhdCI6MTUxNjIzOTAyMn0.4pHu9y6vJvtOnLhpz7M3Znnvcdpm7GCiHPCPYzyxps8"
authenticatedUser = `
{
"metadata":{
"creationTimestamp":null
},
"spec":{
},
"status":{
"authenticated":true,
"user":{
"username":"system:serviceaccount:curl_agent",
"uid":"1"
}
}
}
`
unauthenticatedUser = `
{
"metadata":{
"creationTimestamp":null
},
"spec":{
},
"status":{
"authenticated":false,
}
}
`
)

func main() {
log.Printf("JWT service account For auth startegy: %s \n", serviceJWT)
log.Printf("JWT service account For curl agent: %s \n", agentJWT)

router := mux.NewRouter()
router.HandleFunc("/apis/authentication.k8s.io/v1/tokenreviews", http.HandlerFunc(review)).Methods("POST")
log.Println("Kube Mock API Server started -> http://127.0.0.1:6443")
http.ListenAndServe("127.0.0.1:6443", router)
}

func review(w http.ResponseWriter, r *http.Request) {
body, _ := ioutil.ReadAll(r.Body)
if strings.Contains(string(body), agentJWT) {
w.WriteHeader(200)
w.Write([]byte(authenticatedUser))
return
}
w.WriteHeader(401)
w.Write([]byte(unauthenticatedUser))
return
}

0 comments on commit c162da0

Please sign in to comment.