如何通过将另一个服务主体与 REST API 或 Python SDK 一起使用来 create/delete Azure 服务主体的秘密?
How create/delete secrets of Azure service principal by using another service principal with REST API or Python SDK?
我有 2 个应用程序注册(2 个服务主体)。
首先,我将它们用作我的凭据来获得令牌。
我需要从我的 Python 脚本中创建和删除第二个服务主体的机密。
不幸的是,我没有在文档中找到这样的示例。
我该怎么做?
您可以使用以下代码满足您的要求:
添加Client_Secret:
from azure.identity import ClientSecretCredential
from msgraph.core import GraphClient
import json
clientid= "Serviceprincipal1"
clientsecret = "secret"
tenantid = "tenantId"
credentials=ClientSecretCredential(tenant_id=tenantid,client_id=clientid,client_secret=clientsecret)
graph_client = GraphClient(credential=credentials)
#get details of another service principal by providing the object id of the application
app = graph_client.get('/applications/serviceprincipal2objectid')
print(app.json())
#add new client sceret to that ad app
body={
"passwordCredential": {
"displayName": "NewPaasswordCreatedfromPythonSDK"
}
}
addpass=graph_client.post('/applications/serviceprincipal2objectid/addPassword',json=json.dumps(body))
print("HTTP_request_Response:",addpass.status_code)
输出:
删除Client_Secret:
#remove a client secret for that ad app
body= {
"keyId": "1636f0ce-1b8c-46a0-a580-d0df086b91c7"## keyid of the key added earlier
}
removepass=graph_client.post('/applications/serviceprincipal2objectid/removePassword',json=body)
print("HTTP_request_Response:",removepass.status_code)
输出:
注意: MSGRAPH-core python sdk
仅在预览版中,要使用您必须使用 pip install msgraph-core
安装
我有 2 个应用程序注册(2 个服务主体)。 首先,我将它们用作我的凭据来获得令牌。 我需要从我的 Python 脚本中创建和删除第二个服务主体的机密。 不幸的是,我没有在文档中找到这样的示例。 我该怎么做?
您可以使用以下代码满足您的要求:
添加Client_Secret:
from azure.identity import ClientSecretCredential
from msgraph.core import GraphClient
import json
clientid= "Serviceprincipal1"
clientsecret = "secret"
tenantid = "tenantId"
credentials=ClientSecretCredential(tenant_id=tenantid,client_id=clientid,client_secret=clientsecret)
graph_client = GraphClient(credential=credentials)
#get details of another service principal by providing the object id of the application
app = graph_client.get('/applications/serviceprincipal2objectid')
print(app.json())
#add new client sceret to that ad app
body={
"passwordCredential": {
"displayName": "NewPaasswordCreatedfromPythonSDK"
}
}
addpass=graph_client.post('/applications/serviceprincipal2objectid/addPassword',json=json.dumps(body))
print("HTTP_request_Response:",addpass.status_code)
输出:
删除Client_Secret:
#remove a client secret for that ad app
body= {
"keyId": "1636f0ce-1b8c-46a0-a580-d0df086b91c7"## keyid of the key added earlier
}
removepass=graph_client.post('/applications/serviceprincipal2objectid/removePassword',json=body)
print("HTTP_request_Response:",removepass.status_code)
输出:
注意: MSGRAPH-core python sdk
仅在预览版中,要使用您必须使用 pip install msgraph-core