Middleware for authentication using a token provider. This middleware validates the authentication token by comparing it with the defined protected routes. Additionally, it uses a global logger to record information about unauthorized requests.
npm install auth-interceptor-lib2Middleware for authentication using a token provider. This middleware validates the authentication token by comparing it with the defined protected routes. Additionally, it uses a global logger to record information about unauthorized requests.
AuthProviderInterface CognitoProvider.LoggerInterface 1. Initializes the global logger using LoggerSingleton.initialize(ConsoleLogger).
2. Checks if the current route is a public route. If it is, access is allowed directly.
3. Validates the token provided in the authorization header.
4. If the token is invalid:
- Uses the logger to record the unauthorized attempt.
- Returns a response with the status 401 Unauthorized.
5. If the token is valid:
- Allows the request to continue by calling next().
A middleware function compatible with frameworks like Express.
``typescript
import ConsoleLogger from './logger/console.logger';
import express from 'express';
import AuthInterceptor, { CognitoProvider } from 'auth-interceptor-lib';
const app = express();
// Initialize the global logger, type LoggerInterface exported by: import { LoggerInterface } from 'auth-interceptor-lib'
const logger = new ConsoleLogger();
// Initialize the AuthInterceptor with the TokenProvider and Logger
const authMiddleware = AuthInterceptor(new CognitoProvider(), logger);
// Use the middleware in the application
app.use(authMiddleware);
`
``typescript
import { MiddlewareConsumer, Module, NestModule } from '@nestjs/common'
import AuthProvider, { CognitoProvider } from 'auth-interceptor-lib';
import { ConsoleLogger } from '@/@core/infra/middlewares/logger';
@Module({
imports: [],
providers: [],
})
export class AppModule implements NestModule {
configure(consumer: MiddlewareConsumer) {
const userPoolId = process.env.USER_POOL_ID || '';
if (!userPoolId) {
throw new Error('USER_POOL_ID is not set in the environment variables.');
}
consumer
.apply(AuthProvider(new CognitoProvider(userPoolId), new ConsoleLogger()))
.forRoutes('*');
}
}