c# - 使用 Windows 身份验证在 .NET Core 2.1 中扩展 IPrincipal
问题描述
我正在尝试IPrincipal
使用 Windows 身份验证扩展 .NET Core。
在上一个项目(使用 .NET Framework 4.6.1)中,Application_Start()
我添加了以下代码来扩展IPrincipal
:
protected void WindowsAuthentication_OnAuthenticate(object sender, WindowsAuthenticationEventArgs e)
{
if (e.Identity != null && e.Identity.IsAuthenticated)
{
NgUser opPrincipal = CustomStaticMethod.GetUserAD();
HttpContext.Current.User = opPrincipal;
}
}
这是我的自定义课程
public class NgUser : IPrincipal
{
// code removed for abbr ...
}
然后每次在控制器转换HttpContext.Current.User
中,CustomPrincipal
我都可以访问自定义属性,而无需使用声明或使用静态扩展或在会话中存储对象。
现在在 .NET Core 中,我已经看到您可以自定义声明转换,我也阅读了这篇文章,它们基本上扩展了IPrincipal
.
我更喜欢IPrincipal
使用我的自定义类进行扩展,将其注册Startup.cs
并能够在我的控制器中访问它。
当然这是可行的,问题是如何?
我希望这很清楚,有人可以帮助我。非常感谢
解决方案
这是非常可行的。最简单的方法是在 .NET CoreOnAuthenticate
的管道中添加一个行为类似于 的中间件。Configure()
在这里,您将更换 IPrincipal。请注意,这仅在 Web 应用程序设置为仅在 IIS/IIS Express 中使用 Windows 身份验证运行时才有效。匿名身份验证增加了额外的开销。
如果您有这个简单的 Win auth 设置,请将Startup.cs
其放在Configure(IApplicationBuilder app)
方法顶部附近:
// Because IIS automatically captures the user login, by the time the app is touched
// in any request, the context (ctx) User is already present.
app.Use(async (ctx, next) =>
{
if (ctx.User?.Identity?.IsAuthenticated == true)
{
NgUser opPrincipal = CustomStaticMethod.GetUserAD();
ctx.User = opPrincipal;
}
// be sure to continue the rest of the pipeline!
await next.Invoke();
});
```
推荐阅读
- javascript - 在巨大的 React.JS webapp 中渲染后加载 JavaScript 脚本
- python-3.6 - 调用 tensorflow2 模型未返回已在 call() 方法中定义的输出
- mysql - 从我的 sql 迁移到 postgres 然后继续更新
- javascript - JavaScript面临的问题
- amazon-web-services - 如何在 AWS DynamoDB 上为失败的 INSERT 尝试设置警报
- scikit-learn - 如何正确地逆转换 TFIDF 矢量化器
- swift - 查找相对于屏幕点macOS swift的应用程序位置
- spark-ar-studio - 将鼻子的 3D 位置值转换为 2D 值?
- android-studio - 当我重新启动并加载旧版本的应用程序时,我的 Flutter 应用程序没有更新
- html - 使用溢出的侧面导航定位粘性