Skip to content

Instantly share code, notes, and snippets.

@alirioangel
Last active November 2, 2020 22:26
Show Gist options
  • Save alirioangel/cb5e7c7fd67c29e546a7eb57339d6e49 to your computer and use it in GitHub Desktop.
Save alirioangel/cb5e7c7fd67c29e546a7eb57339d6e49 to your computer and use it in GitHub Desktop.
External Login with Social media.
// startup
.AddGoogle(options =>
{
IConfigurationSection googleAuthNSection =
config.GetSection("Authentication:Google");
options.ClientId = googleAuthNSection["ClientId"];
options.ClientSecret = googleAuthNSection["ClientSecret"];
})
.AddLinkedIn(options =>
{
IConfigurationSection linkedInAuthNSection =
config.GetSection("Authentication:LinkedIn");
options.ClientId = linkedInAuthNSection["ClientId"];
options.ClientSecret = linkedInAuthNSection["ClientSecret"];
});
// ACCOUNT CONTROLLER
[HttpGet("/external")] // Call from Mobile App with the provider name and returnUrl (im not sure how he'll send it to me that).
public IActionResult ExternalLogin(string provider, string returnurl)
{
var redirectUri = Url.Action(nameof(ExternalLoginCallback), "Account", new { returnurl });
var properties = _signInManager.ConfigureExternalAuthenticationProperties(provider, redirectUri);
return Challenge(properties, provider);
}
public async Task<ActionResult<UserDto>> ExternalLoginCallback(string returnUrl)
{
var info = await _signInManager.GetExternalLoginInfoAsync();
if (info == null)
{
return BadRequest();
}
var email = info.Principal.FindFirst(ClaimTypes.Email)?.Value;
var userDB = await _userManager.Users.SingleOrDefaultAsync(x => x.Email == email);
if (userDB == null)
{
var name = info.Principal.FindFirst(ClaimTypes.GivenName)?.Value;
var lastName = info.Principal.FindFirst(ClaimTypes.Surname)?.Value;
var registerType = info.ProviderDisplayName == "Google" ? RegisterType.Google : RegisterType.Linkedin;
var user = new User()
{
Email = email,
Name = name,
LastName = lastName,
RegisterType = registerType
};
var result = await _userManager.CreateAsync(user);
if (!result.Succeeded) BadRequest();
var roleResult = await _userManager.AddToRoleAsync(user,"Member");
if (!roleResult.Succeeded) BadRequest();
return new UserDto()
{
Email = user.Email,
Token = await _tokenService.CreateToken(user),
};
}
return new UserDto()
{
Email = userDB.Email,
Token = await _tokenService.CreateToken(userDB),
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment