Reza Rahmati
1 min readJul 29, 2020

--

Thanks for article, there are some points that can be fixed to have better article.

If AuthService is returning promise, the code is not working out of the box, so changes are required ( I tried to create PR on your github repo but branching is not permitted)

```

export class AuthMiddleware implements NestMiddleware {

use(req: any, res: any, next: (...args) => void) {

passport.authenticate(

"headerapikey",

{ session: false, failureRedirect: "/api/unauthorized" },

value => {

if (value) {

next();

} else {

next(new UnauthorizedException());

}

},

)(req, res, next);

}

}

```

```

export class ApiKeyStrategy extends PassportStrategy(HeaderAPIKeyStrategy) {

constructor(private authService: AuthService) {

super({ header: "apiKey", prefix: "" }, true, async (apikey, done,) => {

const checkKey = await authService.validateApiKey(apikey);

if (!checkKey) {

return done(false);

}

return done(true);

});

}

}

```

in authService

```

async validateApiKey(apiKey: string): Promise<string> {

return new Promise<string>((resolve, reject) => {

resolve(this.apiKeys.find(apiK => apiKey === apiK));

});

}

```

--

--

No responses yet