'How to secure a REST API with an API key
I'm currently creating a Rest API with NestJS (it's really cool by the way).
In this API, I'm using JWT (Json Web Token) to allow users to log in and view different resources based on their role.
However, I want to implement an API Key system to protect the API itself. I don't want any developer to be able to use my api. I want him to go through this API Key to use my api.
Either by a query in the url : https://domaine.com?api_key=${API_KEY}
or via the header :
GET /v1/some-resource
Host: docmaine.com
Accept: application/json
X-API-KEY: MyAwes0m3API_KeY
Do you have a tutorial, course or a track to advise me?
Solution 1:[1]
Why not create a guard that checks for the validity of that header?
@Injectable()
export class ApiKeyGuard implements CanActivate {
constructor(private readonly apiKeyService: ApiKeyService) {} // made up service for the point of the exmaple
async canActivate(context: ExecutionContext): Promise<boolean> {
const req = context.switchToHttp().getRequest();
const key = req.headers['X-API-KEY'] ?? req.query.api_key; // checks the header, moves to query if null
return this.apiKeyService.isKeyValid(key);
}
}
And now you can use @UseGuards(ApiKeyGuard)
on whatever route, or bind it globally, and you've got some basic authentication up for your server.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Jay McDoniel |