Hello, I have a problem with CORS and I think this is right community to get help.

When I use this code:

import { LemmyHttp } from 'lemmy-js-client';
const client = new LemmyHttp('https://lemmy.ml');
const { posts } = await client.getPosts({
    limit: 10,
    page: 1
});

to get posts from lemmy.ml (using lemmy-js-client), I get:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://lemmy.ml/api/v3/post/list?limit=10&page=1. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing). Status code: 400.

I have tried to add header like this:

const client = new LemmyHttp('https://lemmy.ml', {
    headers: {
        'Access-Control-Allow-Origin': '*'
    }
});

but result is the same.

Can someone help me with this?

  • data0@programming.dev
    link
    fedilink
    English
    arrow-up
    1
    ·
    1 year ago

    Setting it to * will prevent the browser from including credentials in the request (cookies). Dynamically setting it to the origin of the requesting client effectively does the same but also allows for using credentials.

    • RonSijm@programming.dev
      link
      fedilink
      English
      arrow-up
      1
      ·
      1 year ago

      I don’t think it would be a very good implementation to just let any site dynamically request to be allowed by CORS, including with credentials… A malicious site could do way too many things on the users behave

      A possible solution would be something like how reddit or github do it - have the user first accept an “Allow third party app / website to access my account” - and after that, add those sites to the Access-Control-Allow-Origin

        • RonSijm@programming.dev
          link
          fedilink
          English
          arrow-up
          1
          ·
          1 year ago

          Well I’m not expert on CORS, nor with the Lemmy API, so it’s probably better to read about CORS exploits in more detailed articles… https://www.freecodecamp.org/news/exploiting-cors-guide-to-pentesting/ for example

          It seems Lemmy is storing a JWT in the cookiejar, so with Access-Control-Allow-Credentials:true and the domain in Access-Control-Allow-Origin a site should be able to do authenticated get requests on a users behave with the JWT, and access personal data.

          The “GET https://programming.dev/api/v3/private_message/” endpoint for example, would let someone read the private messages someone has send/received

          I’m not sure whether someone could do POST requests and add credentials from the cookiejar this way though