如何使用Azure CLI (az ad app)创建作用域

9
使用 Azure CLI 2.x,我无法找到在 Azure AD 门户中“公开 API”部分下“添加作用域”的方法。

enter image description here

我看到的是,如果在创建应用程序时传递 --identifier-uris 参数,则会自动设置 APP ID URI 和作用域。
    `az ad app create --display-name "$appName" --identifier-uris "https://$tenantDomain/$appName" --reply-urls "$replyUrl" --oauth2-allow-implicit-flow true`

enter image description here

不是我期望的,也不是我想要的

因此,我从创建命令中删除了--identifier-urls,并手动添加了我想要的范围。然后,我可以通过清单在OAuth2Permissions下看到我想要的内容,如下所示。我能否使用新的guid将其放入manifest.json并进行插入?

enter image description here

有哪些CLI命令支持明确支持定义作用域? 然后添加客户端应用程序时,我需要选择定义的范围,这如何引用?

文档非常稀少,我认为。此参考非常有帮助,但其中没有任何关于添加范围和客户端的信息。https://learn.microsoft.com/en-us/cli/azure/ad?view=azure-cli-latest。非常感谢提供示例或文档的任何帮助。

5个回答

10
截至2022年7月29日,最新的Azure CLI命令“az ad app update”不再包括oauth2permissions。如果您尝试上述操作,您将会碰壁,希望能找到这篇文章。这些权限的新位置位于api.oauth2PermissionScopes中作为一个数组。
为了解决这个问题,我结合了这篇文章中的一些内容,并且必须要有创意,因为 Azure文档也是错误的。
仍然适用的是,如果您已经公开了现有的API,则必须禁用它才能修改作用域。如果您有一个全新的应用程序注册,您可以直接申请而没有问题。希望这能帮助像我一样的人,他们的自动化由于应用程序注册和清单更改的变化而现在已经失效了。如果您不知道应用程序注册的变化,请查看。如果您已经走到了这一步,我就假定您已经这样做了。
# Add API Read Scope: 
$scopeGUID = [guid]::NewGuid()
$scopeJSONHash = @{
    adminConsentDescription="$apiName on $svrAppRegName"
    adminConsentDisplayName="$apiName on $svrAppRegName" 
    id="$scopeGUID"
    isEnabled=$true
    type="User"
    userConsentDescription="$apiName on $svrAppRegName"
    userConsentDisplayName="$apiName on $svrAppRegName"
    value="$apiName"
}
$azAppOID = (az ad app show --id $serverApplicationId | ConvertFrom-JSON).id
$accesstoken = (Get-AzAccessToken -Resource "https://graph.microsoft.com/").Token
$header = @{
    'Content-Type' = 'application/json'
    'Authorization' = 'Bearer ' + $accesstoken
}
$bodyAPIAccess = @{
    'api' = @{
        'oauth2PermissionScopes' = @($scopeJSONHash)
    }
}|ConvertTo-Json -d 3

#You can try az rest, I used Invoke-RestMethod though.
#$graphURL="https://graph.microsoft.com/v1.0/applications/$azAppOID" 
#az rest --method PATCH --uri $graphurl --headers $header --body $bodyAPIAccess

Invoke-RestMethod -Method Patch -Uri "https://graph.microsoft.com/v1.0/applications/$azAppOID" -Headers $header -Body $bodyAPIAccess

这现在是正确的答案!谢谢 - 帮了很多忙。对于其他人发现这个问题 - 请注意在“oauth2PermissionScopes”中使用单数的“Permission”(而不是旧的复数“oauth2permissions”)。我也被这个问题卡住了。 - Joel Nation
我觉得微软不把自己的API文档化是完全疯狂的。 - undefined

5

正如A2AdminGuy所提到的,现在不能直接更新oauth2Permissions,但你仍然可以使用az ad app update

  1. 执行命令az ad app show --id $appClientId,你会发现oauth2PermissionScopes现在在api中:
