I am creating SPA with Nest.js and React.js and wanted to use passport JWT authentication but run into a problem. After successful login in browser, 401 Error occurs while trying to access routes protected by JwtAuthGuard, like adding new article or logging out. When trying to add new article or log out after successful login using Insomnia, everything works as intended. Why authentication only works when using Insomnia? Do I need to authorize React using cors and provide credentials?
jwt.strategy.ts:
import { ExtractJwt, Strategy } from "passport-jwt";
import { PassportStrategy } from "@nestjs/passport";
import { Injectable, UnauthorizedException } from "@nestjs/common";
import { UserEntity } from "src/user/entities/user.entity";
export interface JwtPayload {
id: string;
}
function cookieExtractor(req: any): null | string {
return (req && req.cookies) ? (req.cookies?.jwt ?? null) : null
}
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor() {
super({
jwtFromRequest: cookieExtractor,
secretOrKey: process.env.SECRET_OR_KEY,
});
}
async validate(payload: JwtPayload, done: (error: Error, user: UserEntity | boolean) => void) {
if (!payload || !payload.id) {
return done(new UnauthorizedException(), false);
}
const user = await UserEntity.findOne({where: {
currentTokenId: payload.id,
}});
if (!user) {
return done(new UnauthorizedException(), false)
}
done(null, user);
}
}
I've tried changing jwtFromRequest from cookieExtractor to ExtractJwt.fromAuthHeaderAsBearerToken(), but no results.