Hi, is there a way I can identify the user based on JWT attached with the request?
Let’s say I have a collection type called “Product”.
When an authenticated user sends a “GET” request on this endpoint, I want to return only the products associated with the user requesting it.
I can get the specific products by sending the User ID in the query params of the API endpoint from the frontend.
But It would be a lot easier if I just send the “GET” request without adding any user ID, and I get the response including only the specific products based on the user’s JWT.
Yes, your user ID is inside the JWT. So simply use a JWT decoder, there’s an NPM package for that.
For every request you just send in the JWT token along and do this:
const jwt_decode = require("jwt-decode"); //npmpackage
let decoded = jwt_decode(data.token); //data is what you sent in.
const userId = decoded.id;
let user = await strapi.plugins["users-permissions"].services.user.fetch({
id: userId,
});
Yeah true, in my case I was using Socket.io technology for a game I’m developing so this was a way for me to identify via JWT. Yours is better if you’re using endpoints
Policy yes would be the best location, albeit not a great example (please don’t write a huge single policy for multiple endpoints like I did in the example) but it gives a bit of context on how you can handle stuff like this in policies:
PS this is a horribly written example, but you get the idea.
Yes, as I can see my JWT token inside the ctx.
I tried this code, which works perfectly:
const user = await strapi.plugins[‘users-permissions’].services.jwt.getToken(ctx);
With ctx.state.user, I have systematically “undefined”.