Identify user based on the JWT attached with request

System Information
  • Strapi Version: 3.6.8
  • Operating System: MacOS
  • Database: MariaDB

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.

Thanks

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,
        });

I think you can also just use the built in ctx

const {user } = ctx.state;

This will give you the user object of that user.

1 Like

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

@DavoMyan and @Eventyret thank you both for helping me out.

@Eventyret can you please guide me a little more on where I should place that code?

Do, I need to add that as a policy and then update all of the endpoints?

Providing a code sample or linking to existing code snippet will be a great help. Thanks

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.

Is this still valid in v4?

Is it possible to have jwt bearer token per user and to update that token in strapi dashboard independent of login credentials?

1 Like

I have ctx.state.user which returns undefined! What’s wrong?

Are you sure you are sending a JWT authenticated request ?

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”.

I use Postman to send my requests.

Any idea about my problem?

This issue comes from an “auth” filed set to fale in the customed route config. Sorry… :sweat_smile:

1 Like