0

I have implemented a middle ware that would be executed on every route. On the basis of the absence of a claim in the identity, I would like to restrict the route access. Below is what I'm able to implement now

app.Map(new PathString(Configuration["APIRoutes"]), HandleCustomAuthentication);

// Function

private void HandleCustomAuthentication(IApplicationBuilder app)
{
    app.Run(async (context) =>
    {
        var route = context.GetRouteData();
        var token = context.Request.Headers["Authorization"].ToString().Split(" ")[1];
        if (context.Request.Headers.ContainsKey("xyz") && context.Request.Headers["xyz"] !="0" )
        {
            // No idea how to make sure if this condition is met run the particular route.
        }
    });
}

Can someone guide how to do it?

P.S: I'm using dot net core 2.0

Kirk Larkin
  • 60,745
  • 11
  • 150
  • 162
Sana
  • 436
  • 2
  • 21

1 Answers1

0

TL;DR: You can't do that (except you parse the route manually). But its the wrong approach anyways.

You are supposed to use the policy based authentication in this case.

Long answer

You can't do that (right now).

Inside the middleware, the not determined yet. They are determined in the Routing middleware (.UseMvc is nothing else than routing middleware).

ASP.NET Core 2.2 introduced a new Endpoint Routing (formerly know as dispatcher) which will act as a new base and to allow early middlewares to access routing data.

But in ASP.NET Core 2.2 the Endpoint Routing is used only under the hood in the UseMvc middleware and has no public accessible API for all other middlewares. This is announced for ASP.NET Core 3.0.

The correct way to do what you are looking for is to implement Policy-based Authorization. Also see blowdart's statement here).

Basically you create a claims based policy and add a [Authorize(Policy = "EmployeeOnly")] attribute to your actions or controllers.

services.AddAuthorization(options =>
{
    options.AddPolicy("EmployeeOnly", policy => policy.RequireClaim("EmployeeNumber"));
});

And on Controller

[Authorize(Policy = "EmployeeOnly")]
public class MyController : ControllerBase
{
    ...
}

or

[Authorize(Policy = "EmployeeOnly")]
public Task<IActionResult> GetEmployeeProfile(Guid employeeId)
{
    ....
}
Community
  • 1
  • 1
Tseng
  • 52,202
  • 10
  • 166
  • 183
  • The problem is i have alot of controllers and its not possible to manually apply authorize attribute to each of it – Sana Mar 26 '19 at 16:46