Search code examples
authenticationauth0strapi

Strapi 4 - User pemissions plugin policy extension


I'm attempting to migrate from Strapi 3 -> 4

I've managed to restructure my folder structure to get the schema working for all my content types.

However, in v3 I had an extra policy on the user-permissions plugin the verified the users jwt token with auth0.

I took the v3 implementation from these docs.

I'm attempting to get it to apply the same logic in v4 and i'm a bit lost since the new docs don't seem fully up-to-date.

I'm adding a new policy in /src/extensions/users-permissions/strapi-server.js Taken from the docs here

module.exports = (plugin) => {
  plugin.policies["permissions"] = async (ctx) => {
    let role;
    console.log("IN HERE");

    if (ctx.state.user) {
      // request is already authenticated in a different way
      return true;
    }

    // ... A bunch more logic
  
    return false
  }
  
  return plugin
}

If I run yarn strapi policies:list then my 'permissions' policy is listed.

However, when trying to use that policy anywhere, I don't see my console log to see that it's being applied.

I've tried to specify that policy in the routes setup:

module.exports = {
  routes: [
    {
      method: "GET",
      path: "/addition-requests",
      handler: "addition-request.find",
    },
    {
      method: "GET",
      path: "/addition-requests/:id",
      handler: "addition-request.findOne",
    },
    {
      method: "POST",
      path: "/addition-requests",
      config: {
        policies: ["plugin::users-permissions.permissions"],
      },
      handler: "addition-request.create",
    },
  ],
};

Is there anything obvious I'm missing? And is there a way to apply a policy to every request that requires auth rather than specifying a policy on the route?


Solution

  • It appears from reading this comment it appears as though any request made to a Strapi endpoint that contains a Bearer token is treated like a request that requires auth.

    That seems to be why the policy isn't being run as if I remove the Authorization header the policy does run. The question of how to execute a policy on an endpoint that requires auth still remains however.

    It appears that the issue around being able to do custom validation on a users jwt is an issue that a few people are facing with v4 Strapi. See my topic on their forum.