c# - ASP.NET Core 使用带有 cookieauthentication 的自定义身份验证处理程序
问题描述
我正在尝试创建自己的 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 进行身份验证
- 如果没有有效的 auth cookie,使用我的 auth 进行质询,如果成功则创建一个 auth cookie
这在实践中有效,但我觉得有点奇怪,我正在执行实际的身份验证HandleChallenge
并在失败时重定向。从另一个(MyAuthenticationHandler)调用一个AuthenticationHandler(cookie)对我来说似乎也很奇怪。
我怎样才能正确设置它,以便我进行实施HandleAuthenticate
呢?
在我当前的实现中,该方法实际上从未被调用过。
另外,是否可以从另一个身份验证处理程序调用?
PS我看过其他几篇文章和文章(包括this、this和this),但我无法通过查看它们找到我的问题的答案。任何帮助,将不胜感激。
解决方案
我认为您所追求的可能会通过 ASP.NET Core 2.1 中的一些新功能来解决
<PackageReference Include="Microsoft.AspNetCore.Authentication" Version="2.1.0-rc1-final" />
以下是如何根据 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 线程。
推荐阅读
- memory-leaks - C# - 将任何不安全的非托管类型转换为托管类型而无需任何新的内存分配 - 在内存中保持相同的大小
- android - 以花哨的方式使用 gson 和 retrofit2 解析 JSON 属性“数据”
- java - Firestore 模拟器在 Docker 中运行时无法启动
- java - 无法在 onTouch 事件中使用 setScaleX 和 setScaleY 调整视图大小和旋转视图
- javascript - 在对象中调用方法时,它说它不是函数
- excel - Excel 高级条件格式
- r - 不同模型的先验分布和后验分布图
- javascript - 如何在 js 文件中轻松找到所需的 jquery 函数?
- javascript - Laravel VueJS 将动态数量绑定到产品列表组件中的每个输入
- angular - 我应该将一个组件全部交给 @inputs() 还是只交给一个 ID/ 对象?