跳到主内容

Kubernetes

根据Kubernetes文档,Kubernetes的API服务器可以使用OpenID Connect (OIDC)进行身份验证。 本文将指导您如何使用Casdoor在Kubernetes中配置身份验证。

环境要求

Prerequisites:

  • 一个Kubernetes集群。
  • 像这样的Casdoor应用程序演示网站
  • kubectl命令工具(可选)。
备注

Kubernetes的oidc-issuer-url只接受使用https://前缀的URL。 因此,您的Casdoor应用程序应部署在HTTPS网站上。

步骤1:创建一个Casdoor应用和用户账户进行身份验证

In Casdoor add an application (e.g. Kubernetes). Note Name, Organization, Client ID, and Client secret. Enable the grant types the cluster will use.

在Casdoor中创建一个应用 授权类型

Add a user; set Organization and Signup application to the application you created.

在Casdoor中添加一个用户

步骤2:使用OIDC身份验证配置Kubernetes API服务器

To enable the OIDC plugin, set the following flags on the API server:

  • --oidc-issuer-url:允许API服务器发现公共签名密钥的提供者的URL。
  • --oidc-client-id:所有令牌必须为其发出的客户端id。

本文使用minikube进行演示。 Configure the OIDC plugin for the minikube API server using the following command at startup:

minikube start --extra-config=apiserver.oidc-issuer-url=https://demo.casdoor.com --extra-config=apiserver.oidc-client-id=294b09fbc17f95daf2fe

步骤3:测试OIDC身份验证

获取身份验证信息

由于kubectl缺乏前端,可以通过向Casdoor服务器发送POST请求进行身份验证。 这是在Python中向Casdoor服务器发送POST请求并检索id_tokenrefresh_token的代码:

import requests
import json

url = "https://demo.casdoor.com/api/login/oauth/access_token"
payload = json.dumps({
"grant_type": "password",
"client_id": "Kubernetes",
"client_secret": "72c65c3912aec24a9f3ec41b65a7577114ed2bae",
"username": "user_3u94sf",
"password": "123456"
})
response = requests.request("POST", url, data=payload)

print(response.text)

执行此代码后,您应收到类似于以下的响应:

{
"access_token": "xxx",
"id_token": "yyy",
"refresh_token": "zzz",
"token_type": "Bearer",
"expires_in": 72000,
"scope": ""
}

Use the obtained id_token to authenticate with the Kubernetes API server.

基于HTTP请求的身份验证

将令牌添加到请求头。

curl https://www.xxx.com -k -H "Authorization: Bearer $(id_token)"
  • https://www.xxx.com是Kubernetes API服务器的部署地址。

基于Kubectl客户端的身份验证

配置文件方法

将以下配置写入~/.kube/config文件。 您应该用您之前获得的值替换配置文件中的每个配置项。

users:
- name: minikube
user:
auth-provider:
config:
client-id: Kubernetes
client-secret: 72c65c3912aec24a9f3ec41b65a7577114ed2bae
id-token: $(id_token)
idp-issuer-url: https://demo.casdoor.com
refresh-token: $(refresh_token)
name: oidc

Access the API server with kubectl. 尝试运行一个测试命令。

kubectl cluster-info

命令行参数方法

Alternatively, pass the id_token in kubectl command-line parameters.

kubectl --token=$(id_token) cluster-info