VSO
VSO

Reputation: 12666

Attribute to Check Auth Logic in .NET Core API

The stack is latest .NET Core w/ C#.

We are pasting the same code checking if someone is trying to edit their own profile (we have their profileId from a JWT) into almost every controller:

if (User.GetProfileId() != profileId)
  return Unauthorized();

I am at a bit of a loss how to remove this redundancy. I can definitely add generic middleware or a filter to perform this, but it seems heavy handed. Is there some approach to add a [MustOwnProfile] attribute and have .NET Core run the test in the above code anywhere the attribute appears?

An example of the above check in context:

    [HttpPost]
    [Route("{profileId:int}/start-profile/{checklistId:int}")]
    [Authorize]
    public async Task<IActionResult> StartProfile(int profileId, int checklistId)
    {
      if (User.GetProfileId() != profileId)
        return Unauthorized();

      await _profileService.StartProfile(profileId, checklistId);
      return Ok();
    }

Upvotes: 0

Views: 205

Answers (1)

Joel Fleischman
Joel Fleischman

Reputation: 434

It's possible to define custom attributes. Cancellation and short-circuiting

Upvotes: 1

Related Questions