项目 04/18/2022 谢谢。
本教程包含代码示例,演示如何让用户通过上一页中创建的示例 ASP.NET Core 项目使用其 Facebook 帐户登录。 首先按照官方步骤创建 Facebook 应用 ID。
在 Facebook 中创建应用
https://localhost:44320/signin-facebook
注意 URI /signin-facebook 设为 Facebook 身份验证提供程序的默认回叫。 可以通过类的FacebookOptions继承RemoteAuthenticationOptions.CallbackPath属性配置 Facebook 身份验证中间件时更改默认回调 URI。
App ID
App Secret
存储 Facebook 应用 ID 和机密
使用机密管理器存储敏感设置,例如 Facebook 应用 ID 和机密值。 对于此示例,请执行以下步骤:
Authentication:Facebook:AppId
Authentication:Facebook:AppSecret
dotnet user-secrets set "Authentication:Facebook:AppId" "<app-id>"
dotnet user-secrets set "Authentication:Facebook:AppSecret" "<app-secret>"
:
__
:
__
:
配置 Facebook 身份验证
Startup.ConfigureServices
services.AddAuthentication().AddFacebook(facebookOptions =>
{
facebookOptions.AppId = Configuration["Authentication:Facebook:AppId"];
facebookOptions.AppSecret = Configuration["Authentication:Facebook:AppSecret"];
});
Program
var builder = WebApplication.CreateBuilder(args);
var services = builder.Services;
var configuration = builder.Configuration;
services.AddAuthentication().AddFacebook(facebookOptions =>
{
facebookOptions.AppId = configuration["Authentication:Facebook:AppId"];
facebookOptions.AppSecret = configuration["Authentication:Facebook:AppSecret"];
});
AddAuthentication
AuthenticationBuilder 每个身份验证方案只能调用注册身份验证处理程序的扩展方法一次。 存在允许配置方案属性、方案名称和显示名称的重载。
使用 Facebook 登录
- 运行应用并选择“登录”。 在“使用其他服务登录”下,选择“Facebook”。 你将重定向到 Facebook 进行身份验证。 输入 Facebook 凭据。 你将重定向到你的站点,可在其中设置电子邮件。
你现在使用 Facebook 凭据登录:
再次操作,取消授权外部登录
用户不批准请求的授权请求时,AccessDeniedPath 可以为用户代理提供重定向路径。
AccessDeniedPath
"/AccessDeniedPathInfo"
services.AddAuthentication().AddFacebook(options =>
{
options.AppId = Configuration["Authentication:Facebook:AppId"];
options.AppSecret = Configuration["Authentication:Facebook:AppSecret"];
options.AccessDeniedPath = "/AccessDeniedPathInfo";
});
AccessDeniedPath
- 已取消远程身份验证。 此应用需要身份验证。 若要再次尝试登录,请选择“登录”链接。
测试 AccessDeniedPath
AccessDeniedPath
使用代理或负载均衡器转发请求信息
https
https
使用转发标头中间件以使应用可以使用原始请求信息来进行请求处理。
有关详细信息,请参阅配置 ASP.NET Core 以使用代理服务器和负载均衡器。
多个身份验证提供程序
当应用需要多个提供程序时,将提供程序扩展方法链接在后面 AddAuthentication:
services.AddAuthentication()
.AddMicrosoftAccount(microsoftOptions => { ... })
.AddGoogle(googleOptions => { ... })
.AddTwitter(twitterOptions => { ... })
.AddFacebook(facebookOptions => { ... });
有关 Facebook 身份验证支持的配置选项的详细信息,请参阅 FacebookOptions API 参考。 配置选项可用于执行以下操作:
- 请求有关用户的各种信息。 添加查询字符串参数,以自定义登录体验。
疑难解答
services.AddIdentity
ConfigureServices
后续步骤
AppSecret
Authentication:Facebook:AppId
Authentication:Facebook:AppSecret