k8s 接入keycloak认证

3,218次阅读
2 条评论

共计 35701 个字符,预计需要花费 90 分钟才能阅读完成。

k8s 接入keycloak认证

前言

OpenID Connect 是一种 OAuth2 认证方式, 被某些 OAuth2 提供者支持,例如 Azure 活动目录、Salesforce 和 Google。 协议对 OAuth2 的主要扩充体现在有一个附加字段会和访问令牌一起返回, 这一字段称作 ID Token(ID 令牌)。 ID 令牌是一种由服务器签名的 JSON Web 令牌(JWT),其中包含一些可预知的字段, 例如用户的邮箱地址,来看一下kubernetes使用OIDC的认证流程

k8s 接入keycloak认证
  • 1.用户登录认证服务器。
  • 2.认证服务器返回 access_tokenid_token refresh_token
  • 3.在使用 kubectl 时,将 id_token 设置为 –token 的参数值,或者将其直接添加到 kubeconfig 中。
  • 4.kubectl 将 id_token 添加到 HTTP 请求的 Authorization 头部中,发送给 API Server。
  • 5.API Server 通过检查配置中引用的证书来确认 JWT 的签名是否合法。
  • 6.API Server 检查 id_token 是否过期。
  • 7.API Server 确认用户是否有操作资源的权限。
  • 8.鉴权成功之后,API 服务器向 kubectl 返回响应。
  • 9.kubectl 向用户返回结果。

由于用来验证你是谁的所有数据都在 id_token 中,Kubernetes 不需要再去联系身份服务。 在一个所有请求都是无状态请求的模型中,这一工作方式可以使得身份认证的解决方案更容易处理大规模请求。 不过,此访问也有一些挑战:

  • Kubernetes 没有提供用来触发身份认证过程的 “Web 界面”。 因为不存在用来收集用户凭据的浏览器或用户接口,你必须自己先行完成对身份服务的认证过程。
  • id_token 令牌不可收回。因其属性类似于证书,其生命期一般很短(只有几分钟), 所以,每隔几分钟就要获得一个新的令牌这件事可能很让人头疼。
  • 如果需要向 Kubernetes 控制面板执行身份认证,你必须使用 kubectl proxy 命令或者一个能够注入 id_token 的反向代理

Keycloak服务快速部署

Kubernetes 要求使用的 OpenID Connect 认证服务必须是 HTTPS 加密的,运行以下脚本生成 Keycloak 服务器的私钥和证书签名请求,并使用 Kubernetes 的 CA 证书进行签发,当然这里你也可以另外生成自己的 CA 证书进行签发,如果这样做的话,请注意在 7.1 启用 OpenID Connect 认证章节中将 CA 证书挂载进 API Server 容器中:

  --oidc-issuer-url=https://keycloak.xadocker.com/auth/realms/kubernetes 
  --oidc-client-id=kubernetes
  --oidc-username-claim=preferred_username
  --oidc-username-prefix=-
  --oidc-groups-claim=groups
  --oidc-ca-file=/root/keycloak.xadocker.com.pem # 挂载ca证书

此处我们用k8s集群来签发CA证书测试

[root@k8s-master keycloak]# cat >keycloak-genera-ssl.sh<<-'AEOF'
#!/bin/bash
# 创建目录存放生成的证书
mkdir -p ssl

# 生成 x509 v3 扩展文件
cat << EOF > ssl/req.cnf
[req]
req_extensions = v3_req
distinguished_name = req_distinguished_name
[req_distinguished_name]
[ v3_req ]
basicConstraints = CA:FALSE
keyUsage = nonRepudiation, digitalSignature, keyEncipherment
subjectAltName = IP:192.168.44.158  # Keycloak 服务器的 IP 地址
EOF

# 生成 Keycloak 服务器私钥
openssl genrsa -out ssl/tls.key 2048
# 生成 Keycloak 服务器证书签名请求(CSR)
openssl req -new -key ssl/tls.key -out ssl/tls.csr -subj "/CN=Keycloak" -config ssl/req.cnf
# 使用 CA 签发 Keycloak 服务器证书
openssl x509 -req -in ssl/tls.csr -CA /etc/kubernetes/pki/ca.crt -CAkey /etc/kubernetes/pki/ca.key -CAcreateserial -out ssl/tls.crt -days 365 -extensions v3_req -extfile ssl/req.cnf
AEOF

[root@k8s-master keycloak]# bash test.sh
Generating RSA private key, 2048 bit long modulus
.................+++
...............................................................+++
e is 65537 (0x10001)
Signature ok
subject=/CN=Keycloak
Getting CA Private Key

# 自行将生成的ssl目录打包发送你的keycloak服务器中,略
[root@k8s-master keycloak]# ll ssl
total 16
-rw-r--r-- 1 root root  232 Aug 14 13:48 req.cnf
-rw-r--r-- 1 root root 1046 Aug 14 13:48 tls.crt
-rw-r--r-- 1 root root  968 Aug 14 13:48 tls.csr
-rw-r--r-- 1 root root 1679 Aug 14 13:48 tls.key

安装keycloak

此处在我的开发机(ubuntu)中采用docker-compose方式安装

xadocker@xadocker-virtual-machine:~/workdir/datadir/keycloak$ cat >docker-compose.yaml<<-'EOF'
version: '2'
services:
  postgres:
      image: postgres:12.2
      environment:
        POSTGRES_DB: keycloak
        POSTGRES_USER: keycloak
        POSTGRES_PASSWORD: keycloak
  keycloak:
      image: jboss/keycloak:16.1.1
      environment:
        DB_VENDOR: POSTGRES
        DB_ADDR: postgres
        DB_DATABASE: keycloak
        DB_USER: keycloak
        DB_PASSWORD: keycloak
        KEYCLOAK_USER: admin # 用户名 
        KEYCLOAK_PASSWORD: xad123456 # 密码
      volumes:
        - ./ssl:/etc/x509/https # 将服务器证书和私钥挂载到容器中
      ports:
        - 80:8080
        - 443:8443
      depends_on:
        - postgres
