我正在尝试创建自己的AuthenticationHandler并与cookie验证一起使用:
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = MyAuth.Scheme;
})
.AddCookie()
.AddScheme<MyAuthenticationOptions, MyAuthenticationHandler>(MyAuth.Scheme, "My auth scheme", options => { });
.
public MyAuthenticationHandler(...) : base(...) {}
protected override Task<AuthenticateResult> HandleAuthenticateAsync()
{
throw new NotImplementedException();
}
protected override async Task HandleChallengeAsync(AuthenticationProperties properties)
{
var myUser = await DoAuth();
if (!myUser.IsAuthenticated)
{
if (Context.Request.Query.ContainsKey("isRedirectedFromSSO"))
{
Context.Response.Redirect("/unauthorized");
return;
}
else
{
Context.Response.Redirect("url to sso");
return;
}
}
var claims = new List<Claim>
{
new Claim(ClaimTypes.NameIdentifier, user.Username),
};
var identity = new ClaimsIdentity(claims, MyAuth.Scheme);
var claimsPrincipal = new ClaimsPrincipal(identity);
var authProperties = new AuthenticationProperties {};
await Context.SignInAsync(
CookieAuthenticationDefaults.AuthenticationScheme,
claimsPrincipal,
authProperties);
Context.Response.Redirect(Request.GetEncodedUrl());
}
}
- 如果存在有效的认证cookie,则使用该cookie进行认证
- 如果不存在有效的认证cookie,则使用我的认证方式发起挑战,并在成功后创建一个认证cookie
这种实现方法在实践中是可行的,但我觉得在HandleChallenge方法中进行实际认证并在失败时重定向有点奇怪。 另外,我也觉得从一个AuthenticationHandler(cookie)调用另一个(MyAuthenticationHandler)有点奇怪。
如何正确设置以便我可以在HandleAuthenticate方法中执行实现? 在我的当前实现中,该方法实际上从未被调用。
此外,从另一个身份验证处理程序调用一个身份验证处理程序是否可以?
HandleChallenge
中进行这个过程,而不是在HandleAuthentication
中呢? - Mohammed Noureldin