使用 Windows 身份验证在 .NET Core 2.1 中扩展 IPrincipal

Extend IPrincipal in .NET Core 2.1 with Windows Authentication

我正在尝试使用 Windows 身份验证在 .NET Core 中扩展 IPrincipal

Application_Start() 的先前项目(使用 .NET Framework 4.6.1)中,我添加了以下代码以扩展 IPrincipal:

protected void WindowsAuthentication_OnAuthenticate(object sender, WindowsAuthenticationEventArgs e)
{
    if (e.Identity != null && e.Identity.IsAuthenticated)
    {
        NgUser opPrincipal = CustomStaticMethod.GetUserAD();
        HttpContext.Current.User = opPrincipal;
     }
 }

这是我的习惯class

public class NgUser : IPrincipal
{
    // code removed for abbr ...
}

然后每次在控制器中将 HttpContext.Current.User 转换为 CustomPrincipal 时,我都可以访问自定义属性,而无需使用声明或使用静态扩展或在会话中存储对象。

现在在 .NET Core 中我看到你可以 customize claims transformation and I've also read this 并且它们基本上扩展了 IPrincipal.

我更愿意使用我的自定义 class 扩展 IPrincipal,在 Startup.cs 中注册它并能够在我的控制器中访问它。

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

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

非常可行。最简单的方法是在 .NET Core 中的 Configure() 管道中添加一个类似于 OnAuthenticate 的中间件。在这里,您将换出 IPrincipal。请注意,这仅在网络应用程序设置为 运行 且仅在 IIS/IIS Express 中使用 Windows 身份验证时才有效。匿名身份验证会增加额外开销。

如果您有这个简单的 Win 身份验证设置,请在您的 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();
});

```