EOF

# 当前目录下文件,注意需要把之前签证的SSL证书目录放在此处
xadocker@xadocker-virtual-machine:~/workdir/datadir/keycloak$ tree
.
├── docker-compose.yaml
└── ssl
    ├── req.cnf
    ├── tls.crt
    ├── tls.csr
    └── tls.key

# 启动服务
xadocker@xadocker-virtual-machine:~/workdir/datadir/keycloak$ sudo docker-compose up -d 
Creating network "keycloak_default" with the default driver
Creating keycloak_postgres_1 ... done
Creating keycloak_keycloak_1 ... done

# 查看服务状态
xadocker@xadocker-virtual-machine:~/workdir/datadir/keycloak$ sudo docker-compose ps -a
       Name                      Command               State                                Ports                             
------------------------------------------------------------------------------------------------------------------------------
keycloak_keycloak_1   /opt/jboss/tools/docker-en ...   Up      0.0.0.0:80->8080/tcp,:::80->8080/tcp,                          
                                                               0.0.0.0:443->8443/tcp,:::443->8443/tcp                         
keycloak_postgres_1   docker-entrypoint.sh postgres    Up      5432/tcp

在浏览器中访问keycloak页面测试:https:yourip:443,用户名:admin,密码:xad123456

k8s 接入keycloak认证

Keycloak配置

在 Keycloak 中有以下几个主要概念:

  • 领域(realms):领域管理着一批用户、证书、角色、组等等,不同领域之间的资源是相互隔离的,实现了多租户的效果。
  • 客户端(clients):需要接入 Keycloak 实现用户认证的应用和服务。
  • 用户(users):用户是能够登录到应用系统的实体,拥有相关的属性,例如电子邮件、用户名、地址、电话号码和生日等等。
  • 组(groups):一组用户的集合,你可以将一系列的角色赋予定义好的用户组,一旦某用户属于该用户组,那么该用户将获得对应组的所有角色权限。
  • 角色(roles):角色是 RBAC 的重要概念,用于表明用户的身份类型。
  • 证书(credential):Keycloak 用于验证用户的凭证,例如密码、一次性密码、证书、指纹等等。

创建realms

创建一个名为test-paas的realms,keycloak默认自带一个master领域

k8s 接入keycloak认证

创建users

k8s 接入keycloak认证

创建clients

k8s 接入keycloak认证

配置mappers

k8s 接入keycloak认证

修改Token时间

k8s 接入keycloak认证

查看Endpoints信息

k8s 接入keycloak认证

kubernetes配置

配置k8s接入OIDC认证

修改apiserver的运行参数,增加如下几行

[root@k8s-master manifests]# pwd
/etc/kubernetes/manifests
[root@k8s-master manifests]# ll
total 16
-rw------- 1 root root 1882 Jul 19 21:35 etcd.yaml
-rw------- 1 root root 2730 Jul 19 21:35 kube-apiserver.yaml
-rw------- 1 root root 2598 Jul 19 21:35 kube-controller-manager.yaml
-rw------- 1 root root 1153 Jul 19 21:35 kube-scheduler.yaml

[root@k8s-master manifests]# cat kube-apiserver.yaml
apiVersion: v1
kind: Pod
metadata:
  annotations:
    kubeadm.kubernetes.io/kube-apiserver.advertise-address.endpoint: 192.168.44.151:6443
  creationTimestamp: null
  labels:
    component: kube-apiserver
    tier: control-plane
  name: kube-apiserver
  namespace: kube-system
spec:
  containers:
  - command:
    - kube-apiserver
    - --advertise-address=192.168.44.151
    - --allow-privileged=true
    - --authorization-mode=Node,RBAC
    - --client-ca-file=/etc/kubernetes/pki/ca.crt
    - --enable-admission-plugins=NodeRestriction
    - --enable-bootstrap-token-auth=true
    - --etcd-cafile=/etc/kubernetes/pki/etcd/ca.crt
    - --etcd-certfile=/etc/kubernetes/pki/apiserver-etcd-client.crt
    - --etcd-keyfile=/etc/kubernetes/pki/apiserver-etcd-client.key
    - --etcd-servers=https://127.0.0.1:2379
    - --insecure-port=0
    - --kubelet-client-certificate=/etc/kubernetes/pki/apiserver-kubelet-client.crt
    - --kubelet-client-key=/etc/kubernetes/pki/apiserver-kubelet-client.key
    - --kubelet-preferred-address-types=InternalIP,ExternalIP,Hostname
    - --proxy-client-cert-file=/etc/kubernetes/pki/front-proxy-client.crt
    - --proxy-client-key-file=/etc/kubernetes/pki/front-proxy-client.key
    - --requestheader-allowed-names=front-proxy-client
    - --requestheader-client-ca-file=/etc/kubernetes/pki/front-proxy-ca.crt
    - --requestheader-extra-headers-prefix=X-Remote-Extra-
    - --requestheader-group-headers=X-Remote-Group
    - --requestheader-username-headers=X-Remote-User
    - --secure-port=6443
    - --service-account-key-file=/etc/kubernetes/pki/sa.pub
    - --service-cluster-ip-range=10.96.0.0/16
    - --tls-cert-file=/etc/kubernetes/pki/apiserver.crt
    - --tls-private-key-file=/etc/kubernetes/pki/apiserver.key

    # 添加以下oidc参数
    - --oidc-issuer-url=https://192.168.44.158/auth/realms/test-paas
    - --oidc-client-id=kubernetes
    - --oidc-username-claim=name
    - --oidc-username-prefix=-
    - --oidc-ca-file=/etc/kubernetes/pki/ca.crt
    image: registry.aliyuncs.com/k8sxio/kube-apiserver:v1.18.9
    imagePullPolicy: IfNotPresent
    livenessProbe:
      failureThreshold: 8
      httpGet:
        host: 192.168.44.151
        path: /healthz
        port: 6443
        scheme: HTTPS
      initialDelaySeconds: 15
      timeoutSeconds: 15
    name: kube-apiserver
    resources:
      requests:
        cpu: 250m
    volumeMounts:
    - mountPath: /etc/ssl/certs
      name: ca-certs
      readOnly: true
    - mountPath: /etc/pki
      name: etc-pki
      readOnly: true
    - mountPath: /etc/kubernetes/pki
      name: k8s-certs
      readOnly: true
  hostNetwork: true
  priorityClassName: system-cluster-critical
  volumes:
  - hostPath:
      path: /etc/ssl/certs
      type: DirectoryOrCreate
    name: ca-certs
  - hostPath:
      path: /etc/pki
      type: DirectoryOrCreate
    name: etc-pki
  - hostPath:
      path: /etc/kubernetes/pki
      type: DirectoryOrCreate
    name: k8s-certs
