我有一个带有自定义身份验证方案的.net core Web API。现在我正在尝试设置Facebook登录并访问创建的声明原则。
以下代码适用于 Cookie:
services.AddAuthentication()
.AddCookie()
.AddFacebook(config => {
// appid and secret set up here
config.CallbackPath = "/externalLogin";
config.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
});
使用此代码,一旦我在操作上使用[Authorize(AuthenticationSchemes = FacebookDefaults.AuthenticationScheme)]
,它就会使用 cookie 登录,我可以通过User.Identity
属性访问主体。
我正在尝试在通过登录方案将其设置到 cookie 中之前获取此主体。我已经设置了尝试为此设置自定义方案:
services.AddAuthentication()
.AddScheme<ExternalOptions, ExternalLogin>(ExternalLogin.SchemeName, config => { })
.AddFacebook(config => {
// appid and secret set up here
config.CallbackPath = "/externalLogin";
config.SignInScheme = ExternalLogin.SchemeName;
});
我已经为方案定义了我的空类:
public class ExternalOptions : AuthenticationSchemeOptions { }
public class ExternalLogin : AuthenticationHandler<ExternalOptions>
{
public const string SchemeName = "External";
public ExternalLogin(IOptionsMonitor<ExternalOptions> options, ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock)
: base(options, logger, encoder, clock)
{
}
protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
{
// need to access the principal here
return AuthenticateResult.Fail("Failed!");
}
}
我尝试在return AuthenticateResult.Fail("Failed!")
上使用调试器,但找不到包含主体信息的属性。
注意:我需要确保没有用于维护无状态的 cookie,以防客户端阻止其 cookie(我想会产生问题)。无论哪种方式,在 Web API 上启用 Cookie 都不被认为是好的。其次,目标是建立一个外部身份验证,以后可以在未来的外部登录(例如google和ms)中重复使用。
可以通过方案options.Events
在身份验证过程的不同点访问ClaimsPrincipal
(每个方案定义自己的事件)。
在这里,您可以使用 cookie 事件。例如:
services
.AddAuthentication()
.AddCookie(options =>
{
// there are various events, be sure to use
// the appropriate one for your use case
options.Events.OnValidatePrincipal = (context) =>
{
var principal = context.Principal;
// reject the principal?
if (principal.Identity.Name != "MyUser")
context.RejectPrincipal();
// each event expect a Task
return Task.CompletedTask;
};
)
.AddFacebook(config => {
// appid and secret set up here
config.CallbackPath = "/externalLogin";
config.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
});