You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET Core 7 MVC项目Microsoft认证失效,GetExternalLoginInfoAsync返回null

问题:Microsoft外部登录后GetExternalLoginInfoAsync()返回null,.NET 6升级至.NET 7后仍未解决

问题背景

团队开发的社交平台仅支持用户通过校园邮箱,借助Microsoft API完成登录与注册操作。注册页面中,用户填写资料点击「注册」时触发以下代码:

public async Task<IActionResult> OnPostConfirmationAsync(string returnUrl = null)
{
    returnUrl = returnUrl ?? Url.Content("~/");
    // Get the information about the user from the external login provider
    var info = await _signInManager.GetExternalLoginInfoAsync();
    
    if (info == null)
    {
        ErrorMessage = "Error loading external login information during confirmation.";
        return RedirectToPage("./Login", new { ReturnUrl = returnUrl });
    }

    if (ModelState.IsValid)
    {
        var user = CreateUser();

        string userName = TruncateEmail(Input.Email);

        ...
    }
}

此前var info = await _signInManager.GetExternalLoginInfoAsync()运行正常,但近期该方法突然返回null,导致注册系统无法工作。已尝试将项目从.NET 6升级至.NET 7,并更新所有Microsoft相关NuGet包,问题仍未解决。

排查与解决方案

1. 检查外部登录会话完整性

GetExternalLoginInfoAsync()依赖登录流程中存储的会话数据,需确认:

  • 登录回调方法(如OnGetCallbackAsync)是否正确调用_signInManager.GetExternalLoginInfoAsync(),且未提前清除会话数据
  • 注册页面的请求是否保持同一会话(无跨域跳转、未丢失身份验证Cookie)

2. 验证Microsoft OAuth应用配置

检查Azure AD应用注册的关键配置:

  • 重定向URI是否包含注册页面的回调地址,且与项目appsettings.json中Authentication:Microsoft:RedirectUri完全一致
  • 应用是否已添加openid、profile、email等必要权限,且已获得管理员同意
  • 近期是否修改过应用的客户端密钥、租户ID,导致项目配置与Azure端不匹配

3. 确认身份验证中间件配置

检查Program.cs(或Startup.cs)中的中间件配置:

  • 已正确添加Microsoft身份验证服务:
    builder.Services.AddAuthentication()
        .AddMicrosoftAccount(options =>
        {
            options.ClientId = builder.Configuration["Authentication:Microsoft:ClientId"];
            options.ClientSecret = builder.Configuration["Authentication:Microsoft:ClientSecret"];
        });
    
  • 中间件顺序是否正确:app.UseAuthentication()必须在app.UseAuthorization()之前,且位于app.UseRouting()之后

4. 排查会话存储问题

若使用分布式会话(如Redis),需确认:

  • 会话服务配置正常,无连接失败或数据丢失情况
  • 会话超时时间设置合理,未导致外部登录完成后会话已过期

5. 调试外部登录流程

在登录回调方法中添加日志输出,确认:

  • 登录成功后是否正确获取到外部登录信息
  • 是否在回调后执行_signInManager.ExternalLoginSignInAsync()或_signInManager.UpdateExternalAuthenticationTokensAsync(),完成会话数据的持久化

内容的提问来源于stack exchange,提问作者unitydevsz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 18:34:54