authenticated-socket-io.adapter.ts
export class AuthenticatedSocketIoAdapter extends IoAdapter {
private readonly authService: AuthService;
constructor(private app: INestApplicationContext) {
super(app);
this.authService = this.app.get(AuthService);
}
createIOServer(port: number, options?: SocketIO.ServerOptions): any {
options.allowRequest = async (request, allowFunction) => {
const { authorized, errorMessage } = await this.check(parse(request?.headers?.cookie || '').jwt, [UserRole.ADMIN]);
if (!authorized) {
return allowFunction(errorMessage, false);
}
return allowFunction(null, true);
};
return super.createIOServer(port, options);
}
main.ts
const app = await NestFactory.create(AppModule);
app.enableCors({
origin: ['http://localhost:4200'],
credentials: true
});
app.use(cookieParser());
app.use(csurf({ cookie: true }));
app.useWebSocketAdapter(new AuthenticatedSocketIoAdapter(app));
When authorization is successful: authorization is successful
When authorization fails: authorization fails
Found the problem: the function from socket io handling the error message:
here the "code" param will be the one I pass in here "allowFunction(errorMessage, false)" That value has to be one of "0", "1", "2", "3" or "4", otherwise the isForbidden will be false, thus not setting the 'Access-Control-Allow-Credentials' header.
Hope this helps someone one day.