最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

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

matteradmin5PV0评论

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?

Post a comment

comment list (0)

  1. No comments so far