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

ASP.NET Core 2.0中GetExternalLoginInfoAsync返回null,GitHub OAuth连接问题

解决ASP.NET Core 2.0对接GitHub OAuth时GetExternalLoginInfoAsync返回null的问题

嘿,我之前在ASP.NET Core 2.0里做GitHub OAuth对接时也踩过这个坑,GetExternalLoginInfoAsync返回null大概率是认证配置没做全或者中间件顺序不对导致的。结合你给出的Startup.cs片段,我帮你列几个必须检查的点:

1. 补全GitHub OAuth的认证服务配置

从你贴的代码来看,你还没添加Authentication服务和GitHub的OAuth选项,这是最关键的缺失项。在ConfigureServices方法里加上这段:

services.AddAuthentication()
    .AddGitHub(options =>
    {
        // 别硬编码,建议从appsettings.json里读取配置
        options.ClientId = Configuration["Authentication:GitHub:ClientId"];
        options.ClientSecret = Configuration["Authentication:GitHub:ClientSecret"];
        // 这个回调路径要和你在GitHub开发者后台设置的完全一致,默认是/signin-github
        options.CallbackPath = "/signin-github";
    });

记得先去GitHub开发者后台创建OAuth应用,拿到ClientId和ClientSecret,并且把回调地址设置成你的域名加上上面的CallbackPath(比如https://yourdomain.com/signin-github)。

2. 确保认证中间件的顺序正确

在Configure方法里,认证中间件必须放在Mvc中间件之前,不然会导致请求到不了认证逻辑,自然拿不到登录信息:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    // 先添加异常处理、静态文件这些中间件...
    
    // 一定要先启用认证
    app.UseAuthentication();
    
    // 再启用Mvc
    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "default",
            template: "{controller=Home}/{action=Index}/{id?}");
    });
}

3. 检查登录Action的实现是否正确

发起GitHub登录的Action要正确配置认证属性,比如:

private readonly SignInManager<User> _signInManager;

// 通过构造函数注入SignInManager
public AccountController(SignInManager<User> signInManager)
{
    _signInManager = signInManager;
}

public IActionResult LoginWithGitHub()
{
    // 回调地址要指向你的外部登录回调Action
    var redirectUrl = Url.Action(nameof(ExternalLoginCallback), "Account");
    var properties = _signInManager.ConfigureExternalAuthenticationProperties("GitHub", redirectUrl);
    // 这里的认证方案名要和AddGitHub一致,默认就是"GitHub"
    return Challenge(properties, "GitHub");
}

public async Task<IActionResult> ExternalLoginCallback()
{
    var info = await _signInManager.GetExternalLoginInfoAsync();
    if (info == null)
    {
        // 如果还是null,继续往下排查其他点
        return RedirectToAction(nameof(Login));
    }
    // 这里写后续的登录或用户绑定逻辑...
}

4. 其他可能的坑

  • HTTPS要求:GitHub生产环境的OAuth回调必须用HTTPS,本地测试的话,记得在launchSettings.json里配置启用HTTPS。
  • 配置读取问题:确认你的appsettings.json里确实配置了Authentication:GitHub:ClientId和Authentication:GitHub:ClientSecret,而且Configuration能正常读取到这些值。
  • Cookie冲突:如果你的项目里自定义了Cookie配置(比如SameSite属性),可能会影响外部登录的会话传递,检查下有没有冲突。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 12:05:20