GetExternalLoginInfoAsync在asp.net core 2.0中返回null

时间:2018-03-20 16:04:38

标签: c# asp.net-core asp.net-identity asp.net-core-2.0 asp.net-identity-2

我想在aspnet core 2.0中使用OAuth连接到GitHub。我有以下设置。

Startup.cs:

services.AddDbContext<DbContext>(options =>
            options.UseNpgsql(Configuration.GetConnectionString("DefaultConnection"))
        );

        services.AddIdentity<User, Role>()
        .AddEntityFrameworkStores<DbContext>()
        .AddDefaultTokenProviders();

        services.AddMvc(options => options.OutputFormatters.Add(new HtmlOutputFormatter()));
        services.AddAntiforgery(x => x.HeaderName = "X-XSRF-TOKEN");

        services.AddAuthentication(options =>
        {
            options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
        })
        .AddCookie()
        .AddGitHub(options =>
        {
            options.ClientId = "xxxxxxxxxx";
            options.ClientSecret = "xxxxxxxxxxxxxxx";
            options.CallbackPath = new PathString("/auth/callback/GitHub");
        })

控制器:

[HttpGet("{provider}")]
    public IActionResult Index(string provider)
    {
        return Challenge(new AuthenticationProperties() { RedirectUri = Url.Action("CallBack", "Auth") }, provider);
    }

[HttpGet("callback")]
    public async Task<IActionResult> CallBack()
    {
        var info = await _signInManager.GetExternalLoginInfoAsync(); // <== this is always NULL
        return Redirect("~/");
    }

auth流程正确完成且没有错误。但是,行

var info = await _signInManager.GetExternalLoginInfoAsync();

总是产生空。

网络上散布着一些线索,例如this one,似乎没有任何划痕让我发痒。

思考?我错过了某个地方的设置吗?大概...

谢谢!

1 个答案:

答案 0 :(得分:0)

与Identityserver4一起使用时,在代码IdentityConstants.ExternalScheme的以下部分不匹配,因此“ auth”为null

但是,将其更改为idsrv.external可以继续进行。

 public async Task<ExternalLoginInfo> GetExternalLoginInfoAsync(string expectedXsrf = null)
    {
        var auth = await HttpContext.AuthenticateAsync(IdentityConstants.ExternalScheme);
        var items = auth?.Properties?.Items;
        if (auth?.Principal == null || items == null || !items.ContainsKey("LoginProviderKey"))