asp.net-core - 重新启动应用程序时,ASP.NET Core 3.1 Microsoft Graph 访问令牌丢失
问题描述
使用ASP.NET Core 3.1
and Microsoft Graph API
,当应用程序重新启动时Access Token
会丢失。用户仍处于登录状态,但无法执行任何Graph API
呼叫。
我已经尝试过这里提到的建议管理增量同意和条件访问,但无法刷新令牌并自动恢复。
这是我的控制器:
readonly ITokenAcquisition tokenAcquisition;
private GraphServiceClient graphServiceClient;
public HomeController(GraphServiceClient graphServiceClient, ITokenAcquisition tokenAcquisition)
{
this.graphServiceClient = graphServiceClient;
this.tokenAcquisition = tokenAcquisition;
}
[HttpGet]
[AuthorizeForScopes(Scopes = new string[] {"user.read"})]
public async Task<IActionResult> A()
{
User user;
try
{
var scopes = new string[] { "user.read" };
var accessToken = await tokenAcquisition.GetAccessTokenForUserAsync(scopes);
user = await graphServiceClient.Me.Request().GetAsync();
}
catch (MicrosoftIdentityWebChallengeUserException ex)
{
// token is invalid....
// the throw causes a redirect to the User Login Page
throw ex.MsalUiRequiredException;
}
user = await graphServiceClient.Me.Request().GetAsync();
Serilog.Log.Debug("{@User}", user);
return View();
}
在上面的代码中,当应用程序重新启动时,访问令牌会丢失,重新抛出异常会导致重定向到登录页面。
如果我然后单击该Sign-in with Microsoft
按钮,则用户已经登录,无需输入凭据。如果我随后访问调用 的控制器Graph API
,则 API 调用成功。
如何在调用 API 之前刷新令牌?
另外我该如何调试呢?如果我在它没有用处设置断点throw ex.MsalUiRequiredException;
,我看不到重定向从哪里获取它的值。
解决方案
Annotation[AuthorizeForScopes(Scopes = new string[] {"user.read"})]
负责处理重定向。
对于调试,请使用AuthorizeForScopes
源文件。
在这种特定情况下,AuthenticationScheme
未将其设置为值,并且为空。
注释 Action 方法以强制执行特定的方案。例如AuthenticationScheme=OpenIdConnectDefaults.AuthenticationScheme
[HttpGet]
[AuthorizeForScopes(Scopes = new string[] {"user.read"}, AuthenticationScheme=OpenIdConnectDefaults.AuthenticationScheme)]
public async Task<IActionResult> A()
{
// snipped
}
这导致了所需的重定向路径:
https://login.microsoftonline.com/{}/oauth2/v2.0/authorize?client_id={}
推荐阅读
- ios - 同时播放视频和录制 react-native(iOS)
- rust - 我可以在 Rust 中创建一个包含字符串和该字符串切片的结构吗?
- postgresql - 具有子查询多行的 Postgres CASE
- java - 快速排序java实现
- vba -
计时器 api 运行时形状超链接不起作用(powerpoint vba) - python - 搜索列表字典的Pythonic方式?
- kubernetes - Kubernetes:没有定义端口的服务
- .net - 为什么两个文字度°符号在 Windows 下的单元测试中比较相等,但在 Linux 下却不相等?
- hex - 如何使用 COBOL 中的不同输入从 Hex 转换为 Ascii
- image - 单击onclass react-native后的随机图像