How to exchange claims based security with header based according to best-practice in .NET Core 3.1?

Viewed 70

NB, it's not equivalent to this question - it's too old and considers other versions/platforms.

We're setting authorization policy like so. It works and I was kind of proud of the solution.

options.AddPolicy("ClaimPolicy", config =>
{
  config.RequireAssertion(context =>
  {
    ClaimsPrincipal user = context.User;
    Claim awo = user.Claims.Single(a=>a.Type=="awo");
    bool authorized = user.IsInRoleAwo("management");
    return authorized;
  });
});

Now, the requirement has changed. The AWO value will still be used but it won't be a part of the access token as a claim in it. Instead, it will be provided to us as the header of the request. Personally, I see it as intuitively suspicious but I couldn't word my reluctance in technical terms, other than it's unconventional and allows the requested to manipulate the security parameter freely. I failed being sufficiently convincing and had to back off. (Undeniably, ones unability to motivate a choice suggests that it wasn't so great one.)

The new version looks like this. The problem is that I can't find any information about hte headers, the request nor HTTP context in there. There are fields for the user and for the resources. That's it.

options.AddPolicy("HeaderPolicy", config =>
{
  config.RequireAssertion(context =>
  {
    var resource = context.Resource;
    // now what?!
    return true;
  });
});

I was hoping that maybe I can obtain the route and pick AWO value from there (as it's a part of the REST path. I've located something in the resource field that could be cast to (Microsoft.AspNetCore.Routing.RouteEndpoint)context.Resource and from there, I can obtain .RoutePattern.RawText giving me. Regrettably, that produces the actual pattern, i.e. DemoApi/mixed/{awo}/data and not the value that's been passed in.

Should I bounce back to not reying in headers to pass me the info to be used in Authorize picking the policy? Or is there a best-practice approach to getting info on what headers were part of the request (or at least to learn the path including the passed parameters)?

I've got a suggestion to create a custom middleware to put in between AddAuthentication() and Add Authorization and possibly a custom authorization handler. I see much higher complexity as a caveat and I can't tell if it's a wise (or even feasible) solution. No blogs discussing it, as far my googling can see. There's an extensive article in that regard on MSDN but it doesn't treat SPA/headers case and, also, seems to me provide the functionality I already have implemented by RequireAssertion(...). There was also a suggestion on applying API key requirements but that seems to me like a lesser security than access tokens obtainable by autorization code flow that we try to achieve.

0 Answers
Related