C#-获取图形访问令牌-使用客户端ID、客户端机密、具有客户端委派权限的作用域



我的AAD应用程序客户端ID上有graph delegated permissions

现在,我想在后端without user consent中使用app Client ID, app Client Secret and Graph Scope为图调用请求访问令牌。

我尝试了以下方法,但获得了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);
}

除非您的场景与我的场景有点不同,否则通常的方法是将当前用户的访问令牌交换为Graph访问令牌,如我的代码示例所示。我的代码在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术语中,这是一种用户断言,用于将传入的访问令牌交换为同一用户的另一个访问令牌。在这篇博客文章中还有一些关于设置的进一步说明。

相关内容

  • 没有找到相关文章

最新更新