Added cors middleware

This commit is contained in:
Igor Hrenowitsch Propisnov 2024-05-20 09:39:34 +02:00
parent 5d2b868a3d
commit c0accbbf34
2 changed files with 43 additions and 1 deletions

View File

@ -8,6 +8,7 @@ import { SecurityHeadersMiddleware } from './middleware/security-middleware/secu
import { HttpsRedirectMiddleware } from './middleware/https-middlware/https-redirect.middleware';
import { AuthModule } from './modules/auth-module/auth.module';
import { AccessTokenGuard } from './modules/auth-module/common/guards';
import { CorsMiddleware } from './middleware/cors-middleware/cors.middlware';
@Module({
imports: [
@ -24,7 +25,12 @@ export class AppModule {
configure(consumer: MiddlewareConsumer) {
consumer
// TODO: Redirect via Reverse Proxy all HTTP requests to HTTPS
.apply(CspMiddleware, SecurityHeadersMiddleware, HttpsRedirectMiddleware)
.apply(
CspMiddleware,
SecurityHeadersMiddleware,
HttpsRedirectMiddleware,
CorsMiddleware
)
.forRoutes({ path: '*', method: RequestMethod.ALL });
}
}

View File

@ -0,0 +1,36 @@
import { Injectable, NestMiddleware } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { Request, Response, NextFunction } from 'express';
@Injectable()
export class CorsMiddleware implements NestMiddleware {
constructor(private readonly configService: ConfigService) {}
public use(req: Request, res: Response, next: NextFunction): void {
if (this.configService.get<string>('NODE_ENV') === 'production') {
const allowedOrigin = this.configService.get<string>('CORS_ALLOW_ORIGIN');
if (req.headers.origin === allowedOrigin) {
res.header('Access-Control-Allow-Origin', allowedOrigin);
res.header(
'Access-Control-Allow-Methods',
this.configService.get<string>('CORS_ALLOW_METHODS')
);
res.header(
'Access-Control-Allow-Headers',
this.configService.get<string>('CORS_ALLOW_HEADERS')
);
if (req.method === 'OPTIONS') {
res.sendStatus(200);
} else {
next();
}
} else {
res.status(403).json({ message: 'Forbidden' });
}
} else {
next();
}
}
}