Simple and secure custom API Keys using ASP.NET Core #2
Replies: 4 comments 5 replies
-
This article was super helpful. Thank you for sharing. |
Beta Was this translation helpful? Give feedback.
-
thumb up |
Beta Was this translation helpful? Give feedback.
-
Whilst this has been quite useful, the code doesn't actually guarantee the key length and could fail at any time. To demonstrate. Here is a simplified generator based on the above. Fixed to 32 bytes with no prefix.
This is then called by a console app recursively:
After a few minutes, the following result is returned.
As you can see, at least one of the keys generated was only 30 characters long, but the examples above substring to 33 characters. This would cause an IndexOutOfRange exception. The max length will always be 43 as the 32 bytes converted to Base64 always ends with an '=' which is removed. The question is how do we deal with this? We could check the length and regenerate, but if we were really unlucky it could take a few attempts before we found a valid key. This could introduce an unwanted performance overhead. Or how about, if the length is too short, we keep the old key but add a new one to the end of it. We are more likely then to have an adequately long key on the first attempt. Let's look at the modified code:
We now know that it won't return anything that's less than 33 characters long, but we'll run the console app again anyway.
Now we can add the substring and be sure that we always get 33 characters returned. |
Beta Was this translation helpful? Give feedback.
-
Great article! Couple questions... I need to store API keys in the database and fetch them. Do you prefer storing the API key in the cache for X amount of time instead of hitting the db per call? Say, 5 minutes. After 5 mins a db call would be made per key I am using identity. Is their a best approach to building a relationship between ApiKey and IdentityUser? That way we can validate and restrict access to certain route data? Such as.. we don't want customer1 accessing the api to access customer2 data and so fourth. Would this be better done with claims in the pipeline? |
Beta Was this translation helpful? Give feedback.
-
Simple and secure custom API Keys using ASP.NET Core
https://www.camiloterevinto.com/post/simple-and-secure-api-keys-using-asp-net-core.html
Beta Was this translation helpful? Give feedback.
All reactions