在 Facebook 开发者中心创建一个应用程序,并获取客户端 ID 和客户端密钥。
将以下代码添加到 Startup.cs 文件的 ConfigureServices 方法中,以配置 Facebook 身份验证选项:
services.AddAuthentication()
.AddFacebook(options =>
{
options.AppId = "[Your_App_Id]";
options.AppSecret = "[Your_App_Secret]";
});
在 ConfigureServices 方法中调用 AddMvc。如果尚未安装 Microsoft.AspNetCore.Mvc 包,则需要执行此操作。
在 Startup.cs 文件的 Configure 方法中,使用以下代码启用身份验证中间件:
app.UseAuthentication();
Log in with Facebook
var info = await _signInManager.GetExternalLoginInfoAsync();
if (info == null)
{
return RedirectToAction(nameof(Login));
}
var result = await _signInManager.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, isPersistent: false, bypassTwoFactor: true);
if (result.Succeeded)
{
return LocalRedirect(returnUrl);
}
else
{
// Create a new user account if the user doesn't already have an account
var email = info.Principal.FindFirstValue(ClaimTypes.Email);
var user = new ApplicationUser { UserName = email, Email = email };
var createUserResult = await _userManager.CreateAsync(user);
if (createUserResult.Succeeded)
{
var addLoginResult = await _userManager.AddLoginAsync(user, info);
if (addLoginResult.Succeeded)
{
await _signInManager.SignInAsync(user, isPersistent: false);
return LocalRedirect(returnUrl);
}
}
return RedirectToAction(nameof(Login));
}
注意:需要安装 Microsoft.AspNetCore.Authentication.Facebook 包,并在视图文件中引