a blog for those who code

Thursday, 20 June 2019

How to fix ExternalLoginInfo returns null in Asp.Net Core

I am working on integrating Github Login in my app. For that I was using the below code in my AuthConfigurer.cs


services.AddAuthentication(options => {
   options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
   options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
   options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
})

.AddCookie()

.AddGitHub(options => {
  options.ClientId = configuration["Authentication:GitHub:ClientId"];
  options.ClientSecret = configuration["Authentication:GitHub:ClientSecret"];
  options.Scope.Add("user:email");
  options.SaveTokens = true;
});

My Controller have two functions :

This function is just to create a ChallengeResult with the specified authentication schemes and properties.

[HttpGet]

public IActionResult SignInWithExternalProvider(string provider)
{
  var authenticationProperties = _signInManager.
          ConfigureExternalAuthenticationProperties
  (
    provider,          
    Url.Action(nameof(ExternalLoginCallback),
             new { p = provider })
  );
  return Challenge(authenticationProperties, provider);
}

[HttpGet]
public async Task<ActionResult> ExternalLoginCallback(string p)
{
  var externalLoginInfo = await _signInManager
                                  .GetExternalLoginInfoAsync();
}

The above function is the callback function from the External Providers. Now the externalLoginInfo is always coming as null because we are actually bypassing the authentication scheme when we have done.

services.AddAuthentication(options => {
   options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
   options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
   options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
})

Since there are two cookie middlewares, one fore ApplicationCookie and other ExternalApplicationCookie which has different authentication schemes and if we set the default authentication scheme for both it might not work for any of them. That is what happening with me. Thus I removed any additional setting of Authentication Scheme and my Configur function will have the below code

services.AddAuthentication().AddGitHub("Github", options =>
{
  options.ClientId = configuration["Authentication:GitHub:ClientId"];
  options.ClientSecret = configuration["Authentication:GitHub:ClientSecret"];
  options.Scope.Add("user:email");
  options.SaveTokens = true;
});

Thus now I am getting my externalLoginInfo as I wanted.

No comments:

Post a comment