添加用户

此示例脚本在 API 管理中创建用户并获取订阅密钥。

Note

本文进行了更新,以便使用新的 Azure PowerShell Az 模块。 若要详细了解新的 Az 模块和 AzureRM 兼容性,请参阅新 Azure Powershell Az 模块简介。 有关安装说明,请参阅安装 Azure PowerShell

如果选择在本地安装并使用 PowerShell,则本教程需要 Azure PowerShell 模块 1.0 或更高版本。 运行 Get-Module -ListAvailable Az 即可查找版本。 如果需要升级,请参阅安装 Azure PowerShell 模块。 如果在本地运行 PowerShell,则还需运行 Connect-AzAccount -EnvironmentName AzureChinaCloud 来创建与 Azure 的连接。

示例脚本

##########################################################
#  Script to create a user in api management and get a subscription key
###########################################################

$random = (New-Guid).ToString().Substring(0,8)

#Azure specific details
$subscriptionId = "my-azure-subscription-id"

# Api Management service specific details
$apimServiceName = "apim-$random"
$resourceGroupName = "apim-rg-$random"
$location = "China East"
$organisation = "Contoso"
$adminEmail = "admin@contoso.com"

# User specific details
$userEmail = "user@contoso.com"
$userFirstName = "userFirstName"
$userLastName = "userLastName"
$userPassword = "userPassword"
$userNote = "fellow trying out my apim instance"
$userState = "Active"

# Subscription Name details
$subscriptionName = "subscriptionName"
$subscriptionState = "Active"

# Set the context to the subscription Id where the cluster will be created
Select-AzureRmSubscription -SubscriptionId $subscriptionId

# Create a resource group.
New-AzureRmResourceGroup -Name $resourceGroupName -Location $location

# Create the Api Management service. Since the SKU is not specified, it creates a service with Developer SKU. 
New-AzureRmApiManagement -ResourceGroupName $resourceGroupName -Name $apimServiceName -Location $location -Organization $organisation -AdminEmail $adminEmail

# Create the api management context
$context = New-AzureRmApiManagementContext -ResourceGroupName $resourceGroupName -ServiceName $apimServiceName

# create a new user in api management
$user = New-AzureRmApiManagementUser -Context $context -FirstName $userFirstName -LastName $userLastName `
    -Password $userPassword -State $userState -Note $userNote -Email $userEmail

# get the details of the 'Starter' product in api management, which is created by default
$product = Get-AzureRmApiManagementProduct -Context $context -Title 'Starter' | Select-Object -First 1

# generate a subscription key for the user to call apis which are part of the 'Starter' product
New-AzureRmApiManagementSubscription -Context $context -UserId $user.UserId `
    -ProductId $product.ProductId -Name $subscriptionName -State $subscriptionState

清理资源

如果不再需要资源组和所有相关资源,可以使用 Remove-AzResourceGroup 命令将其删除。

Remove-AzResourceGroup -Name myResourceGroup

后续步骤

有关 Azure PowerShell 模块的详细信息,请参阅 Azure PowerShell 文档

可以在 PowerShell 示例中找到 Azure API 管理的其他 Azure Powershell 示例。