Securely Storing and Transmitting 3rd Party API Keys in AWS Cognito
I am developing an application where users need to provide an API key to a 3rd party service, our app (a serverless app on AWS with a dynamo db) then makes requests to that 3rd party service on behalf of the user. Users are authenticated into our application through an AWS Cognito user pool.
Initially I thought about storing the API key in our db and associating it with the user, when the user makes a request to us we would retrieve the key and make the request to the 3rd party.
Another possible solution would be to store the API key as a custom attribute in cognito, when the user signs up have them enter this. This key would then be transmitted in the id token JWT that cognito gives us after the user logs in, we could then get it and send it on without storing the key in our own DB.
Is this a good idea or a terrible idea ?
Best Approach: Direct Authentication and Short-Lived Tokens
The answer depends on many factors: What is validity period of API keys? What threats you consider? What is the price of different kinds of attacks? What are usability requirements? What risks are acceptable and what are not? Etc.
In your scheme, users have no control of their API keys. There is no guarantee that API keys are used only for the purposes that users approved. There are risks that API keys will be leaked because of weaknesses in your applications (logging of API keys, providing access to user API keys to other applications or to persons that user has not authorized, etc.), and users cannot do anything to prevent it. If user provided an API key to your application and later on wants to prohibit your application to use it, there is no guarantee that your application will really do that, that there is no copy somewhere.
Better approach would be, if the 3rd party service would authenticate the user based on the API key directly, without your application, and would issue user a short-lived token, e.g. with validity of 5 minutes, and user would pass this token to your application. Then user can be sure that after the token expired your application will guaranteed have no access to the 3rd party API in the name of this user.