azure - C# - 获取图形访问 token - 使用客户端 ID、客户端 key 、范围和客户端委托(delegate)权限

标签 azure oauth-2.0 microsoft-graph-api bearer-token clientcredential

我在我的 AAD 应用客户端 ID 上获得了图形委托(delegate)权限

现在,我想在后端使用应用程序客户端 ID、应用程序客户端 key 和图形范围请求图形调用的访问 token 未经用户同意

我已经尝试了以下方法,但收到错误请求,任何人都可以指导我以正确的方式解决我做错的事情吗?

string graphAccessUrl = "https://login.microsoftonline.com/tenant.onmicrosoft.com/oauth2/v2.0/token";
    
_httpClient.DefaultRequestHeaders.Accept.Clear();
_httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));
List<KeyValuePair<string, string>> values = new()
{
    new KeyValuePair<string, string>("grant_type", "client_credentials"),
    new KeyValuePair<string, string>("client_id", appClientId),
    new KeyValuePair<string, string>("client_secret", appClientSecret),
    new KeyValuePair<string, string>("scope", scope) //graph scope
};
HttpContent c = new FormUrlEncodedContent(values);
//GET Method  
try
{
    HttpResponseMessage response = _httpClient.PostAsync(new Uri(graphAccessUrl), c).Result;
    if (response.IsSuccessStatusCode)
    {
        string responseString = response.Content.ReadAsStringAsync().Result;
        TokenData reponseObj = JsonConvert.DeserializeObject<TokenData>(responseString);
        string accessToken = reponseObj.access_token;                            
        return accessToken;
    }
    else
    {                            
        throw new ArgumentException("Failed to get authtoken due response code." + response.StatusCode);
    }
}
catch (Exception ex)
{
    throw new ArgumentException(ex.Message);
}

最佳答案

除非您的场景与我的稍有不同,否则通常的方法是将当前用户的访问 token 交换为图形访问 token ,如 my code sample 所示。 。我的代码位于 Node.js 中,但您可以轻松地将其转换为 C#。

    *
    * Use the Azure specific 'on behalf of' flow to get a token with permissions to call the user info endpoint
    */
    private async _getGraphAccessToken(accessToken: string): Promise<string> {

        try {

            const formData = new URLSearchParams();
            formData.append('grant_type', 'urn:ietf:params:oauth:grant-type:jwt-bearer');
            formData.append('client_id', this._configuration.graphClient.clientId);
            formData.append('client_secret', this._configuration.graphClient.clientSecret);
            formData.append('assertion', accessToken);
            formData.append('scope', 'openid profile email');
            formData.append('requested_token_use', 'on_behalf_of');

            const options = {
                url: this._configuration.tokenEndpoint,
                method: 'POST',
                data: formData,
                headers: {
                    'content-type': 'application/x-www-form-urlencoded',
                    'accept': 'application/json',
                },
            };

            const response = await axios.request(options as AxiosRequestConfig) as any;
            return response.data.access_token!;

        } catch (e) {

            // Report Graph errors clearly
            throw ErrorFactory.fromUserInfoTokenGrantError(e, this._configuration.tokenEndpoint);
        }
    }

在 OAuth 术语中,这是一个用户断言,用于将传入的访问 token 交换为同一用户的另一个访问 token 。有关设置的更多说明,请参阅 this blog post .

关于azure - C# - 获取图形访问 token - 使用客户端 ID、客户端 key 、范围和客户端委托(delegate)权限,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71688655/

相关文章:

java - 无法观察发送到 Azure 时间序列洞察资源管理器的事件

java - 在具有 Java REST 后端的 iPhone 应用程序中使用第 3 方 oauth2 服务

c# - 如何使用 MSAL 在控制台应用程序中代表用户获取访问 token 以调用 MS Graph?

azure - 返回 400 "Resource not found for the segment ' 联系人的组的图表 Delta API。”

azure-active-directory - 如何使用/adminconsent端点为一组用户而不是整个组织授予权限?

c# - 在VS2017中使用azure函数,无法绑定(bind)到ServiceBus队列作为输出

Azure cli - 列出禁用 https-only 的所有 Web 应用程序

python - Azure Web作业 : Force stop if running longer than X mins

spring-boot - 如何像 RestTemplate 一样从 WebClient 获取 accesstoken?

canvas - 使用 php-sdk 和 oauth 授权和验证 Canvas 应用程序用户