status: {}

# 修改完后apiserver会自动重新部署,若配置错误可能会导致apiserver不可用

创建测试集群角色和绑定

[root@k8s-master keycloak]# cat >xadocker-crb.yaml
<<-'EOF'
kind: ClusterRole
apiVersion: rbac.authorization.k8s.io/v1
metadata:
  name: namespace-view
rules:
  - apiGroups: [""]
    resources: ["namespaces"] 
    verbs: ["get", "watch", "list"]
---
kind: ClusterRoleBinding
apiVersion: rbac.authorization.k8s.io/v1
metadata:
  name: xadocker-crb
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: namespace-view
subjects:
- kind: User
  name: xadocker
  apiGroup: rbac.authorization.k8s.io

EOF

[root@k8s-master keycloak]# kubectl apply -f xadocker-crb.yaml
clusterrole.rbac.authorization.k8s.io/namespace-view created
clusterrolebinding.rbac.authorization.k8s.io/xadocker-crb created

获取认证令牌

现在我们已经完成了 Keycloak 和 Kubernetes 的设置,接下来我们尝试获取身份验证令牌,需要提供以下参数:

  • grant_type:获取令牌的方式。OAuth 2.0 规定了四种获取令牌的方式,分别是:授权码(authorization-code)、隐藏式(implicit)、密码式(password)、客户端凭证(client credentials)。password 表示以密码的方式获取令牌。
  • client_id:客户端 ID。
  • client_secret:客户端密钥。client_secret 可以在 kubernetes 客户端的 Credentials 中获取
  • username:用户名。
  • password:密码。
  • scope:要求的授权范围,OpenID Connect 的请求 scope 设置为 openid。

查看client_secret

k8s 接入keycloak认证

使用curl获取令牌

[root@k8s-master keycloak]# yum install jq -y
[root@k8s-master ~]# curl -ks -X POST https://192.168.44.158/auth/realms/test-paas/protocol/openid-connect/token -d grant_type=password -d client_id=kubernetes -d username=xadocker -d password=xadocker -d scope=openid -d client_secret=J7C8ELBUs8VkGVS7fdARfqkkiBK28Zh3 | jq .
{
  "access_token": "eyJhbGciOiJSUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICI1NmJwY1daLTJ6UldoOUkyY0U5SkhPaXViZXBfUEh4RTVmUG1ZUEtJOU1VIn0.eyJleHAiOjE2NjA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5ODgtYjYwYi1lOGNlZWQyNjg2YjUiLCJpc3MiOiJodHRwczovLzE5Mi4xNjguNDQuMTU4L2F1dGgvcmVhbG1zL3Rlc3QtcGFhcyIsImF1ZCI6Imt1YmVybmV0ZXMiLCJzdWIiOiIzZjg2YzgyNy1iM2NiLTRjYmYtYWM3ZC05ZmVhNzMxNjY2NmEiLCJ0eXAiOiJJRCIsImF6cCI6Imt1YmVybmV0ZXMiLCJzZXNzaW9uX3N0YXRlIjoiNzhmNTY1MDAtYWQ1NC00MzllLTlmYjYtMjRjNzkxYmVmYzlmIiwiYXRfaGFzaCI6IjNITHdPLVN3dFVUVkJtb2Y0YTJkLUEiLCJhY3IiOiIxIiwic2lkIjoiNzhmNTY1MDAtYWQ1NC00MzllLTlmYjYtMjRjNzkxYmVmYzlmIiwiZW1haWxfdmVyaWZpZWQiOmZhbHNlLCJuYW1lIjoieGFkb2NrZXIiLCJwcmVmZXJyZWRfdXNlcm5hbWUiOiJ4YWRvY2tlciJ9.N4ONpdjkOr21-uqchwWHS9qNq5AfFnZgK214iu58nCSq-wo8esWll3xGYMDcbxetczzr1mh13J5rxUpqwNQPBdODGat9FpMECfBJDhkt8MDEtMihR_acePG9JKoDvnF0Ei1S_NNn0Q3HIWvKeWN_RGHKGaDi_01eTD1eVTwp3gaUIkZK3npPYiX8a3isMIzDIHFakxUfQYbBSjFakuNpHcuv4JAodN43F1iiBmFY-OIPeXnnViiMOT-j5j_92gs03waVP0Vf9UpJfVe2rXOzYgN9-MnqGfXQhzvvywc7lHeVyY78lisV7UYNl5I8EqMZkPBLBn9FefDfDR1LovXqxA",
  "not-before-policy": 0,
  "session_state": "78f56500-ad54-439e-9fb6-24c791befc9f",
  "scope": "openid profile email"
}

