.Net Core Graph API 令牌问题 - "Access token has expired or is not yet valid"
.Net Core Graph API Token Issue - "Access token has expired or is not yet valid"
我正在开发 .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
访问令牌的生命周期很短,有时只有一个小时甚至更短。因此,当当前访问令牌即将过期时,您需要使用刷新令牌向 AzureAd 请求新的访问令牌。
看到这个linkhttps://docs.microsoft.com/en-us/azure/active-directory/develop/refresh-tokens
我正在开发 .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
访问令牌的生命周期很短,有时只有一个小时甚至更短。因此,当当前访问令牌即将过期时,您需要使用刷新令牌向 AzureAd 请求新的访问令牌。
看到这个linkhttps://docs.microsoft.com/en-us/azure/active-directory/develop/refresh-tokens