kubectl proxy 加token 驗證
proxy 不支持token加驗證,只能再封裝了一層代理,進行加驗證。
開啓代理
kubectl proxy --port=8089 --address=127.0.0.1 --accept-hosts='^*$' # 後面這個可以去掉,不用允許所有
代碼
mkdir go-proxy
cd go-proxy
go mod init go-proxy
vim main.go
package main
import (
"bytes"
"fmt"
"github.com/ouqiang/goproxy"
"io/ioutil"
"log"
"net"
"net/http"
"net/url"
"strings"
"time"
)
type EventHandler struct{}
func (e *EventHandler) Connect(ctx *goproxy.Context, rw http.ResponseWriter) {
}
func (e *EventHandler) Auth(ctx *goproxy.Context, rw http.ResponseWriter) {
}
func (e *EventHandler) BeforeRequest(ctx *goproxy.Context) {
if clientIP, _, err := net.SplitHostPort(ctx.Req.RemoteAddr); err == nil {
if prior, ok := ctx.Req.Header["X-Forwarded-For"]; ok {
clientIP = strings.Join(prior, ", ") + ", " + clientIP
}
ctx.Req.Header.Set("X-Forwarded-For", clientIP)
}
// 讀取Body
body, err := ioutil.ReadAll(ctx.Req.Body)
if err != nil {
// 錯誤處理
return
}
if ctx.Req.Header.Get("token") != "1234" {
fmt.Println("沒有權限,禁止登錄")
ctx.Abort()
return
}
// Request.Body只能讀取一次, 讀取後必須再放回去
// Response.Body同理
ctx.Req.Body = ioutil.NopCloser(bytes.NewReader(body))
}
func (e *EventHandler) BeforeResponse(ctx *goproxy.Context, resp *http.Response, err error) {
if err != nil {
return
}
// 修改response
}
// 設置上級代理
func (e *EventHandler) ParentProxy(req *http.Request) (*url.URL, error) {
return url.Parse("http://127.0.0.1:8089")
}
func (e *EventHandler) Finish(ctx *goproxy.Context) {
log.Printf("請求結束 URL:%s\n", ctx.Req.URL)
}
// 記錄錯誤日誌
func (e *EventHandler) ErrorLog(err error) {
log.Println(err)
}
func main() {
proxy := goproxy.New(goproxy.WithDelegate(&EventHandler{}))
server := &http.Server{
Addr: ":8000",
Handler: proxy,
ReadTimeout: 1 * time.Minute,
WriteTimeout: 1 * time.Minute,
}
err := server.ListenAndServe()
if err != nil {
panic(err)
}
}
go run main.go
注意
主要修改的地方有2個
if ctx.Req.Header.Get("token") != "1234" { 這裏是輸入你的token密碼
return url.Parse("http://127.0.0.1:8089") 這裏是你本地的 proxy 接口
請求
請求頭 添加 token : 1234