【发布时间】:2018-10-26 12:16:16
【问题描述】:
我正在尝试创建自己的 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
这在实践中有效,但我觉得有点奇怪,我在HandleChallenge 中进行实际身份验证,如果失败则重定向。
从另一个 (MyAuthenticationHandler) 调用一个 AuthenticationHandler (cookie) 在我看来也很奇怪。
我怎样才能正确设置它,以便我在 HandleAuthenticate 中进行实施?
在我当前的实现中,该方法实际上从未被调用过。
另外,可以从另一个身份验证处理程序调用吗?
附:我查看了其他几篇帖子和文章(包括this、this 和this),但我无法通过查看它们找到我的问题的答案。任何帮助将不胜感激。
【问题讨论】:
-
链接多个中间件怎么样?
-
如何做到这一点?你能链接到一个基本的例子吗? :)
-
谁是您的 SSO 身份提供者?
-
我想我一开始误解了这个问题。现在我想我知道问题是什么了。为什么你在
HandleChallenge而不是HandleAuthentication做这个过程? -
这正是我的问题:)
标签: c# asp.net security authentication asp.net-core