【问题标题】:Call azure ad-protected API from powershell with username/password使用用户名/密码从 powershell 调用受广告保护的 Azure API
【发布时间】:2019-06-18 08:56:20
【问题描述】:

我有一个受 Azure AD 保护的 Web api。 我的 javascript 发送一个回调 url,用户访问令牌被发送到

https://login.microsoftonline.com/{my_tenant}/oauth2/v2.0/token/?redirect_uri={my_url}&...

现在我想使用 powershell 访问我的 api,因此我只想将令牌作为响应。我用下面的代码试过这个resource owner password credential-flow,但它只是说用户名或密码不正确......(我使用相同的手动登录)

   $creds =  @{
        client_id = $clientId
        username = $username
        password = $password
        grant_type = "password"
        scope="User.Read" 
    }

$headers = @{        
    "Content-Type"="application/x-www-form-urlencoded"
}
Invoke-RestMethod $authUrl -Method Post -Body $creds -Headers $headers;  

所以,简而言之,我想通过powershell使用用户名和密码登录,可以吗?

【问题讨论】:

    标签: azure powershell asp.net-web-api azure-active-directory


    【解决方案1】:

    我无法重现您的问题,请仔细检查您的用户名和密码。

    或者你可以试试我的工作示例,如果你想从你自己的api中获取toekn,scope应该是{Application ID URI or Application ID}/User.Read,如果你使用scope="User.Read",它默认代表MS Graph API。

    示例

     $authUrl = "https://login.microsoftonline.com/{tenant-id}/oauth2/v2.0/token/"
    
     $clientId = "xxxxxxxxxxxxxxxxxxx"
     $username = "xxxxxx@xxx.onmicrosoft.com"
     $password = "xxxxxx"
    
       $creds =  @{
            client_id = $clientId
            username = $username
            password = $password
            grant_type = "password"
            scope="{Application ID URI or Application ID}/User.Read" 
        }
    
    $headers = @{        
        "Content-Type"="application/x-www-form-urlencoded"
    }
    Invoke-RestMethod $authUrl -Method Post -Body $creds -Headers $headers
    

    更新:

    在使用资源所有者密码凭证流程时,请注意以下重要事项。

    【讨论】:

    • 感谢您的回复。我仍然得到无效的用户名或密码。我用两个不同的帐户进行了测试,其中一个现在已被锁定,所以在我解锁之前我无法进行更多测试。之后我会回来并尝试更多
    • @Cowborg 您的用户帐户是否启用了 MFA?如果用户需要使用多重身份验证 (MFA) 来登录应用程序,他们将被阻止。
    • @Cowborg 看看我回复中的更新,使用这个流程有一些重要的事情。
    • 谢谢!我不明白项目符号2。那可以使用哪些帐户?
    • @Cowborg 可能是工作帐户/学校帐户。您可以在门户中导航到 Azure AD -> 用户 -> 新用户,创建一个新用户进行测试。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-17
    • 1970-01-01
    • 2020-02-19
    • 2022-08-05
    • 2017-11-02
    • 1970-01-01
    相关资源
    最近更新 更多