1
我想通過微軟圖拉取經過身份驗證的azure活動目錄用戶的辦公室位置,但不斷收到403 Forbidden響應。當從一個dotnet核心應用程序訪問Microsoft Graph時禁止403
我能夠進行身份驗證,我可以生成一個訪問令牌,但HTTP響應狀態代碼始終是403
下面是一些代碼,我一直在使用,但我有一種感覺,可能是由於配置或權限,請讓我知道你需要什麼額外的信息。
public class AccountService : IAccountService
{
private readonly AzureAd _adSettings;
public AccountService(IOptions<AzureAd> adSettings)
{
_adSettings = adSettings.Value;
}
public async Task<string> GetStoreIdFromUser(string userId)
{
var storeId = string.Empty;
string accessToken = await GetBearerAccesToken();
using (var client = new HttpClient())
{
using (var request = new HttpRequestMessage(HttpMethod.Get, GetUserUrl(userId)))
{
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
using (var response = await client.SendAsync(request))
{
if (response.StatusCode == HttpStatusCode.OK)
{
var json = JObject.Parse(await response.Content.ReadAsStringAsync());
storeId = json?["physicalDeliveryOfficeName"]?.ToString();
}
}
}
}
return storeId;
}
#region private methods
private string GetUserUrl(string userPrincipalName)
{
return string.Format("https://graph.windows.net/{0}/users/{1}?{2}", _adSettings.TenantId, userPrincipalName, "api-version=1.6");
}
private async Task<string> GetBearerAccesToken()
{
string result = string.Empty;
// Get OAuth token using client credentials
string authString = "https://login.microsoftonline.com/" + _adSettings.TenantId;
AuthenticationContext authenticationContext = new AuthenticationContext(authString, false);
// Config for OAuth client credentials
ClientCredential clientCred = new ClientCredential(_adSettings.ClientId, _adSettings.AppKey);
string resource = "https://graph.windows.net";
AuthenticationResult authenticationResult = await authenticationContext.AcquireTokenAsync(resource, clientCred);
result = authenticationResult.AccessToken;
return result;
}
#endregion
}
你試圖訪問微軟圖表或Azure的AD圖? –
應該是Microsoft Graph。我在我的AD應用程序註冊中添加了該權限。 –
403意思是「我知道你是誰,但你不能訪問這個東西。」在https://jwt.io檢查令牌,並查看受衆羣體聲明(aud)是Microsoft Graph資源URI('https:// graph.microsoft.com'),並且必需的角色位於令牌中。 – juunas