c# - Denying access to users on an ASP.NET Core Web API endpoint - Stack Overflow

I have an endpoint in my API like: apiusers{:userId}...I only want the user with userId to have acc

I have an endpoint in my API like: api/users/{:userId}/...

I only want the user with userId to have access to his own endpoint and not to the endpoints of any other user.

I implemented a JWT Bearer token, which is used for authorization. I get the id from it and check if it matches the route the user wants to access:

[HttpGet("{userId:int}"), Authorize]
public async Task<ActionResult> GetUserById([FromRoute] int userId)
{
    var id = int.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier));

    if (id != userId)
    {
        return BadRequest("Access denied.");
    }
    
    var user = await unitOfWork.UserRepository.GetUserByIdAsync(userId);
    
    if (user == null)  
        return NotFound("User not found");

    return Ok(user);
}

Now, I don't think this is the correct approach. The token can easily be tampered with and the id changed. How else could I do this?

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745651481a4638291.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信