Allow user only access his/her own resource with id in Authorize[] middleare .Net Core Api

Viewed 543

I am using role based authentication in .Net Core 3.1 Api. I am using Jwt tokens and user claims. Role based authentication works fine. But in some controllers I want to make sure that user gets his/her own data. Because if an employee sends other employee id in a request he/she can get that resource data, I don't want that.

I have email, id and roles in token with some other data.

What I want is that something like [Authorize(Roles="Employee", Id={userId})]

[HttpGet("getUserInventory")]
    //[Authorize(Roles="Employee", Claims.Id={userId})]
    public IActionResult getUserInventory([FromQuery] int userId)
    {
        var inventories = _userInventoryExportService.GetGlobalInventory(userId);
        if(inventories.Success)
        {
            return Ok(inventories.Data);
        }
        return BadRequest(inventories.Message);
    }
1 Answers

Have a look at this tutorial we've created at Curity: Securing a .NET Core API. You will see there how to configure authorization based on claims found in a JWT access token.

Related