Last Updated on May 17, 2023 by Aram
When it comes to Web API security, it is important that you would be aware of all the measures, configurations and code that you should apply to enhance and boost the security, that is; To make sure no bots can access your APIs, no attackers can wreak havoc to your website and servers, or malicious users can steal your customer information.
Also you need to make sure that you deny access for any unauthenticated user, and forbid any unauthorized access to resources that are not intended for a specific user.
You might not be able to completely secure your APIs, but the more enhancements you apply, the better it will become.
Even though this article is about general Web API security, but I will be referencing many blog posts with topics related to ASP.NET Core Web API Security.
So here are the tips to boost your Web API security:
Use API Key, share it with the client once, and store its hash at your side
You should never leave your Web API open without any sort of authentication for whoever is trying to access your API.
So to have least requirement for your Web API security, you should have an authentication mechanism where you expect an API key in the headers or a basic authentication with username and password base64 encoded, it is true that this isn’t the best way to protect the APIs, since you will have to verify the API key or the basic authorization credentials each time the APIs are called, and the fact that they are sent over the http call make them prone to network sniffing and spoofing especially if they are sent over plain http or weak https ciphers.
But still you will get the least required protection for your API so you can deny anyone not having the correct key or the basic authorization from accessing your API.
Also hashing the API Keys with a strong hashing function is recommended, so that whenever you store it at your side, not to store it in a plain format, just similar approach to the passwords storage security.
We will discuss the hashing functions later in this article.
Check my article here to learn how to Secure ASP.NET Core Web API using API Key Authentication.
Use Cryptographically Secure Random Numbers for API Keys
Whenever you want to generate an API key for a client, don’t just go and generate a simple random number or a text that can be easily cracked.
If you are building Web API using ASP.NET Core, starting from .NET 6, you can easily access the RandomNumberGenerator class and use the GetBytes method with a value like 32 or 64 and it will generate a cryptographically secure random number for you which you can use as an API Key and provide it to your client to call your APIs.
Take a look a function that generates a cryptographically secure API Key
1
2
3
4
5
6
7
8
|
public static async Task<string> GenerateApiKey()
{
var secureRandomBytes = new byte[32];
using var randomNumberGenerator = RandomNumberGenerator.Create();
await Task.Run(() => randomNumberGenerator.GetBytes(secureRandomBytes));
var apiKey = Convert.ToBase64String(secureRandomBytes);
return apiKey;
}
|
Generated Api Key Sample
1 |
"y0gSDYmGW6JuukqX2FU+sa6d3NAAm3Ayk2aAGRwDnh4=" |
Rotate your API keys
It is recommended that you expire or refresh the API Keys every once and while with a new API key generated to your client while invalidating or removing the older ones, this way you can make sure that if a non-authorized person gain access to a previous API key won’t be able to access your APIs.
You can keep the hashed values of your API keys in a database and manage their expiry. Also you can have an admin UI portal so that it will be easier for any account admin to manage the keys.
Here is a good article explaining about Key Rotation.
White-list IPs
Don’t leave your APIs open for all, make sure to white-list the IPs or domains that are going to access your APIs and deny anything unlisted from accessing your APIS.
White-listing can be implemented via several layers, either through your domain or hosting provider which most of them provide the means to whitelist IP Addresses that can access your site or APIs.
Or you can add the whitelist via .htaccess file for Apache or Web.Config for IIS servers.
And if you are using a cloud provider, then you will definitely have the white-listing capability through the API Gateway.
Check this article to learn more about Whitelisting.
Implement JWT Authentication with Refresh Tokens
Now to have a better Web API security and more efficient solution than the API Key authentication, you can use the JWT authentication to secure your APIs. This is when you generate a JSON Web Token and provide it for your client , and then they can use it in the subsequent API calls that require the Authorization header to provided as Bearer token. with JWT you can guarantee that your API call is correct, authentic and from the correct authorized user to access the API.
JWTs are meant to be short lived and dispensable for only the duration it was meant to be created, so that the token that you generate for
Don’t reinvent the wheel, use the ASP.NET Core JwtBearer Nuget package to guarantee a proper and secure generation of your tokens
I have a comprehensive tutorial that will teach you how to Apply JWT Access Tokens and Refresh Tokens in ASP.NET Core Web API 6
Also, you should implement policy-based authentication, so that you can fine-grain the authorizations you allow for your users based on their roles or specific requirements.
Check my other article that explains how to use JWT authentication with policies and requirements.
Always Apply Server Side Validation and Sanitization
Never rely on your front-end to validate the user input.
This is a very basic but rather essential part that you need to take care of, being an API or backend developer, which means that you always have to do validation for all the input data that is reaching your APIs, never trust or rely on your front end to do validation, even if the frontend was applying very strict and detailed validation on every single field.
Always remember that the frontend is residing at the client’s side or browser, so using browser or other software tools, they can easily bypass the frontend validation and manipulate the data, this can provide the perfect environment for your attackers to breed malicious scripts and code to attack your APIs and backend including the database.
One of the most commonly known security issues related to data and validation is Cross-Site Scripting XSS, where the malicious user would inject a script to your input forms in your site, all the way to your APIS, and so other user will be seeing this script when loading the content at their side.
For this case you should always validate the user’s input at the server side as well as, and more importantly to prevent XSS, to sanitize your input for html tags or scripts.
Again, don’t reinvent the wheel and write your own html or script sanitizer, each technology has plenty of ready libraries to use to sanitize and encode the user’s input. If your API is under .NET technology (old or new version) ASP.NET Core Web API, you can use the Html sanitizer library in ASP.NET Core Web API to handle this part.
Check this article by OWASP to learn more about XSS.
And check the following article, by Microsoft, to read about how to Prevent Cross-Site Scripting (XSS) in ASP.NET Core.
Also applying server-side validation can guarantee data integrity and that no front-end client can easily submit data without going through your validation first.
Implement OAuth 2.0 and OpenID Connect
To implement OAuth 2.0 security protocol to your APIs, you can rely on a well-known identity provider that will the major part of provisioning and handing the complexity of generating, validation and managing the authentication/authorization.
There are several examples of great identity providers like identityServer4 (now part of DuendeSoftware) or auth0 by okta
There are different flows supported by OAuth 2.0 protocol, each specializing in a specific use case or implementation, so the flows vary between Native Mobile Apps, SPA Web Apps, Desktop Apps, Service to service clients.
You can read and learn more about OAuth 2.0 from this site.
OpenID Connect extends the OAuth 2.0 protocol to authenticate the user’s identity and enable them to access different providers via Single-Sign on.
With OpenID Connect the authorization server generates an ID Token and sends it back to the client which it can use to verify the user’s identity.
Check the following article to learn more about OpenID Connect.
Force https, and don’t use plain http
Once you are ready to deploy your changes to a server (to go live), you need to enforce the usage of https, you should not allow any request/response to happen over plain http.
This can be easily enabled by a single line of configuration in your Program.cs file:
1 |
app.UseHttpsRedirection();
|
Use a Valid and strong SSL/TLS certificate
Your website as well as your Web API show always use an SSL/TLS certificate that is valid and strong. And make sure it is based on TLS 1.2 , since the previous versions TLS 1.0 and 1.1 have known vulnerabilities and only available to support older browsers and sites.
So you should opt to upgrade your hosting environment as well as your clients to TLS 1.2 or 1.3. Check this Microsoft article to learn more about how to ensure correct upgrade.
You can read further about SSL and TLS in this Wikipedia article.
Your browser will notify you and your users about your site being secure or not, and if the certificate is valid or not, via the secure lock icon, which anyone can click to get more details about the site’s security.
You can always purchase or renew your SSL/TLS certificate from your hosting provider’s admin panel, make sure to contact their support if you have any doubts or issues with your certificate.
Usually most hosting providers give you a 3-months free SSL/TLS certificate that you can use to test and have your site running on a secure channel, and then you can purchase one and apply it on your site.
Implement a Rate Limiter
A rate limiter’s function is to throttle the requests to your APIs for a specified number of requests within a specified time or duration.
Implementing a rate limiter on your Web APIs, is greatly important to limit the usage of your APIs, and this is particularly helpful to decrease the damage that might happen from a DDOS attack which can wreck havoc to your servers and affect your business, the following link can you help learn more about Rate Limiting
Now, in ASP.NET Core Web API 7, you can use the Rate Limiter Middleware to apply rate limiting from the code itself, as it is now a built-in feature in .NET 7.
You can check this blog post about implementing the RateLimiter in ASP.NET Core Web API 7
Implement a Web Application Firewall
A Web Application Firewall helps monitor, detect, filter, prevent malicious traffic like bot or fraudulent attacks on your APIs.
Many of the hosting providers offer you, free or paid, web application firewall services and there are many sophisticate and advanced firewalls that can smartly protect your Web API or website.
This can also help in mitigating and deterring the risk of DDOS Attacks on your Web API in a significant way.
Cloudflare has an extensive documentation about Web Application Firewall and in fact they provide robust firewall implementations alongside their hosting services.
Run a security scan with a 3rd Party Security Service
It is always great to have a 3rd eye to look into the security of your Web APIs, sometimes you might be missing to implement a policy that you are not aware of, or underestimating a tweak in your security implementation, thinking that no one might notice it.
But having a dedicated and professional security entity run a comprehensive scan on your Web APIs along with its hosting environment might be greatly beneficial and even crucial to your business.
There are so many great website security scanners online that provide comprehensive security scans for your online business and can detect many security issues.
If you are in the field of security, enthusiast about performing the security test yourself, or just want to expand your security testing and best practices knowledge, you can instead learn the OWASP security testing guidelines, there is a huge documentation and learning material under this Github repository.
More Security Tips?
Implement a Captcha on your frontend and do API-Side Validation
Having a captcha can greatly reduce the number of fraudulent and bot requests to your APIs, which will enhance your overall site security and allow only your real users interact with your APIs.
There are a numerous captcha services that you can easily integrate with, and my recommendation would go for Google reCaptcha V3 , as it provides you with a score representing the possibility of whether a request to your API is from a real user or a bot.
Check my tutorial on how you can implement a server-side validation for Google reCaptcha v3 using ASP.NET Core Web API in .NET 6
Store your passwords Hashed using Cryptographically Secure Hashing Functions
Never store a password in plain text, I know this a very trivial and basic rule, but still there are many out-there saving users passwords in a plain text.
Always make sure to hash the password before saving it.
Choosing the right hashing function is also crucial, for example you shouldn’t use md5 to hash password as it has been broken or cracked since a long time ago.
In fact, there are several online massive databases that caches ‘cracked’ passwords, check hashes.com.
The general recommendation nowadays is to use a cryptographically secure hashing functions.
There are different types of hashing functions that implement Key derivation functions.
And if you are going to save the password hash of your users, then it is greatly recommended that you use a Password-based Key Derivative Function with a large number of iterations. The latest recommendation by OWASP is to use 310,000 iterations and the standard password salt to be 64-bit or 128-bit will be even better as recommended by the IETF. Read here to learn more.
Even though it is widely used nowadays, PbKDF 2 is prone against the modern parallel computing power of GPUs and specialty Hardware like ASIC that are currently used for crypto mining, this is because of its relatively small RAM requirements.
The better hashing functions that are recommended in the key derivation functions category: are scrypt, Argon2id, Balloon Hashing. These can stand firm against the GPU and ASIC attacks. These have similar approaches to implementation to PbKDF 2.
Another equally solid hashing function that uses the key stretching and blowfish methodologies is bcrypt.
Summary
Security is a massively critical topic that you always need to keep in mind in order to build secure and reliable Web API services. You need to have Secure Web API that can hold firmly against the countless efforts from the malicious users and spammers to ruin your online businesses and websites.
In this article we learned about the different tips that we can apply to have secure web API and mainly we discussed about securing ASP.NET Core Web API. I think many of the mentioned tips and topics cover other technologies that you can use to build and secure Web API.
If you like this article, please share it using the social media buttons.
And let me know down in the comments if you have more tips or measures to share regarding Web API security.
Further Readings
This is a wide topic that requires lots of reading and learning, so here are some interesting and good reads about Web API security:
- OWASP API Security Project
- Best practices for REST API security: Authentication and authorization
- Make secure .NET Microservices and Web Applications
Articles from my Blog
- A Quick Guide to Learn ASP.NET Core Web API
- Secure Angular Site using JWT Authentication with ASP.NET Core Web API
- Apply JWT Access Tokens and Refresh Tokens in ASP.NET Core Web API 6
- Google reCAPTCHA v3 Server Verification in ASP.NET Core Web API
- Exception Handling and Logging in ASP.NET Core Web API
Bonus
Enjoy this wonderful masterpiece sonata by Mozart beautifully played by Christoph Eschenbach
Mozart: Piano Sonata No. 10 in C major K 330 – Christoph Eschenbach, 1970 – DG 2561 069