"api": {
    "acceptMappedClaims": null,
    "knownClientApplications": [],
    "oauth2PermissionScopes": [],
    "preAuthorizedApplications": [],
    "requestedAccessTokenVersion": null
}

你需要更新api属性以便设置oauth2PermissionScopes:
$apiScopeId = [guid]::NewGuid().Guid
$apiScopeJson = @{
    requestedAccessTokenVersion = 2
    oauth2PermissionScopes      = @(
        @{
            adminConsentDescription = "$AppName on $EnvironmentAbbrev"
            adminConsentDisplayName = "$AppName on $EnvironmentAbbrev"
            id                      = "$apiScopeId"
            isEnabled               = $true
            type                    = "User"
            userConsentDescription  = "$AppName on $EnvironmentAbbrev"
            userConsentDisplayName  = "$AppName on $EnvironmentAbbrev"
            value                   = "authenticate"
        }
    )
} | ConvertTo-Json -d 4 -Compress

$apiUpdateBody = $apiScopeJson | ConvertTo-Json -d 4

az ad app update --id $apiClientId --set api=$apiUpdateBody --verbose
--verbose参数可以删除,但有趣的是,更新命令是对图形API的路径请求。
由于它是一条路径请求,您不必总是发送整个api属性,您可以进行两个请求以更新不同的属性,之前的请求将不受影响。
以下是如何更新SPA的redirectUris
$appSpaJson = @{
    redirectUris = @("http://localhost:3000")
} | ConvertTo-Json -d 3 -Compress
    
$appUpdateBody = $appSpaJson | ConvertTo-Json -d 4

az ad app update --id $appClientId --set spa=$appUpdateBody

你的意思是向API发送Patch请求吗? - Rob Bowman
你是指向API发送Patch请求吗? - undefined

5

本文翻译自Azure CLI: 创建公开OAuth2权限的API的Azure AD应用程序

您可以使用az ad app update命令(请参阅文档)

