没有ADAL的Azure AD访问令牌

时间:2016-06-11 15:49:35

标签: azure azure-ad-graph-api azure-ad-b2c

我正在尝试在服务器端编辑用户的AD配置文件,这需要访问令牌。我可以使用仅使用客户端ID和密码的本机应用程序示例来执行此操作。 The docs提到仅使用http请求就可以实现这一点(请参阅获取访问令牌),但我找不到任何示例或方法来执行此操作。

2 个答案:

答案 0 :(得分:3)

您可以使用OAuth2来请求访问令牌。以下是有关如何在Azure AD中使用OAuth2的示例。它是用PowerShell脚本编写的。

$tenantID = "<the Tenant ID of your Azure AD>"
$loginEndpoint = "https://login.windows.net/"
$graphResourceURI = "https://graph.windows.net/"
$clientId = "<the client id of your AD application>"
$key = "<the client secret of your AD application>"

# the URL for requesting access token.
$tokenURL = $loginEndpoint+$tenantID+"/oauth2/token"

# the token request body.
$body = "grant_type=client_credentials&client_id="+$clientId `
         +"&client_secret="+[system.uri]::EscapeDataString($key) `
         +"&resource="+[system.uri]::EscapeDataString($graphResourceURI)

# the token request headers.
$headers = @{"Content-Type"="application/x-www-form-urlencoded"}

$authenticationResult = Invoke-RestMethod -Method POST `
                         -Uri $tokenURL -Headers $headers -Body $body

$authenticationResult.access_token

您在此处使用的AD应用程序必须是“Web应用程序和/或Web API”,因为Native AD应用程序没有客户端密钥。

答案 1 :(得分:-5)

我使用杰克的答案让这个工作,但有一些变化。以下是完整的工作示例:

$tenantID = "<the name of your tenant of your Azure AD>"
$loginEndpoint = "https://login.windows.net/"
$graphResourceURI = "https://graph.windows.net/"

$clientId = "<the client id of your AD application>"
$key = "<the client secret of your AD application>"

# the URL for requesting access token.
$tokenURL = $loginEndpoint+$tenantID+"/oauth2/token"

# the token request body.
$body = "grant_type=client_credentials&client_id="+$clientId `
         +"&client_secret="+[system.uri]::EscapeDataString($key) `         
         +"&resource="+[system.uri]::EscapeDataString($graphResourceURI)

# the token request headers.
$headers = @{"Content-Type"="application/x-www-form-urlencoded"}

$authenticationResult = Invoke-RestMethod -Method POST `
                         -Uri $tokenURL -Headers $headers -Body $body

$authenticationResult.access_token
相关问题