测试使用该id_token调用apiserver

[root@k8s-master keycloak]#  curl -k https://apiserver.demo:6443/api/v1/namespaces -H "Authorization: Bearer eyJhbGciOiJSUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICI1NmJwY1daLTJ6UldoOUky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ceVersion": "1981"
  },
  "items": [
    {
      "metadata": {
        "name": "default",
        "selfLink": "/api/v1/namespaces/default",
        "uid": "de9ddb07-7031-40ad-baa4-95e433214f67",
        "resourceVersion": "152",
        "creationTimestamp": "2022-08-14T08:52:08Z",
        "managedFields": [
          {
            "manager": "kube-apiserver",
            "operation": "Update",
            "apiVersion": "v1",
            "time": "2022-08-14T08:52:08Z",
            "fieldsType": "FieldsV1",
            "fieldsV1": {"f:status":{"f:phase":{}}}
          }
        ]
      },
      "spec": {
        "finalizers": [
          "kubernetes"
        ]
      },
      "status": {
        "phase": "Active"
      }
    },
    {
      "metadata": {
        "name": "kube-node-lease",
        "selfLink": "/api/v1/namespaces/kube-node-lease",
        "uid": "e880d057-49f4-4fc3-a5d7-8863884d7de8",
        "resourceVersion": "14",
        "creationTimestamp": "2022-08-14T08:52:06Z",
        "managedFields": [
          {
            "manager": "kube-apiserver",
            "operation": "Update",
            "apiVersion": "v1",
            "time": "2022-08-14T08:52:06Z",
            "fieldsType": "FieldsV1",
            "fieldsV1": {"f:status":{"f:phase":{}}}
          }
        ]
      },
      "spec": {
        "finalizers": [
          "kubernetes"
        ]
      },
      "status": {
        "phase": "Active"
      }
    },
    {
      "metadata": {
        "name": "kube-public",
        "selfLink": "/api/v1/namespaces/kube-public",
        "uid": "48797249-dbd2-477d-b645-9e5c337faba6",
        "resourceVersion": "6",
        "creationTimestamp": "2022-08-14T08:52:06Z",
        "managedFields": [
          {
            "manager": "kube-apiserver",
            "operation": "Update",
            "apiVersion": "v1",
            "time": "2022-08-14T08:52:06Z",
            "fieldsType": "FieldsV1",
            "fieldsV1": {"f:status":{"f:phase":{}}}
          }
        ]
      },
      "spec": {
        "finalizers": [
          "kubernetes"
        ]
      },
      "status": {
        "phase": "Active"
      }
    },
    {
      "metadata": {
        "name": "kube-system",
        "selfLink": "/api/v1/namespaces/kube-system",
        "uid": "3087b69d-c656-4e2f-99a6-4145c3f41dc5",
        "resourceVersion": "5",
        "creationTimestamp": "2022-08-14T08:52:06Z",
        "managedFields": [
          {
            "manager": "kube-apiserver",
            "operation": "Update",
            "apiVersion": "v1",
            "time": "2022-08-14T08:52:06Z",
            "fieldsType": "FieldsV1",
            "fieldsV1": {"f:status":{"f:phase":{}}}
          }
        ]
      },
      "spec": {
        "finalizers": [
          "kubernetes"
        ]
      },
      "status": {
        "phase": "Active"
      }
    }
  ]

使用refresh_token重新获取一个id_token,因为每个token只有30分钟有效期(可自行修改,在上文relams中设置token生命周期)

[root@k8s-master keycloak]# curl -ks -X POST https://192.168.44.158/auth/realms/test-paas/protocol/openid-connect/token -d grant_type=refresh_token -d client_id=kubernetes -d scope=openid -d client_secret=J7C8ELBUs8VkGVS7fdARfqkkiBK28Zh3 -d refresh_token=eyJhbGciOiJIUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICJiNmE2NWVlMy0yMzEzLTRlMzUtOGQ3NC0xOGVlMDMwNzE2MDUifQ.eyJleHAiOjE2NjA0Njk1MDUsImlhdCI6MTY2MDQ2NzcwNSwianRpIjoiYWIyODE1ZTktNjUxMy00N2NiLTkzMzgtYzRhMjljZjU3N2QzIiwiaXNzIjoiaHR0cHM6Ly8xOTIuMTY4LjQ0LjE1OC9hdXRoL3JlYWxtcy90ZXN0LXBhYXMiLCJhdWQiOiJodHRwczovLzE5Mi4xNjguNDQuMTU4L2F1dGgvcmVhbG1zL3Rlc3QtcGFhcyIsInN1YiI6IjNmODZjODI3LWIzY2ItNGNiZi1hYzdkLTlmZWE3MzE2NjY2YSIsInR5cCI6IlJlZnJlc2giLCJhenAiOiJrdWJlcm5ldGVzIiwic2Vzc2lvbl9zdGF0ZSI6Ijc4ZjU2NTAwLWFkNTQtNDM5ZS05ZmI2LTI0Yzc5MWJlZmM5ZiIsInNjb3BlIjoib3BlbmlkIHByb2ZpbGUgZW1haWwiLCJzaWQiOiI3OGY1NjUwMC1hZDU0LTQzOWUtOWZiNi0yNGM3OTFiZWZjOWYifQ.6dV1N4X0y4lZ8j4evntiHPT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b6-24c791befc9f",
  "scope": "openid profile email"
}

