[英]How to Authorize user on WebApi if user is authenicated in the application
[英]How can I authorize REST API for an application rather than for a user?
我有一个移动应用程序,需要调用 REST API。这是我的代码:
string url = $@"https://graph.microsoft.com/v1.0/solutions/bookingBusinesses/{adTenantId}/appointments";
string accessToken = new JwtSecurityTokenHandler().WriteToken(AuthService.JwtToken);
HttpClient client = new();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
HttpResponseMessage response = await client.GetAsync(url).ConfigureAwait(false);
这给了我错误 401(未经授权)。 我可能是错的,但在我看来,这是因为我使用基于用户身份验证的访问令牌。 我可能需要调用 API 不是作为用户,而是作为我的应用程序。 购买 我不知道如何获取该应用程序的访问令牌。 该应用程序已注册 Azure AD 并具有必要的 API 权限。
假设您已经正确设置了 MS Graph API 的应用程序,并且您有以下配置:
var app = ConfidentialClientApplicationBuilder.Create(ClientId)
.WithClientSecret(ClientSecret)
.WithAuthority(new Uri("https://login.microsoftonline.com/" + Tenant))
.Build();
string[] scopes = new string[] { "https://graph.microsoft.com/.default" };
var result = await app.AcquireTokenForClient(scopes).ExecuteAsync();
var accessToken = result.AccessToken;
请注意,我使用 scope https://graph.microsoft.com/.default
作为您分配给应用程序的所有权限。 您可以使用更具体的范围。
参考资料。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.