什么是 Azure 服务主体?

What is Azure Service Principal?

我的要求很简单。我想在非交互模式下通过我的 shell 脚本登录到 Azure,但是 "az login -u username -p password" 命令给出了以下错误:

Get Token request returned http error: 400 and server response: {"error":"invalid_grant","error_description":"AADSTS70002: Error validating credentials. : SAML token is invalid. : The element with ID 'xxxxxx' was either unsigned or the signature was invalid.

一些网站告诉我创建一个服务主体。现在我的问题是,什么是服务主体,以及如何创建服务主体以便我可以从我的 shell 脚本执行我的命令(用于创建不同的资源,如应用程序网关)?

开始吧:Use portal to create an Azure Active Directory application and service principal that can access resources.

When you have an application that needs to access or modify resources, you must set up an Azure Active Directory (AD) application and assign the required permissions to it. This approach is preferable to running the app under your own credentials because:

  • You can assign permissions to the app identity that are different than your own permissions. Typically, these permissions are restricted to exactly what the app needs to do.
  • You do not have to change the app's credentials if your responsibilities change.
  • You can use a certificate to automate authentication when executing an unattended script.

请参考这个official document

An Azure service principal is a security identity used by user-created apps, services, and automation tools to access specific Azure resources. Think of it as a 'user identity' (login and password or certificate) with a specific role, and tightly controlled permissions to access your resources. It only needs to be able to do specific things, unlike a general user identity. It improves security if you only grant it the minimum permissions level needed to perform its management tasks.

如果您想使用 Azure CLi 2.0 创建新的服务主体 (sp)。您可以使用 Azure AD 用户登录。然后执行以下命令。

az ad sp create-for-rbac --name {appId} --password "{strong password}"

结果如下:

{
  "appId": "a487e0c1-82af-47d9-9a0b-af184eb87646d",
  "displayName": "MyDemoWebApp",
  "name": "http://MyDemoWebApp",
  "password": {strong password},
  "tenant": "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX"
}

appId是您的登录用户,password是登录密码。

创建sp后,你还需要赋予它Contributor角色,然后你才能管理你的Azure资源。

az role assignment create --assignee <objectID> --role Contributor

现在,您可以使用以下命令以非交互模式登录。

az login --service-principal -u <appid> --password {password-or-path-to-cert} --tenant {tenant}

服务主体只是在 Azure AD 中模拟用户。参考 - https://sanganakauthority.blogspot.com/2019/04/how-to-create-service-principal-or-app.html

使用它,您可以使用 REST API 对 Azure 执行任何类型的管理任务。这样您就无需在弹出窗口中提供凭据,从而有助于使用 REST API 在 Azure 中实现自动化。