gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 07:04:11 26 4
gpt4 key购买 nike

我在我的 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com