使用kubectl方式测试

生成kubeconfig

[root@k8s-master keycloak]# kubectl config set-credentials xadocker --auth-provider=oidc    --auth-provider-arg=idp-issuer-url=https://192.168.44.158/auth/realms/test-paas --auth-provider-arg=client-id=kubernetes    --auth-provider-arg=client-secret=J7C8ELBUs8VkGVS7fdARfqkkiBK28Zh3 --auth-provider-arg=refresh-token=eyJhbGciOiJIUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICJiNmE2NWVlMy0yMzEzLTRlMzUtOGQ3NC0xOGVlMDMwNzE2MDUifQ.eyJleHAiOjE2NjA0Njk4MzcsImlhdCI6MTY2MDQ2ODAzNywianRpIjoiZDc0MzlhOTYtMWJiMy00MDdjLWJhNjctY2NkZjljY2ExMmU0IiwiaXNzIjoiaHR0cHM6Ly8xOTIuMTY4LjQ0LjE1OC9hdXRoL3JlYWxtcy90ZXN0LXBhYXMiLCJhdWQiOiJodHRwczovLzE5Mi4xNjguNDQuMTU4L2F1dGgvcmVhbG1zL3Rlc3QtcGFhcyIsInN1YiI6IjNmODZjODI3LWIzY2ItNGNiZi1hYzdkLTlmZWE3MzE2NjY2YSIsInR5cCI6IlJlZnJlc2giLCJhenAiOiJrdWJlcm5ldGVzIiwic2Vzc2lvbl9zdGF0ZSI6Ijc4ZjU2NTAwLWFkNTQtNDM5ZS05ZmI2LTI0Yzc5MWJlZmM5ZiIsInNjb3BlIjoib3BlbmlkIHByb2ZpbGUgZW1haWwiLCJzaWQiOiI3OGY1NjUwMC1hZDU0LTQzOWUtOWZiNi0yNGM3OTFiZWZjOWYifQ.QoezuV8TKVjfSQ6VzU_Mr__ML-luqRVq9t11rHXpC_4 --auth-provider-arg=id-token=eyJhbGciOiJSUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICI1NmJwY1daLTJ6UldoOUkyY0U5SkhPaXViZXBfUEh4RTVmUG1ZUEtJOU1VIn0.eyJleHAiOjE2NjA0Njk4MzcsImlhdCI6MTY2MDQ2ODAzNywiYXV0aF90aW1lIjowLCJqdGkiOiIxYzg5YzdkZC00MTc3LTQ5OTctODI1OC1lZjU2MWEzZDJhOTkiLCJpc3MiOiJodHRwczovLzE5Mi4xNjguNDQuMTU4L2F1dGgvcmVhbG1zL3Rlc3QtcGFhcyIsImF1ZCI6Imt1YmVybmV0ZXMiLCJzdWIiOiIzZjg2YzgyNy1iM2NiLTRjYmYtYWM3ZC05ZmVhNzMxNjY2NmEiLCJ0eXAiOiJJRCIsImF6cCI6Imt1YmVybmV0ZXMiLCJzZXNzaW9uX3N0YXRlIjoiNzhmNTY1MDAtYWQ1NC00MzllLTlmYjYtMjRjNzkxYmVmYzlmIiwiYXRfaGFzaCI6Ik1KS05CMW1fSThoU0pIbElIcGFTaHciLCJhY3IiOiIxIiwic2lkIjoiNzhmNTY1MDAtYWQ1NC00MzllLTlmYjYtMjRjNzkxYmVmYzlmIiwiZW1haWxfdmVyaWZpZWQiOmZhbHNlLCJuYW1lIjoieGFkb2NrZXIiLCJwcmVmZXJyZWRfdXNlcm5hbWUiOiJ4YWRvY2tlciJ9.ZWSBodNgWLmc24aDbGdC0xaeYFvaZIfYR_WRkTre6QCUo2VVMhNVrvcqPcr2M7ToCMDRtfb6SCw_8LVmZm0dyWzLQqVr_Vqz9bAc7HMHYHYOcSmk7tcOFQJcckZD9n5W8YrCsOesNbv3CslkXZBlaz7y3W_3FwDSYxJprpsslhB_ZAXBVG-fkyJBzkqIbRjL02GgNzaPq1Z9wNuHSjlJVAm04eu7Xh1IK-7Bg1u0uwbjuh0D-qBP1YrbLMtxPqldBYQQ-yQdYZD6_QjUWFJGXN4FyHbQlnOzEoEItNLrPOLjFUdnMgaR5fwa3ScTVse0hApytBDJrHsFZyPKotNvOQ --auth-provider-arg=idp-certificate-authority=/etc/kubernetes/pki/ca.crt
User "xadocker" set.

查看当前kubeconfig

[root@k8s-master ~]# cat .kube/config
apiVersion: v1
clusters:
- cluster:
    certificate-authority-data: LS0tLS1CRUdJT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dWN0N5Q1BjClp0alh2MWlLcVJkSEEyam83ZU11VTRLMkMvRFlKTFNSVkcwSStjamRuYzN2a0hoMjBvaDVPdTR3NUhHRWhrci8KTjdCdVhwN2pRM1BKUjhUQmluWmxMS0JJZEdsOVNYay9ad29Fd1V3YzNMdFlrRGNjeVhuZmdkMmJORjVOYkVFbwo4Qm5WdnR6K1JSd0hFUUdFTTRDT0t1OWFHUHlUNFdmYU83bSsxaDhBYXBENVRYOVY0TTI3SHFpVnVWUT0KLS0tLS1FTkQgQ0VSVElGSUNBVEUtLS0tLQo=
    server: https://apiserver.demo:6443
  name: kubernetes
