整体思路


        用户访问一个页面,在该页面中设置一个超链接,点击跳转至K8S Dashboard;跳转后,使用剪贴板上已复制的Token粘贴到Dashboard页面中的输入框登录即可。
        写个定时任务将Token复制到页面上,过期了重新再登录;
        如果要对这个页面做权限控制,配置账户密码,可考虑借助使用nodejs koa或nginx-ingress等等


使用nodejs搭建一个web容器用于展示该跳转页面


参考:https://www.jianshu.com/p/15971d243186


创建server.js,定义一个Web服务

vi server.js

var url = require("url"),
    fs = require("fs"),
    http = require("http"),
    path = require("path");
http.createServer(function (req, res) {
    var pathname = __dirname + url.parse("/dist"+req.url).pathname;//资源指向dist目录
    if (path.extname(pathname) == "") {
        pathname += "/";
    }
    if (pathname.charAt(pathname.length - 1) == "/") {
        pathname += "index.html";
    }
    fs.exists(pathname, function (exists) {
        if (exists) {
            switch(path.extname(pathname)){
                case ".html":
                    res.writeHead(200, {"Content-Type": "text/html"});
                    break;
                default:
                    res.writeHead(200, {"Content-Type": "application/octet-stream"});
            }
            fs.readFile(pathname, function (err, data) {
                res.end(data);
            });
        } else {
            res.writeHead(404, {
                "Content-Type": "text/html"
            });
            res.end("<h1>404 Not Found</h1>");
        }
    });
}).listen(3003);
console.log("监听3003端口");

创建Dockerfile

vi Dockerfile

# Pull base image
FROM docker.io/node:latest

# Expose ports.
EXPOSE 3003

# Usage: USER [UID]
USER root

# Usage: WORKDIR /path
WORKDIR /http-server

# add  js
ADD  server.js /http-server/

RUN mkdir dist

# modify conf
ENTRYPOINT ["node","/http-server/server.js"]

创建镜像,并推送致仓库


- docker build -t yourharboraddr/lib/dashboard-token:v0.0.1 .
- docker push yourharboraddr/lib/dashboard-token:v0.0.1


定义Deployment和SVC,部署到kubernetes-dashboard空间,避免其它用户骚操作

vi deployment-token.yaml

apiVersion: apps/v1
kind: Deployment
metadata:
  labels:
    app: dashboard-token
  name: dashboard-token-developer
  namespace: kubernetes-dashboard
spec:
  replicas: 1
  selector:
    matchLabels:
      app: dashboard-token
  template:
    metadata:
      labels:
        app: dashboard-token
    spec:
      containers:
      - image: yourharboraddr/lib/dashboard-token:v0.0.1
        imagePullPolicy: IfNotPresent
        name: dashboard-token-containers
        ports:
        - containerPort: 3003
          protocol: TCP
---
apiVersion: v1
kind: Service
metadata:
  labels:
    app: dashboard-token
  name: dashboard-token-developer-svc
  namespace: kubernetes-dashboard
spec:
  ports:
  - port: 3003
    protocol: TCP
    targetPort: 3003
    nodePort: 3xxxx
  selector:
    app: dashboard-token
  type: NodePort

部署     kubectl apply -f deployment-token.yaml

定义一个用于展示跳转按钮的页面模板

       自动复制token后跳转至Dashboard,href直接在URL中选择了develop命名空间,该用户没有授权查看命名空间的权限,只能在界面上选择default命名空间,但可以直接用URL中的命名空间跳转至有权限的命名空间develop

vi index.html.templete

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Go to K8S Dashboard!</title>
</head>
<body>
 <input type="text" value="k8stoken" id="token" style="opacity: 0" readonly/>
  <a title='Token will hidding in your clipboard!!!' href="https://yourDashboardIP:yourPort/#/pod?namespace=develop" onclick="javascript:document.getElementById('token').select();document.execCommand('Copy');">Go to K8S Dashboard!</a>
</body>
</html>

定义一个Shell脚本,复制一个index.html

- 获取普通用户的token,将token存入index.html
- 再将index.html复制到pod中

vi getToken4developer.sh
#! /bin/bash

export POD_NAME=$(kubectl get pods --namespace kubernetes-dashboard -l "app=dashboard-token" -o jsonpath="{.items[0].metadata.name}")
export K8S_DEVELOPER_TOKEN=$(kubectl -n develop create token developer)

rm -f /root/dashboard/index.html
cp  /root/dashboard/index.html.templete /root/dashboard/index.html
#将token添加到index.html中
sed -i 's/k8stoken/'"$K8S_DEVELOPER_TOKEN"'/g' /root/dashboard/index.html
#复制index.html至pod
kubectl cp /root/dashboard/index.html $POD_NAME:/http-server/dist/  --namespace kubernetes-dashboard

定时任务

- Token不是老过期么,在linux上写个cronjob定时将新的token复制到index.html中
- crontab -e 
- 每半个小时或者一个小时什么的更新一下,过期前更新一下就行
- */1 * * * bash  /root/dashboard/getToken4developer.sh

测试


- 访问该pod的地址:http://yourk8sIP:3xxxx 自动打开index.html
- 点击Go to K8S Dashboard!按钮,跳转至k8s的dashboard中
- 粘贴Token登录即可

使用nodejs koa配置账户密码进行权限拦截

yourname/yourpassword


const Koa = require('koa');
const router = require("@koa/router")()
const path = require("path")
const views = require("koa-views")
const app = module.exports = new Koa()

app.use(views(path.join(__dirname,"dist/"),{extension:'html'}))

app.use(async ctx => {
    let authBase64Str = ctx.request.header['authorization'];
    //console.log('auth str ',  authBase64Str)
    if (authBase64Str) {
        let authStr = authBase64Str.substring(5).trim()
        let buffer = Buffer.from(authStr, 'base64') //base64 decode, base64 encode: toString('base64')
        //console.log('name:pwd ', buffer.toString())
        if (buffer.toString() === 'yourname:yourpassword') { //配置账户密码
            //let tmp = buffer.toString().split(':')
            //return ctx.body = `htpp base auth\n username: ${tmp[0]}\n password: ${tmp[1]}`
            return ctx.render("index")
        }
    }

    ctx.set({
        'WWW-authenticate': "Basic Realm='websitName'"
    })
    ctx.status = 401;

})

app.listen(3003, () => {
    console.log('app.listen 3003...')
})

参考:

http basic auth 实现请求网页时弹出账号密码输入框_前端请求接口 弹窗输入账号密码-CSDN博客

响应 | response (响应 | response ) - Koa 中文开发手册 - 开发者手册 - 腾讯云开发者社区-腾讯云

koa利用koa-views通过路由返回html页面_koa框架路由如何跳转到html页面-CSDN博客

koa设置静态资源以加载html页面_koa路由中间件加载网页-CSDN博客

Logo

K8S/Kubernetes社区为您提供最前沿的新闻资讯和知识内容

更多推荐