Krishna Kowshik
Krishna Kowshik

Reputation: 41

How do I restrict a user from accessing/updating another user's details?

I have an http endpoint /update-user-details that is authenticated by a JWT token.

There are two valid users in my system User1 and User2.

How do I restrict User1 from updating User2's details using the /update-user-details endpoint?

Upvotes: 3

Views: 955

Answers (2)

David Brossard
David Brossard

Reputation: 13834

You have 3 options:

  • DIY: implement code yourself that will do it. That's what Chappie Johnson recommends in their response.
  • Externalize authorization logic: use an authorization framework to do the check for you. The way to externalize really depends on the framework you developed the API in. For instance, you could look into Flask Authorization for Python or Ruby CanCanCan or .NET claims.
  • Externalize authorization using a standard approach: Attribute-Based Access Control (ABAC) is actually what you are looking for. In ABAC you write policies that state what can and cannot happen. and are the two ways you can write policies. The good thing about this approach is that you can always change the policies without rewriting your API.

Upvotes: 1

Joe B.
Joe B.

Reputation: 820

In your JWT you should have a claim in the body of the token that contains the user id of the requesting user. Before making an edit, you could check to see that the user_id value in your JWT matches the user_id value that user1 is attempting to edit. If the user_id's do not match, then reject the change.

    String userId = getUserIdFromJwt();
    if (!userId.equals("some user id")) {
        throw new HttpUnauthorizedException("You do not have access to edit" + 
        "this resource.");
    }

You have all the information about the current requesting user in the JWT so you are able to make assertions about the user.

Upvotes: 0

Related Questions