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

后端 未结 2 531
离开以前
离开以前 2021-02-01 19:57

For serveral days now I am trying to get OAuth authentication with Google and Facebook to work within my ASP.net core web api project.

my current status is:

相关标签:
2条回答
  • 2021-02-01 19:59

    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

    0 讨论(0)
  • 2021-02-01 20:20

    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));
    }
    
    0 讨论(0)
提交回复
热议问题