Custom middleware bearer 401 error

I wrote custom middleware for leads and want to grant access to route locations by bearer token. My middleware sees the lead and prints it, but I still encounter an error.

const jwt = require("jsonwebtoken");

module.exports = (config, { strapi }) => {
  return async (ctx, next) => {
    if (ctx.request.path.startsWith("/api/location")) {
      const authorizationHeader = ctx.request.header.authorization;
      if (!authorizationHeader) {
        ctx.unauthorized("Authorization header not found");
        return;
      }

      const [scheme, token] = authorizationHeader.split(" ");

      if (scheme !== "Bearer" || !token) {
        ctx.unauthorized("Invalid authorization format");
        return;
      }

      try {
        // Verify the token (assuming JWT)
        const decoded = jwt.verify(token, process.env.JWT_SECRET);
        const lead = await strapi.service("api::lead.lead").verify(decoded);

        if (!lead) {
          ctx.unauthorized("Invalid token");
          return;
        }

        // Attach lead info to the context state as user
        ctx.state.user = lead;
        console.log("User information attached to context state:", lead);
      } catch (err) {
        ctx.unauthorized("Token verification failed: " + err.message);
        return;
      }
    }

    await next();
  };
};

Route:

module.exports = {
  routes: [
    {
      method: "GET",
      path: "/location/pdf/:id",
      handler: "location.pdf",
      config: {
        middlewares: ["global::bearerAuth"],
      },
    },
  ],
};

Middleware config:

export default [
  "strapi::logger",
  "strapi::errors",
  "strapi::security",
  "strapi::cors",
  "strapi::poweredBy",
  "strapi::query",
  "strapi::body",
  "strapi::session",
  "strapi::favicon",
  "strapi::public",
  {
    name: "global::bearerAuth",
    config: {},
  },
]

This topic has been created from a Discord post (1255424717058216078) to give it more visibility.
It will be on Read-Only mode here.
Join the conversation on Discord