简体   繁体   English

C# - 获取图形访问令牌 - 使用客户端 ID、客户端密码、Scope 和客户端委派权限

[英]C# - Get Graph access token - using Client ID, Client Secret, Scope with Client Delegated Permissions

I have got the graph delegated permissions on my AAD app Client ID.我在我的 AAD 应用程序客户端 ID 上获得了graph delegated permissions

Now, I want to request access token for the graph calls using app Client ID, app Client Secret and Graph Scope in the backend without user consent .现在,我想在without user consent的情况下在后端使用app Client ID, app Client Secret and Graph Scope请求图形调用的访问令牌。

I have tried the below approach but getting a Bad Request , can anyone guide me in the right way of what I'm doing wrong?我已经尝试了以下方法但收到了Bad Request ,任何人都可以以正确的方式指导我做错什么吗?

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);
}

Unless your scenario is a little different to mine, the usual approach is to exchange the current user's access token for a Graph access token, as in my code sample .除非您的场景与我的略有不同,否则通常的方法是将当前用户的访问令牌交换为 Graph 访问令牌,如我的代码示例中所示 My code is in Node.js but you'll be able to translate it to C# easily enough.我的代码在 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);
        }
    }

In OAuth terms this is a user assertion, to swap an incoming access token for another access token for the same user.在 OAuth 术语中,这是一个用户断言,用于将传入访问令牌交换为同一用户的另一个访问令牌。 Some further notes on setup in this blog post . 这篇博文中关于设置的一些进一步说明。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在应用程序中使用之前验证客户端 ID 和客户端密码 - Verify Client ID and Client Secret before using it in Application 您能否通过 web 请求使用用户名和密码而不使用 client_id 获得 Azure 的访问令牌? - Can you get an access token for Azure with a username and password and without using a client_id via web request? 从 Angular 获取没有客户端密码的 Azure AD 访问令牌,Power BI 的用户名/密码 - Get Azure AD access token without client secret, username/password for Power BI from Angular 使用 JMeter 从 Hashicorp 保管库中检索客户端密钥 ID - Retrieve client secret id from Hashicorp vault using JMeter 如何在没有企业应用程序客户端密钥的情况下刷新 Microsoft Graph API 的令牌? - How to refresh the token of Microsoft Graph API without Client Secret for an Enterprise App? 如何获取委托权限的令牌(Microsoft Graph) - How to acquire token for delegated permissions (microsoft graph) 我们可以使用 Application Client ID + Client Secret 而不是 Tokens - Can we use Application Client ID + Client Secret instead of Tokens 如何从客户端获取登录用户的 access_token? 使用Azure AD B2C混合流 - How to get access_token from client side for signed in user? using Azure AD B2C hybrid flow 使用客户端密码访问 Dynamics Business Central - Access to Dynamics Business Central with Client Secret AAD B2C - 使用 ConfidentialClientApplicationBuilder 和客户端机密获取令牌时的主题(子)是什么? - AAD B2C - What is the subject (sub) when getting a token with ConfidentialClientApplicationBuilder and a client secret?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM