How to replace HttpContext.User in ASP.NET core after authorization?

I have a custom class MyPrincipalwith some custom properties that I want to replace authenticated with ClaimsPrincipal, for example.HttpContext.User

I added special middleware:

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);
  }
}

I registered middleware to run after authentication, but before MVC in Startup.cs:

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

In mine, _Layout.cshtmlI want to use a custom property from mine MyPrincipal:

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

So far, so good, the user is recognized as MyPrincipal.

But when I add the global authorization policy:

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

Suddenly Userin _Layoutis just a ClaimsPrincipal.

MVC , ?

P.S. ASP.NET Core 2.0 Preview 2, .

+4
1

PolicyEvaluator AuthenticationScheme, Principal. , AuthenticationScheme AuthorizationPolicyBuilder.

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

, HttpContext.Authentication.SignInAsync .

+2

Source: https://habr.com/ru/post/1682862/


All Articles