contexts:
- context:
    cluster: kubernetes
    user: kubernetes-admin
  name: kubernetes-admin@kubernetes
current-context: kubernetes-admin@kubernetes
kind: Config
preferences: {}
users:
- name: kubernetes-admin
  user:
    client-certificate-data: LS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS0tCk1JSUM4akNDQWRxZ0F3SUJBZ0lJTXhDMklyYUVuRUl3RFFZSktvWklodmNOQVFFTEJRQXdGVEVUTUJFR0ExVUUKQXhNS2EzVmlaWEp1WlhSbGN6QWVGdzB5TWpBNE1UUXdPRFV4TkRsYUZ3MHlNekE0TVRRd09EVXhOVE5hTURReApGekFWQmdOVkJBb1REbk41YzNSbGJUcHRZWE4wWlhKek1Sa3dGd1lEVlFRREV4QnJkV0psY201bGRHVnpMV0ZrCmJXbHVNSUlCSWpBTkJna3Foa2lHOXcwQkFRRUZBQU9DQVE4QU1JSUJDZ0tDQVFFQTRZdExjWms4a0pqK3FDMkoKYUgrTUZpUmNXcjRvN0wwTGRhQmt0TzJFMVhuTGdqdjFNNkdYZ3BxeVFHMXR4YWQyZGhiWTFaNnVnV05LMEFEcApxcFpTU2VsZVorazJRUnVPZEhwWTFqM1RSQkZGNXliOTV3bzc5Q29BY0crMlVuU1ZLZGxNZitTZmo1TjFldUxmCm8xMkhzUXlnNmNBQzlWL2ZZOC93RHpIdlVkRHlmTGk5VG1iQzlUSUhjT1ZD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TGlHTENZZDFTdGpNRjcxV0tPTCtlbGFnbXlqL3lSbkV1eit4NW0rbHY0T3lwMnZTWUcwcGI2SgpUZGVINUZ5Skp0V3g0UDZ5QUsyWTdYMjJiMEVYUlJESGF0QWVQTWYwVVY2NldQcWl6S1F1QzFJcVRyZnlML3Y5CnJrT3UzZUZNcWIvUGs0MlJXQVBMaHMzVm5mNXZBUklicWhwbk1rNXRBb0dBYlIxZEFDT1JkYmhoOHhBTU5jLzEKZ0FqT3Z6Q042L1Rja3MvSmtSb3o0VHhmMGZueEtjMzQyVGlSNThFMTJTU3dSdk9xeGsvUE94b1JZcjE0ZGZUUQp3bnorWTAyNmNBZ3lkTVdIbUs5MGRWWmpLcFc5NnRUd052MmVhdzBLS3F2VitGR1V3L3p6L2gwUU81K1h3Ri9UCm96T21MaVFuNFJPZ2padUdTcjZwa2UwQ2dZRUFwZGlJR2x5UjFlQ2Y0RjB2a25id2dLV0d4emdpSXVLTExQemgKR2NjUnRraktMMjUwbzdiOUIvejl1cDRoWm9LODQxNzNWSmp1U3ZuQVl6R1AwSUk2RklueFF5YmRiKys0cW1TUApTcTlKbGkxcktkaHNjaXFNT2QyNjl0Mktrc3hjUlJrTk9PUC9OeG1BYnB0YzRxblYvV2tZb040eEtoUmJJck1iCnROanlBYVVDZ1lBR2NwS2VubDkrem5LZGZvK2R2QklFVk01SW1rZmVaUmJJblNYRTBPamN0alJKR1Q2d1NqNzcKYTRPbnU5SWQzeDYvWGlBRTRkeWdGeVFkQ0NHQURRWUFZNnpLYjgwZ3JWRTNqcWVaYVZqTFJET3RQN0V1OFFzdQpGaG5paEFRUlRyd1FHZ09tQnMxLzlaMTl0QUthUmJTN1RYTmJ5OTJvQklySmp5SXZwY3A5RHc9PQotLS0tLUVORCBSU0EgUFJJVkFURSBLRVktLS0tLQo=
- name: xadocker
  user:
    auth-provider:
      config:
        client-id: kubernetes
        client-secret: J7C8ELBUs8VkGVS7fdARfqkkiBK28Zh3
        id-token: eyJhbGciOiJSUz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OQ
        idp-certificate-authority: /etc/kubernetes/pki/ca.crt
        idp-issuer-url: https://192.168.44.158/auth/realms/test-paas
        refresh-token: eyJhbGciOiJIUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICJiNmE2NWVlMy0yMzEzLTRlMzUtOGQ3NC0xOGVlMDMwNzE2MDUifQ.eyJleHAiOjE2NjA0Njk4MzcsImlhdCI6MTY2MDQ2ODAzNywianRpIjoiZDc0MzlhOTYtMWJiMy00MDdjLWJhNjctY2NkZjljY2ExMmU0IiwiaXNzIjoiaHR0cHM6Ly8xOTIuMTY4LjQ0LjE1OC9hdXRoL3JlYWxtcy90ZXN0LXBhYXMiLCJhdWQiOiJodHRwczovLzE5Mi4xNjguNDQuMTU4L2F1dGgvcmVhbG1zL3Rlc3QtcGFhcyIsInN1YiI6IjNmODZjODI3LWIzY2ItNGNiZi1hYzdkLTlmZWE3MzE2NjY2YSIsInR5cCI6IlJlZnJlc2giLCJhenAiOiJrdWJlcm5ldGVzIiwic2Vzc2lvbl9zdGF0ZSI6Ijc4ZjU2NTAwLWFkNTQtNDM5ZS05ZmI2LTI0Yzc5MWJlZmM5ZiIsInNjb3BlIjoib3BlbmlkIHByb2ZpbGUgZW1haWwiLCJzaWQiOiI3OGY1NjUwMC1hZDU0LTQzOWUtOWZiNi0yNGM3OTFiZWZjOWYifQ.QoezuV8TKVjfSQ6VzU_Mr__ML-luqRVq9t11rHXpC_4
      name: oidc

