首页 > 解决方案 > 使用 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并能够在我的控制器中访问它。

当然这是可行的,问题是如何?

我希望这很清楚,有人可以帮助我。非常感谢

标签: c#.net-corewindows-authentication

解决方案


这是非常可行的。最简单的方法是在 .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();
});

```


推荐阅读