我正在開發一個.Net 6應用程式,托管在一個Azure App Service并使用Azure AD Authentication.
查看請求頁面時,我想檢查用戶是否屬于Azure Ad Group. 這有時有效,但用戶在嘗試查看頁面時會定期收到錯誤訊息:“訪問令牌已過期或尚未生效。”
我假設令牌已過期,就好像用戶清除了他們的 cookie,AAD 將重新對他們進行身份驗證,創建一個新令牌,一切都很好,但我無法在重繪 令牌周圍找到任何東西,我不確定在哪里從這里出發。
有沒有人經歷過這種行為并找到了解決方案?
以下是代碼的一些相關部分
Startup.cs 檔案:
string[] initialScopes = Configuration.GetValue<string>("GraphAPI:Scopes")?.Split(' ');
services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApp(Configuration.GetSection("AzureAd"))
.EnableTokenAcquisitionToCallDownstreamApi(options =>
{
Configuration.Bind("AzureAd", options);
}, initialScopes)
.AddInMemoryTokenCaches()
.AddMicrosoftGraph(options =>
{
options.Scopes = String.Join(' ', initialScopes);
});
AADGroupFunctions.cs
AADGroupFunctions.cs
private readonly GraphServiceClient _graphServiceClient;
public AADGroupFunctions(GraphServiceClient graphServiceClient)
{
_graphServiceClient = graphServiceClient;
}
public async Task<List<IADLookupModel>> FindUsersInGroup(string groupId)
{
var listOfUsers = new List<IADLookupModel>();
var filterString = $"startswith(mail, '{groupId}')";
var groups = await _graphServiceClient.Groups
.Request()
.Header("ConsistencyLevel", "eventual")
.Filter(filterString)
.Expand("members")
.Top(1)
.GetAsync();
if (groups.Any())
{
if (groups.First().Members.Any())
{
foreach (Microsoft.Graph.User user in groups.First().Members)
{
try
{
var mail = "";
if (user.Mail != null)
{
mail = user.Mail.ToLower();
listOfUsers.Add(new UserModel()
{
DisplayName = user.DisplayName,
UPN = user.UserPrincipalName.ToLower(),
Email = mail,
Description = user.JobTitle ?? ""
});
}
}
catch (Exception)
{
}
}
}
}
return listOfUsers;
}
嘗試呼叫該FindUsersInGroup()函式時的錯誤訊息:
An unhandled exception occurred while processing the request.
ServiceException: Code: InvalidAuthenticationToken Message: Access token has expired or is not yet valid. Inner error: AdditionalData: date: 2022-02-21T17:37:46 request-id: [removed] client-request-id: [removed] ClientRequestld: [removed] Microsoft.Graph.HttpProvider.SendAsync(HttpRequestMessage request, HttpCompletionOption completionOption, CancellationToken cancellationToken)
Routing
uj5u.com熱心網友回復:
訪問令牌的生命周期很短,有時像一個小時甚至更短。因此,當當前訪問令牌即將到期時,您需要使用重繪 令牌向 AzureAd 請求新的訪問令牌。
看到這個鏈接https://docs.microsoft.com/en-us/azure/active-directory/develop/refresh-tokens
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/431513.html
標籤:asp.net-mvc 微软图形 API 令牌 开放式连接
上一篇:ASP.NET按鈕單擊事件
下一篇:從Json問題中提取詳細資訊
