Home > Software engineering >  Forbidden error fetch API from client to server(vanilla js as client and nestjs as backend)
Forbidden error fetch API from client to server(vanilla js as client and nestjs as backend)

Time:08-02

I have issue with call online API from client. I created nestjs API with httponly credential and when

  • nestjs app hosted in local and client from local it's worked
  • also when nestjs app hosted in online server and client hosted in online server it's worked
  • but when nestjs hosted in online server and client call API from local get forbidden error.

nestjs main.ts:

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { ValidationPipe } from '@nestjs/common';

// eslint-disable-next-line @typescript-eslint/no-var-requires
const cookieSession = require('cookie-session');

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.enableCors({
    credentials:true,
    origin:['http://localhost:3000','http://test.nextu.top']
  });
  app.use(
    cookieSession({
      keys: ['asdasd'],
    }),
  );
  app.useGlobalPipes(new ValidationPipe());
  await app.listen(5072);
}
bootstrap();

client fetch:

const doLogin = async () => {
    const bData = {
        Email: '********',
        Password: '****'
    }
    fetch("http://api.nextu.top:5072/auth/signin", {
        method: "POST",
        body: JSON.stringify(bData),
        headers: {
            "access-control-allow-origin": "*",
            'Content-Type': 'application/json;charset=UTF-8',
        },
        credentials: 'include'
    }).then(res => res.json()).then(data => {
        console.log(data);
        getUserInfo();
    })
}
const getUserInfo = () => {
    fetch('http://api.nextu.top:5072/auth/userinfo', {
        method: 'GET',
        headers: {
            "access-control-allow-origin": "*",
            'Content-Type': 'application/json;charset=UTF-8',
        },
        credentials: 'include'
    }).then(res => res.json()).then(data => console.log(data)).catch(err => console.log(err))
}

doLogin() working fine in each situation getUserInfo() don't work when call from client and nestjs app hosted in online server

  • getUserInfo() has AuthGurd in nestjs
  • getUserInfo() working fine in postman
  • forbiden error : forbiden error

CodePudding user response:

I find a way to solve it: changed from:

   cookieSession({
     keys: ['asdasd']
   }),
 );

to:

  app.use(
    cookieSession({
      keys: ['asdasd'],
      sameSite: 'none'
    }),
  );

and run client and server on https.

  • sameSite: 'none' just work on https mode

CodePudding user response:

You should define on which domain the cookie is set, like so

app.use(express.session({
  cookie: { domain:'.nextu.top'},
}));

Note that the '.' is very important as it tell that cookie can be set on any subdomains of "nextu.top"

It work as expected on dev because your front and back are on the same domain "localhost", the only thing changing is the port, but on prod your front is "test.nextu.top" and back "api.nextu.top" which are not the same and cause your issue

  • Related