几天来,我一直在尝试通过 Google 和 Facebook 进行 OAuth 身份验证,以便在我的 ASP.net core Web api 项目中工作。
我目前的状态是:
- 我有一个 ASP.net core Web Api 项目,其中需要对用户进行身份验证
- 我有一个 Angular 2 Web 应用程序,它应该使用我的 Web API(带有身份验证)
- 我有一个 android 应用程序,它应该使用我的 web api (带有身份验证)
我的目标是:
- 使用 Google/Facebook 作为 OAuth 提供商进行登录
- 稍后:添加自己的用户帐户(可能使用 IdentityServer4)
- 无需重定向到特殊的登录网站(如 IdentityServer4 解决方案)。只需点击应用程序中的 facebook/google 按钮,允许访问,完成!
在我的 Android 和 Angular 应用程序中,我能够从 google/facebook 检索访问令牌。现在,我想使用 OAuth 隐式流程,使用给定的访问令牌在我的 Web api 上对用户进行身份验证(将令牌作为不记名令牌放入标头中)
我的问题是:有没有通用的方法可以轻松做到这一点?我不想为此使用 facebook/google SDK。
我尝试过以下操作:
-
使用身份服务器4:这样我就可以在我的 webapi 上使用 facebook/google 登录,但需要重定向到 IdentityServer4 登录页面。有没有可能的方法只需点击我的应用程序中的 google/fb 按钮并登录,没有重定向到identityServer登录页面?
-
使用 google/facebook 身份验证中间件 (https://learn.microsoft.com/en-us/aspnet/core/security/authentication/social/ https://learn.microsoft.com/en-us/aspnet/core/security/authentication/social/):但他们没有验证我发送的不记名令牌(尝试了无数种方法来实现正确的验证)。这甚至可以在 Web api 中使用吗?
- 尝试使用Microsoft.AspNetCore.Authentication.JwtBearer-中间件并自己为 google/facebook 添加必要的选项,但也没有验证(以及无数次尝试)
在过去的几天里,我尝试了很多可能的解决方案,但我完全陷入困境,不知道我需要做什么才能实现这一目标。此时,我已经阅读了几乎所有 asp.net web api oauth 教程/stackoverflow 条目,但无法弄清楚如何在我的情况下按照我的意愿使用它。大多数教程仅适用于 mvc 网站或使用 IdentityServer4 并重定向到其登录页面。
有什么建议或解决方案吗?我缺少什么?
如果我理解正确的话,您已经通过您的应用程序从 Facebook SDK 获得了 Facebook 用户令牌。
和你一样,我找不到如何使用 ASP.NET Core 库/包来做到这一点。所以我回到了基础。
我只需使用 Facebook 令牌调用 api 的端点,根据 Facebook 图形 api 检查它,如果正常,则注册用户(如果需要)并返回我的 JWT 令牌,就像用户通过经典用户名/密码路径登录一样。
[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));
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)