我正在尝试创建自己的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());
}
}
这在实践中是可行的,但是我觉得有点奇怪,我在< code>HandleChallenge中进行实际的身份验证,如果失败就重定向。从一个AuthenticationHandler(MyAuthenticationHandler)调用另一个AuthenticationHandler (cookie)对我来说也很奇怪。
我如何正确设置它,以便在< code>HandleAuthenticate中实现它?在我目前的实现中,这个方法从来没有被真正调用过。
另外,可以从另一个身份验证处理程序调用一个身份验证处理程序吗?
附言:我已经看了其他几篇帖子和文章(包括这个、这个和这个),但是我没有从这些帖子中找到我问题的答案。任何帮助都将不胜感激。
我认为您所追求的可能会通过ASP.NET Core 2.1中的一些新功能来解决
<代码>
下面是一个如何基于httpcontext数据“选择”身份验证方案的示例:
builder.AddPolicyScheme("scheme", "scheme", opts =>
{
opts.ForwardDefaultSelector = ctx =>
{
if (ctx.Request.Query.ContainsKey("isRedirectedFromSSO"))
{
return null; // or ctx.ForbidAsync(), not sure here.
}
return OpenIdConnectDefaults.AuthenticationScheme; // or your own sso scheme, whatever it may be here.
};
})
.AddCookie()
.AddOpenIdConnect();
看看这个GitHub线程。