Forbidden 403 to fetch a private article with Cookies

[details=“System Information”]

  • Strapi Version: 3.6.3
  • Operating System: Ubuntu 20.04.1 LTS
  • MongoDB: v4.4.6
  • Node Version: v14.15.4
  • NPM Version: 6.14.10
  • Yarn Version: 1.22.10

Hi,
I am working on an authentication blog using Gatsby and Strapi where I have to make some content as private and some as public.

I followed this thread to send cookies from the Strapi server: Use of JWT in httpOnly cookie #4632 - #27 by davoscript

I’m having trouble fetching a single article. It’s giving me 403 Forbidden Error. I can see a jwt token being set in the browser. Cookie is present in the Request Header as well.

My frontend request:

 const response = await axios({
            method: 'post',
            url: `http://localhost:1337/graphql`,
            data: { 
                query: `
                    query($id: ID!){
                        article(id: $id ) {
                            id
                            title
                            content
                            author {
                                name
                            }
                        }
                    }`,
                    variables: {
                        id: id,
                    },
            },
            withCredentials: true
        });

Setting cors middle inside config/middleware.js file:

  • If the origin is " * " then Strapi server works fine but the frontend throws cors error

  • If I mention origin explicitly as http://localhost:8000 then the server throws an error which is “InternalServerError: http://localhost:1337 is not valid origin”. But, frontend doesn’t throw me cors error anymore and JWT Token is set in the browser’s cookie. However, the main issue which is to fetch a single article remains the same.

Middleware:

module.exports = {
  settings: {
    cors: {
      origin: ['http://localhost:8000'], // throws Internal Server Errror but cors issue is resolved
   // origin: [ " * " ] // doesn't throw Strapi server error but gets cors error on the fronend
    },
  },
};

But now, when I restart the server, it says “InternalServerError: http://localhost:1337 is not a valid origin” And frontend doesn’t throw me cors error anymore.

FrontEnd Repo: https://github.com/purnima-strapi-blogs/gatsby-auth-with-strapi
Backend Repo: https://github.com/purnima-strapi-blogs/strapi-auth-blog-backend

Any idea why it’s throwing a “403 Forbidden" error?

1 Like