然后,您可以通过使用可选参数--set来设置应用程序的属性

  1. Create a oauth2-permissions.json containing the permission:

    [
      {
        "adminConsentDescription": "Access CP Debug Desc",
        "adminConsentDisplayName": "Access CP Debug",
        "id": "85b8f1a0-0733-47dd-9af4-cb7221dbcb73",
        "isEnabled": true,
        "type": "Admin",
        "userConsentDescription": null,
        "userConsentDisplayName": null,
        "value": "Access"
      }
    ]
    
  2. Run this script, it will create the app, disable the existing scope and add the new scope:

    # Create the app registration
    APP_REG=$(az ad app create --display-name myapi --identifier-uris https://myapi)
    
    # Get the app id
    APP_ID=$(echo $APP_REG | jq -r '.appId')
    
    # disable default exposed scope
    DEFAULT_SCOPE=$(az ad app show --id $APP_ID | jq '.oauth2Permissions[0].isEnabled = false' | jq -r '.oauth2Permissions')
    az ad app update --id $APP_ID --set oauth2Permissions="$DEFAULT_SCOPE"
    
    # Create new scopes from file 'oath2-permissions'
    az ad app update --id $APP_ID --set oauth2Permissions=@oauth2-permissions.json
    

嗨,这看起来很有前途。然而,这行代码$ DEFAULT_SCOPE = $(az ad app show --id $ appId | jq'.oauth2Permissions [0] .isEnabled = false' | jq -r'.oauth2Permissions')会失败,并显示以下信息: jq:未识别术语“jq”作为cmdlet、函数、脚本文件或...的名称。我将看看是否有其他方法。 - user2503078
你是在运行Windows还是Linux?jq是Bash/Shell的JSON查询包 https://stedolan.github.io/jq/ - Thomas
如果你使用 PowerShell 中的 ConvertTo-JsonConvertFrom-Json,那就可以实现这个功能了吧? - Thomas
如果我知道要更改什么,那么我只需在OAuthPermissions中将IsEnabled设置为false,然后将整个JSON传回set中吗?我可以使用以下命令来隔离JSON块:az ad app list --display-name $appName --query [].oauth2Permissions[0] - user2503078
是的,这是在创建新范围之前禁用默认范围。 - Thomas
显示剩余2条评论

3

这是我在WSL Ubuntu上使用bash所采用的方法,希望对其他人有用:

# replace all <value> blocks with your own value

# create app registration and extract appId
clientid=$(az ad app create \
    --display-name <name> \
    --query appId \
    --output tsv)

# generate a UUID for the scope
uuid=$(uuidgen)

# set the API object as a JSON object
api=$(echo '{
    "acceptMappedClaims": null,
    "knownClientApplications": [],
    "oauth2PermissionScopes": [{
        "adminConsentDescription": "<description>",
        "adminConsentDisplayName": "<name>",
        "id": "'$uuid'",
        "isEnabled": true,
        "type": "User",
        "userConsentDescription": "<description>",
        "userConsentDisplayName": "<name>",
        "value": "<value>"
    }],
    "preAuthorizedApplications": [],
    "requestedAccessTokenVersion": 2
}' | jq .)

# Update app registration with App ID URL and api object
az ad app update \
    --id $clientid \
    --identifier-uris api://$clientid \
    --set api="$api"

2
这很有帮助,但值得注意的是,api属性的内容必须包括所有所需内容。因此,如果针对已经具有权限范围的现有应用程序注册运行,则如果没有首先禁用这些范围,将会引发错误。 - Rob Bowman
@RobBowman 很好知道,谢谢你提醒。我一直在纯粹使用它来生成新的应用程序注册。 - Jaime Still
这对我帮助很大,我一直在尝试执行 az ad app update --set oauth2Permissions="stuff" 而不是 az ad app update --set api="a bit more stuff" - undefined

2

在参考上面的帖子并进行大量试错和使用非常有用的链接的帮助下,我成功地编写出了CLI脚本以在Windows环境下添加范围。由于PowerShell在Windows上不支持'jq',因此必须删除反引号才能使其正常工作。现在,我需要解决使用CLI添加预授权应用程序的问题。

$userAccessScopeApi = '{
    "lang": null,
    "origin": "Application",        
    "adminConsentDescription": "Access CP Debug desc",
    "adminConsentDisplayName": "Access CP Debug",
    "id": "--- replaced in scripts ---",
    "isEnabled": true,
    "type": "Admin",
    "userConsentDescription": null,
    "userConsentDisplayName": null,
    "value": "Access"
}' | ConvertTo-Json | ConvertFrom-Json
`

Write-Host " -  1 read oauth2permissions"
#(az ad app show  --id $appid)
$appjson = (az ad app list --display-name $appName)         
$app = $appjson | ConvertFrom-Json
$oauth2Permissions = $app.oauth2Permissions
$oauth2Permissions[0].isEnabled = 'false'

$oauth2Permissionsjson = ConvertTo-Json -InputObject @($oauth2Permissions) 

Write-Host " -  2 disable oauth2Permission in Azure App Registration"
$oauth2Permissionsjson | Out-File -FilePath .\oauth2Permissionsold.json
az ad app update --id $appId --set oauth2Permissions=@oauth2Permissionsold.json

Write-Host " -  3 delete the default oauth2Permission"
az ad app update --id $appId --set oauth2Permissions='[]'

Write-Host " -  4 add the new scope required add the new oauth2Permissions values"
$oauth2PermissionsApiNew = $userAccessScopeApi | ConvertFrom-Json
$oauth2PermissionsApiNew[0].id = New-Guid
$oauth2PermissionsApiNew = ConvertTo-Json -InputObject @($oauth2PermissionsApiNew) 

# Write-Host "new oauth2permissions : " + $oauth2PermissionsApiNew" 
$oauth2PermissionsApiNew | Out-File -FilePath .\oauth2Permissionsnew.json
az ad app update --id $appId --set oauth2Permissions=@oauth2Permissionsnew.json

Write-Host " - Updated scopes (oauth2Permissions) for App Registration: $appId"`

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接