ASP.net core web api: Using Facebook/Google OAuth access token for authentication

大城市里の小女人 提交于 2019-12-02 20:40:47

If I undertsand correctly, you already have your Facebook user token from Facebook SDK through your app.
Like you I couldn't find how to do it with an ASP.NET Core library / package. So I went back to basics.
I just call a endpoint of my api with the Facebook token, check it against the Facebook graph api and if fine then I register the user (if required) and return my JWT token as if the user logged through a classical username / password path.

[HttpPost]
[AllowAnonymous]
[Route("api/authentication/FacebookLogin")]
public async Task<IActionResult> FacebookLogin([FromBody] FacebookToken facebookToken)
{
    //check token
    var httpClient = new HttpClient { BaseAddress = new Uri("https://graph.facebook.com/v2.9/") };
    var response = await httpClient.GetAsync($"me?access_token={facebookToken.Token}&fields=id,name,email,first_name,last_name,age_range,birthday,gender,locale,picture");
    if (!response.IsSuccessStatusCode) return BadRequest();
    var result = await response.Content.ReadAsStringAsync();
    var facebookAccount = JsonConvert.DeserializeObject<FacebookAccount>(result);

    //register if required
    var facebookUser = _context.FacebookUsers.SingleOrDefault(x => x.Id == facebookAccount.Id);
    if (facebookUser == null)
    {
        var user = new ApplicationUser {UserName = facebookAccount.Name, Email = facebookAccount.Email};
        var result2 = await _userManager.CreateAsync(user);
        if (!result2.Succeeded) return BadRequest();
        facebookUser = new FacebookUser {Id = facebookAccount.Id, UserId = user.Id};
        _context.FacebookUsers.Add(facebookUser);
        _context.SaveChanges();
    }

    //send bearer token
    return Ok(GetToken(facebookUser.UserId));
}

You have to copy the custom code available in this article on medium

Creat a function in AccountController.cs

 private async Task<ExternalLoginInfo> AuthenticationManager_GetExternalLoginInfoAsync_WithExternalBearer()

And paste the code given in the article

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!