How to authenticate request made from custom plugin?

System Information
  • Strapi Version: 4.10.2
  • Operating System: Windows 11
  • Database: SQLite
  • Node Version: 18.15.0
  • NPM Version: 9.5.0
  • Yarn Version: 1.22.19

I have a custom plugin with the following route:

module.exports = [
  {
    method: "GET",
    path: "/export/:formToExport/:deleteAfterExport",
    handler: "myController.index",
    config: {
      policies: [],
    },
  },
];

And I have an admin page with a button that calls the following function to call that endpoint:

  const handleDownload = async () => {
    try {
      const url = `/export-form-submissions/export/${encodeURIComponent(
        formToExport
      )}/${deleteAfterExport}`;
      const response = await fetch(url);

      //do more stuff
  };

I get a 401 error when I call this function unless I disable the authentication with auth: false in the route’s config. I don’t want to disable the authentication check as I only want logged in users to be able to make the request.

Is there a way I can include the login session information in the request so that I can call the endpoint from the plugin’s admin page?

Use the helper plugin, per answer here …
How to call default api endpoint in custom plugin

Thank you so much for your response! You’ve saved my butt!

Is there any mention of these helper functions in the documentation? I can’t seem to find them anywhere…

Many thanks again!

I don’t think they are documented, yet, except in the code on GitHub.

Hey @ChrisLau90 and @stevewlrls

I am having the same issue but calling my plugin route from postman i get 401.
I am using the bearer token of an authenticated user but i cant find the way to pass the 401. It only work with auth:false config, but i want to be called only for an authenticated user and i want to know information about that user in the controller.

module.exports = [
{
method: ‘POST’,
path: ‘/test/hello’,
handler: ‘test.hello’,
config: {
policies: ,
},
}
];

By using Postman, you’re accessing your route outside of an authenticated session. Only requests from the Strapi front end have a user session associated with them, and even those need to be made using the helper plugin to add the session token. If one could just copy a session token and use it from elsewhere, it would leave Strapi with a big hole in its security.

There may be a way to get Postman to use the authentication api route to get an active session for a known user, but I haven’t tried to do that, and don’t know how. Perhaps if you re-frame your question [i.e. ask a new one about that] you may find someone who can help.

I suspect it wouldn’t help you to create an API token and use that for testing, because you want to obtain details of the current user - and an API token doesn’t have one.