express elegant way to restrict resources belongs to specific user

Viewed 29

I found a lot of thread about permissions/role based authorization. however i'm looking for an elegant way or any bast practice to return data/resource belongs to specific user?

for example: I expect that http://localhost:3000/transactions will not return all transactions, only the transactions that belongs to the authenticated user that initiated the request.

my simple/manually solution? each transaction item has user_id field, so I can write middleware that decode the jwt token and takes the user_id from the token and expose it to the request object (i.e request.user_id = user_id from the token). and for each route (like transaction) i can take this request.user_id and add it to the query.

I wonder, what's is the best solution to handle this in express/node.js application? library? service? SaaS?

1 Answers

Your approach sounds correct. UserID is a value used for authorization, received in a digitally verifiable way, and referred to as a claim. A good approach is to design a claims or claimsPrincipal object containing details like this, used by your API's business authorization.

In Node.js this is sometimes processed in middleware when the token is validated and then saved to response.locals.claims, as in this code of mine. The values can then be used by business logic as you describe.

Related