Should pass and get id from params or should get from JWT token?

Viewed 321

When modeling a resource in REST way. We use hierarchical pattern.

I will model my User resource at /users and profile of a user at /users/:id/profile

Also, a user must be authenticated using a token to access their profile, in this case JWT.

So, I also can model this way /user and user/profile.

I have this confusion for a long, but have a hunch at the same time that first one is better.

Should I pass and get id from params or from JWT token?

1 Answers

Another option is to use "self" in uri ( users/self/profile ). I usually create an api that get id from params ( user/{id}/profile ) and then write a middleware for those clients who don't want to send id and read the userid from JWT token for them .

I put some code to explain better what i mean . For example we have this api :

[HttpGet("users/{userId}/profile")]
public IHttpActionResult GetProfile(long userId)
{

}

We can call api like this : users/1/profile

And then i have this middleware :

public class SelfRequestMiddleware
{
    public void Invoke()
    {
        // input : /users/self/profile
        // output : /users/1/profile

        if(Uri.Split('/').Contains("self"))
            Uri.Replace("self",UserId); // Get User Id From Token
    }
}

Now we can call this api with both uri :

/users/1/profile

/users/self/profile

And it depends on client how to call the api .

Related