#JWT Issue

3 messages · Page 1 of 1 (latest)

leaden merlin
#

Hi all.. I've a problem with my backend (NestJS server). I've uploaded my project into a Container and now I have the problem that my req.headers looks different then on localhost development.

// prod

{
  host: '<url>:4005',
  connection: 'keep-alive',
  pragma: 'no-cache',
  'cache-control': 'no-cache',
  'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36',
  accept: 'application/json, text/plain, */*',
  origin: 'http://<url>:3005',
  referer: 'http://<url>:3005/',
  'accept-encoding': 'gzip, deflate',
  'accept-language': 'de-DE,de;q=0.9,en-US;q=0.8,en;q=0.7'
}



// localhost

{
  host: 'localhost:4000',
  connection: 'keep-alive',
  pragma: 'no-cache',
  'cache-control': 'no-cache',
  'sec-ch-ua-platform': '"Windows"',
  'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36',
  accept: 'application/json, text/plain, */*',
  'sec-ch-ua': '"Chromium";v="130", "Google Chrome";v="130", "Not?A_Brand";v="99"',
  'sec-ch-ua-mobile': '?0',
  origin: 'http://localhost:3005',
  'sec-fetch-site': 'same-site',
  'sec-fetch-mode': 'cors',
  'sec-fetch-dest': 'empty',
  referer: 'http://localhost:3005/',
  'accept-encoding': 'gzip, deflate, br, zstd',
  'accept-language': 'de-DE,de;q=0.9,en-US;q=0.8,en;q=0.7',
  cookie: '<token>'
}
cyan jackalBOT
#

Hey there! 👋

Thanks for reaching out. Please elaborate further on your problem. The more details you can provide, the better we'll be able to help you.

If applicable, please share any relevant code snippets or error messages you've encountered. Please provide a minimal reproduction repository or steps to reproduce the issue. It would greatly assist us in understanding and resolving the problem.

We're here to help, so feel free to provide more context, and we'll do our best to assist you further!

leaden merlin
#

This are all the steps it takes ...

login:

// frontend - nuxt3

async login() {
  try {
    const { $config } = useNuxtApp();
    const login = await axios.post(`${$config.public.backendServer}/api/auth/login`, {
      username: this.username,
      password: this.password,
    }, {withCredentials: true});

    if (login.status === 200) {
      const { access_token } = login.data; // get access token

      if (access_token) {
        localStorage.setItem('token', access_token); // save token
      }
      this.$router.push('/dashboard');
    }
  } catch (error) {
    this.errorMessage = translate('error.login');
  }
}
// backend nest

@Post('login')
async loginUser(@Body() body: { username: string; password: string }, @Res() res: Response) {
    const { username, password } = body;

    const account: Account | null = await this.accountsService.findUserByUsername(username);

    if (!account) {
        return res.status(401).json({ message: 'Invalid credentials' });
    }

    const passwordMatches: boolean = bcrypt.compareSync(password, account.passwordHash);

    if (!passwordMatches) {
        return res.status(401).json({ message: 'Invalid credentials' });
    }

    const jwt: string = this.jwtService.sign({
        username: account.username,
        role: account.role,
        id: account.id
    });
    res.cookie('dtn_jwt', jwt, {
        httpOnly: true,
        secure: true,
        maxAge: 10 * 60 * 1000
    });

    return res.status(200).json({ message: 'Login successful', account: account, access_token: jwt }); // ✅ goes here
}
// frontend - nuxt3 [ /middleware/routeProtection.ts ]

async function isUserAuthenticated(): Promise<any> {
    const { user, setUser } = useUserStore();
    if (user.value) {
        return { user: user.value };
    }

    try {
        const { $config } = useNuxtApp();
        // ✅ sends request to the backend [ nest ]
        const response = await axios.get(`${$config.public.backendServer}/api/auth/verify`, { withCredentials: true });
        user.value = response.data.user;
        return { user: response.data.user };
    } catch (error) {
        return { user: null };
    }
}
// backend - nest

@Get('verify')
async verifyToken(@Req() req: Request, @Res() res: Response) {
    try {
        const token = req.headers.cookie.split('=')[1]; // ❌ finds no .cookie? and goes into catch()
        if (!token) {
            return res.status(401).json({ message: 'Not authenticated' });
        }

        const decoded = this.jwtService.verify(token);
        const user: Account | null = await this.accountsService.findUserByUsername(decoded.username);

        if (!user) {
            return res.status(401).json({ message: 'User not found' });
        }

        return res.status(200).json({ user });
    } catch (error) {
        return res.status(401).json({ message: 'Invalid token' });
    }
}