c# - 授权后如何替换 ASP.NET Core 中的 HttpContext.User?

标签 c# asp.net-core asp.net-core-mvc

我有一个带有一些自定义属性的自定义用户类 MyPrincipal,我想用它替换经过身份验证的 ClaimsPrincipal,例如HttpContext.User

我添加了一个自定义中间件:

public class MyMiddleware {
  private readonly RequestDelegate next;

  public MyMiddleware(RequestDelegate next) {
    this.next = next;
  }

  public async Task Invoke(HttpContext context) {
    if (context.User.IsAuthenticated) {
      context.User = new MyPrincipal(context.User);
    }
    await next(context);
  }
}

我已将中间件注册为在身份验证之后运行,但在 Startup.cs 中的 MVC 之前运行:

public void Configure(IApplicationBuilder app) {
  app.UseAuthentication();
  app.UseMiddleware<MyMiddleware()>;
  app.UseMvcWithDefaultRoute();
}

在我的 _Layout.cshtml 中,我想使用 MyPrincipal 中的自定义属性:

...
@if (User is MyPrincipal) {
  <do stuff>
}
...

到目前为止,用户被识别为 MyPrincipal

但是当我添加全局授权策略时:

public void ConfigureServices(IServiceCollection services) {
  services.AddMvc(options => {
    var policy = new AuthorizationPolicyBuilder(CookieAuthenticationDefaults.AuthenticationScheme)
        .RequireAuthenticatedUser()
        .Build();
    options.Filters.Add(new AuthorizeFilter(policy));
  });
}

突然间,_Layout 中的 User 只是一个 ClaimsPrincipal

我如何才能阻止 MVC 替换我的委托(delegate)人,或者在授权策略完成后连接到管道?

附言我正在使用 ASP.NET Core 2.0 Preview 2,以防万一。

最佳答案

PolicyEvaluator 正在验证替换 PrincipalAuthenticationScheme。要解决此问题,请从 AuthorizationPolicyBuilder 构造函数中移除 AuthenticationScheme 参数。

var policy = new AuthorizationPolicyBuilder()
    .RequireAuthenticatedUser()
    .Build();

这会将策略应用于所有身份验证方案,并假定您已在别处调用了 HttpContext.Authentication.SignInAsync

关于c# - 授权后如何替换 ASP.NET Core 中的 HttpContext.User?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45462730/

相关文章:

c# - 将 Try-Catch 放在 For 循环中是不好的做法吗?

c# - 没有 ASP.NET 标识的 .NET Core 外部身份验证

c# - 验证 List<T> 以确保列表包含列表中的一项与数据注释 MVC C#

c# - 在 ASP.NET Core 2.0 Web Api 中返回 "raw"json

c# - 停止页面重新加载

c# - Webapi 方法未找到异常 get_MessageHandlers

docker - 如何在运行 .net Core 模板的 windows docker 容器和 windows 主机中安装开发证书?

c# - .NET Core API key 和身份集成

c# - 一个 Controller 给出 “This localhost page can’找不到”

c# - EF Core 多对多自连接