测试访问

[root@k8s-master keycloak]# kubectl --user xadocker get namespace                                                       NAME              STATUS   AGE
default           Active   21m
kube-node-lease   Active   21m
kube-public       Active   21m
kube-system       Active   21m

使用oidc-login插件自动配置

该方式需要在token失效后自行更新,不方便,恰好社区提供了插件oidc-login来自动便捷更新

k8s 接入keycloak认证
# 需要先安装krew来装插件,此处略
xadocker@xadocker-virtual-machine:~$ kubectl krew install oidc-login
Updated the local copy of plugin index.
Installing plugin: oidc-login
Installed plugin: oidc-login
\
 | Use this plugin:
 | 	kubectl oidc-login
 | Documentation:
 | 	https://github.com/int128/kubelogin
 | Caveats:
 | \
 |  | You need to setup the OIDC provider, Kubernetes API server, role binding and kubeconfig.
 | /
/
WARNING: You installed plugin "oidc-login" from the krew-index plugin repository.
   These plugins are not audited for security by the Krew maintainers.
   Run them at your own risk.

配置kubeconfig

# 准备基本kubectl基本集群信息
xadocker@xadocker-virtual-machine:~$ cat .kube/config 
apiVersion: v1
clusters: 
- cluster:
    certificate-authority-data: LS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS0tCk1JSUN5RENDQWJDZ0F3SUJBZ0lCQURBTkJna3Foa2lHOXcwQkFRc0ZBREFWTVJNd0VRWURWUVFERXdwcmRXSmwKY201bGRHVnpNQjRYRFRJeU1EZ3hOREE0TlRFME9Wb1hEVE15TURneE1UQTROVEUwT1Zvd0ZURVRNQkVHQTFVRQpBeE1LYTNWaVpYSnVaWFJsY3pDQ0FTSXdEUVlKS29aSWh2Y05BUUVCQlFBRGdnRVBBRENDQVFvQ2dnRUJBTjArCnRMOWhZWjFRSVZoYnlPQ0xsN0hOd21OT3FxeW9BUHAxdjRUaDJrZnhZVHptUnppc3VSdm1BOS9DL2JJdEE4cDEKR3JWcEhXWitvL1VUYU9zUjlOcmc5S2NBREdQcVAzbkFFeDNRSVRpaTZ1TWYvUFVvU09kUHRJbjRUOUVTVGM2MApsYWV1dE9RN1hBV1JmQ2N3cHA4cUFHWWM5QXkveGc4SDlxaVA5eHJtekRWeFl6UUdOUk5jQkNTR2huQkJ1WnhoCjVqLzFHUHZ5a2x4VWhLTGZEdTBTNVRCT0ZjcjNxU0FzNnl4alFmeCtLU0lVNmVqNkdEL1JYSm12UVNPMlI4b1oKVk1pcnRqK2NVR3EvUVErWXVMS1lXSWc5M255YWl3QXpCbzVkd2UyZ2NtemRBT2ZWRGJFVWw4anJQM2dTQ1EvVwpNTzdROVpZejRIUytkbXY1YXA4Q0F3RUFBYU1qTUNFd0RnWURWUjBQQVFIL0JBUURBZ0trTUE4R0ExVWRFd0VCCi93UUZNQU1CQWY4d0RRWUpLb1pJaHZjTkFRRUxCUUFEZ2dFQkFBNngwUlNvaUdoTFU5TTVWNUV5Ymw4eDdCbksKb3ZqcHcwRndpM0dyZHkyczRYdzBMZEtXZDdlcmZKR2JyMk1WZm1FQ1lERTVLblJuVkF3WE9yQ1pueWNSTmhrSwpmNGc5SDZuMHQxam95T2piT1NKZkdHVWVnb01OaW1HREFYT3RrcDFyS1FNOU5CRkdBcW9YeUFDTXdWN0N5Q1BjClp0alh2MWlLcVJkSEEyam83ZU11VTRLMkMvRFlKTFNSVkcwSStjamRuYzN2a0hoMjBvaDVPdTR3NUhHRWhrci8KTjdCdVhwN2pRM1BKUjhUQmluWmxMS0JJZEdsOVNYay9ad29Fd1V3YzNMdFlrRGNjeVhuZmdkMmJORjVOYkVFbwo4Qm5WdnR6K1JSd0hFUUdFTTRDT0t1OWFHUHlUNFdmYU83bSsxaDhBYXBENVRYOVY0TTI3SHFpVnVWUT0KLS0tLS1FTkQgQ0VSVElGSUNBVEUtLS0tLQo=
    server: https://apiserver.demo:6443
  name: kubernetes
contexts:
- context:
    cluster: kubernetes
    user: ""
  name: ""
current-context: ""
kind: Config
preferences: {}

# 配置oidc-login配置
xadocker@xadocker-virtual-machine:~$ kubectl config set-credentials xadocker     --exec-api-version=client.authentication.k8s.io/v1beta1     --exec-command=kubectl     --exec-arg=oidc-login     --exec-arg=get-token     --exec-arg=--oidc-issuer-url=https://192.168.44.158/auth/realms/test-paas     --exec-arg=--oidc-client-id=kubernetes     --exec-arg=--oidc-client-secret=J7C8ELBUs8VkGVS7fdARfqkkiBK28Zh3     --exec-arg=--insecure-skip-tls-verify
User "xadocker" set.

# 查看此时配置文件
xadocker@xadocker-virtual-machine:~$ cat .kube/config 
apiVersion: v1
clusters:
- cluster:
    certificate-authority-data: LS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS0tCk1JSUN5RENDQWJDZ0F3SUJBZ0lCQURBTkJna3Foa2lHOXcwQkFRc0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dTR3NUhHRWhrci8KTjdCdVhwN2pRM1BKUjhUQmluWmxMS0JJZEdsOVNYay9ad29Fd1V3YzNMdFlrRGNjeVhuZmdkMmJORjVOYkVFbwo4Qm5WdnR6K1JSd0hFUUdFTTRDT0t1OWFHUHlUNFdmYU83bSsxaDhBYXBENVRYOVY0TTI3SHFpVnVWUT0KLS0tLS1FTkQgQ0VSVElGSUNBVEUtLS0tLQo=
    server: https://apiserver.demo:6443
  name: kubernetes
contexts:
- context:
    cluster: kubernetes
    user: ""
  name: ""
current-context: ""
kind: Config
preferences: {}
users:
- name: xadocker
  user:
    exec:
      apiVersion: client.authentication.k8s.io/v1beta1
      args:
      - oidc-login
      - get-token
      - --oidc-issuer-url=https://192.168.44.158/auth/realms/test-paas
      - --oidc-client-id=kubernetes
      - --oidc-client-secret=J7C8ELBUs8VkGVS7fdARfqkkiBK28Zh3
      - --insecure-skip-tls-verify
      command: kubectl
      env: null
      provideClusterInfo: false

登录测试,执行kubectl –user=xadocker get namespace 会自动打开浏览器进入keycloak登录界面

k8s 接入keycloak认证

kubelogin 的 id_token 和 refresh_token 缓存在 ~/.kube/cache/oidc-login/ 目录中,没有超过令牌有效期时,无需再次输入用户名和密码进行认证

xadocker@xadocker-virtual-machine:~$ cat .kube/cache/oidc-login/f7ae9cac5eccb9f0d441a0ab0f48a31e289734564ef583cef74f8c80b775ba9e 
{"id_token":"eyJhbGciOiJSUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICI1NmJwY1daLTJ6UldoOUkyY0U5SkhPaXViZXBfUEh4RTVmUG1ZUEtJOU1VIn0.eyJleHAiOjE2NjA0NzQ4MDgsImlhdCI6MTY2MDQ3MzAwOCwiYXV0aF90aW1lIjoxNjYwNDczMDA4LCJqdGkiOiIwOTNhZjM3OC05M2RkLTQxYjktYmQ5Zi1jNGJmMGU0MzY0YTMiLCJpc3MiOiJodHRwczovLzE5Mi4xNjguNDQuMTU4L2F1dGgvcmVhbG1zL3Rlc3QtcGFhcyIs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cHM6Ly8xOTIuMTY4LjQ0LjE1OC9hdXRoL3JlYWxtcy90ZXN0LXBhYXMiLCJhdWQiOiJodHRwczovLzE5Mi4xNjguNDQuMTU4L2F1dGgvcmVhbG1zL3Rlc3QtcGFhcyIsInN1YiI6IjNmODZjODI3LWIzY2ItNGNiZi1hYzdkLTlmZWE3MzE2NjY2YSIsInR5cCI6IlJlZnJlc2giLCJhenAiOiJrdWJlcm5ldGVzIiwibm9uY2UiOiJxS2Vza1NyZW9OY0RNZTB1MFdjUzBVMVU1emNJWUxnU3VzRl9ldzVCTkJzIiwic2Vzc2lvbl9zdGF0ZSI6IjgyMGRiY2ZiLWI0MjEtNDI1Mi1hYmI3LWUwOTQ4OWZkM2VmNSIsInNjb3BlIjoib3BlbmlkIHByb2ZpbGUgZW1haWwiLCJzaWQiOiI4MjBkYmNmYi1iNDIxLTQyNTItYWJiNy1lMDk0ODlmZDNlZjUifQ.IyiQcM7zz8COZMMu0eKHAk6FA4nbq11HONbt8xxU_jM"}

至此通过oidc协议认证kubernetes功能基本实现,读者可以尝试接入多个集群或创建mapper映射group字段~~

正文完
 1
xadocker
版权声明:本站原创文章,由 xadocker 2022-08-12发表,共计35701字。
转载说明:除特殊说明外本站文章皆由CC-4.0协议发布,转载请注明出处。
评论(2 条评论)
评论达人 LV.1
2022-10-07 14:44:18 回复

windows中怎么弹出登录网页?而且如果是通过跳板机呢?

 Windows  Chrome  中国广东省广州市电信
    Avatar photo
    xadocker 博主
    2022-10-07 14:49:18 回复

    @越 在windows的powershell下安装kubectl和插件或许可行,还没试过~~>_<~~有堡垒机的话老实用命令获取吧,大不了写个shell脚本,后期我看看咯

     Windows  Chrome  中国广东省广州市电信