My plan for securing web app: are there holes? - security

I've developed a CodeIgniter project tracking app for a client which lives at a public URL but is used privately. It includes a simple REST API, used exclusively for a Dashboard widget and Cocoa menu bar app though it will grow later.
Originally designed for a small team, the app is going to be used more broadly within the (large) company. My plan to grow and secure it...
Evaluate traffic needs, project resource usage, and scale hosting accordingly.
Rely exclusively on HTTPS and purchase a decent SSL certificate.
Require authentication for the REST API.
Actively monitor for abuse and have a blacklist (or several) in place.
Are there any obvious issues that need to be addressed or best practices to follow for a private/public app such as this?

It's a rather broad question. There are several complicated facets.
SSL is good; think about enabling CI's CSFR protection
Lock down your server. Close ports like email and ftp if you don't need them. Google for tutorials or ask specific questions based on your OS.
A great guide of form-based auth stuff: The definitive guide to form-based website authentication
Make sure your permissions are how you want them. e.g. keep private things private. Design a policy for granting and revoking access.

Related

How to manage API keys for npm packages that require key on the client-side code?

It's a hot debate on how to securely handle API Keys.
And almost all of us know that it's the best solution to have them stored on the server side, and never exposed in client-side applications.
Our clients can send requests to our APIs, and our APIs can act as proxy to send/receive data to/from the third party API and return the response back to our client.
However, there are some third party SDKs that you can integrate into your client-side app and they also have their API Keys.
For example, Zoom has SDKs for Web, Android, iOS, Windows, etc., or Pusher has Pusher Key.
When you want to work with these libraries, you CAN NOT send request to your API to hide API Key. You have to initialize these libraries in your client-side code (react for example).
An example from Zoom to join a meeting inside your web app:
client.join({
apiKey: apiKey,
signature: signature,
meetingNumber: meetingNumber,
password: password,
userName: userName
})
What are the best practices to secure API Keys for client-side SDKs and libraries?
Your Problem
When you want to work with these libraries, you CAN NOT send request to your API to hide API Key. You have to initialize these libraries in your client-side code (react for example).
What are the best practices to secure API Keys for client-side SDKs and libraries?
Well you found yourself a very hard problem to solve (but not impossible to some degree), because once the API Key is in the client side it's public. So, no matter how well you hide it will always be possible to retrieve it on a browser or mobile app.
Web Apps
On browsers is very trivial to get hands on the API key, just open the developer tools and in the network tab look for the request you are interested in extracting the API key and click on it to inspect the request headers.
Mobile Apps
In mobile devices id more laborious to extract an API key from a mobile app, but not that difficult has many may think.
JNI/NDK - Hide API Key in Native C Code
For example, you can hide the the API key in C native code via JNI/NDK:
Using Android Studio 2.2 and higher, you can use the NDK to compile C and C++ code into a native library and package it into your APK using Gradle, the IDE's integrated build system. Your Java code can then call functions in your native library through the Java Native Interface (JNI) framework.
This approach aims to protect the AP/i key from being extracted from your mobile app binary via static binary analysis, as exemplified in this repo and blog post I wrote:
During this article we will use the Android Hide Secrets research repository that is a dummy mobile app with API keys hidden using several different techniques.
Extract the API Key hidden in Native C Code with a MitM Attack
In the above blog post the API key hidden in the source code with JNI/NDK interface was not possible to extract via static binary analysis, but it was easy to extract with a MitM attack as I demo in the article Steal that Api Key with a Man in the Middle Attack:
In order to help to demonstrate how to steal an API key, I have built and released in Github the Currency Converter Demo app for Android, which uses the same JNI/NDK technique we used in the earlier Android Hide Secrets app to hide the API key.
So, in this article you will learn how to setup and run a MitM attack to intercept https traffic in a mobile device under your control, so that you can steal the API key. Finally, you will see at a high level how MitM attacks can be mitigated.
Prevent MitM Attack with Certificate Pinning
The first thing one can do to prevent a MitM attack is to use certificate pinning and I wrote about how to do it in the article Securing HTTPS with Certificate Pinning:
In order to demonstrate how to use certificate pinning for protecting the https traffic between your mobile app and your API server, we will use the same Currency Converter Demo mobile app that I used in the previous article.
In this article we will learn what certificate pinning is, when to use it, how to implement it in an Android app, and how it can prevent a MitM attack.
I see the smile on your face now, but will not be for long because certificate pinning can be bypassed.
Bypassing Certificate Pinning
You can do it repackaging the mobile app without pinning or by using an instrumentation framework at runtime to disable it.
Repackaging the mobile app to bypass pinning
This is not hard to achieve when you have the correct tools and open source is full of them. I wrote how to do it in the article Bypassing Certificate Pinning
In this article you will learn how to repackage a mobile app in order to make it trust custom ssl certificates. This will allow us to bypass certificate pinning.
Using an Instrumentation Framework to bypass pinning
This is my preferred method and my instrumentation framework of preference is Frida, and guess what, I also have an article on it with the title How to Bypass Certificate Pinning with Frida on an Android App to show you how to do it:
Today I will show how to use the Frida instrumentation framework to hook into the mobile app at runtime and instrument the code in order to perform a successful MitM attack even when the mobile app has implemented certificate pinning.
Bypassing certificate pinning is not too hard, just a little laborious, and allows an attacker to understand in detail how a mobile app communicates with its API, and then use that same knowledge to automate attacks or build other services around it.
Possible Solutions
You may employ an array of different approaches and techniques to defend your API server and mobile app, but give preference to use a security solution that spans both the mobile/web app and API server.
The solution(s) to use will depend on your threat model, your budget and your resources and I will give you below pointers to some options.
For Mobile Apps
I recommend you to read this answer I gave to the question How to secure an API REST for mobile app?, especially the sections Hardening and Shielding the Mobile App, Securing the API Server and A Possible Better Solution.
For Web Apps
You can learn some useful techniques to help your API backend to try to respond only to requests coming from what you expect, your genuine web app, and to do so I invite you to read my answer to the question Secure api data from calls out of the app, especially the section dedicated to Defending the API Server.
Do You Want To Go The Extra Mile?
In any response to a security question I always like to reference the excellent work from the OWASP foundation.
For APIS
OWASP API Security Top 10
The OWASP API Security Project seeks to provide value to software developers and security assessors by underscoring the potential risks in insecure APIs, and illustrating how these risks may be mitigated. In order to facilitate this goal, the OWASP API Security Project will create and maintain a Top 10 API Security Risks document, as well as a documentation portal for best practices when creating or assessing APIs.
For Mobile Apps
OWASP Mobile Security Project - Top 10 risks
The OWASP Mobile Security Project is a centralized resource intended to give developers and security teams the resources they need to build and maintain secure mobile applications. Through the project, our goal is to classify mobile security risks and provide developmental controls to reduce their impact or likelihood of exploitation.
OWASP - Mobile Security Testing Guide:
The Mobile Security Testing Guide (MSTG) is a comprehensive manual for mobile app security development, testing and reverse engineering.
For Web Apps
The Web Security Testing Guide:
The OWASP Web Security Testing Guide includes a "best practice" penetration testing framework which users can implement in their own organizations and a "low level" penetration testing guide that describes techniques for testing most common web application and web service security issues.
What do you want to secure exactly? I assume you want to avoid someone from misusing your API key, but you should ask yourself, from what security risk or threat do you want to protect?
You should also understand what kind of API key are you dealing with, as not all of them are intended for the same use-case and could 'offer' different level of security.
For example, you could have an API key in the form of a personal access token (in GitHub, for instance), where the token is directly tied to a user/employee and should be considered a secret, or you may have an API key in the form of a machine token that it's tied to your organization or your repository (still in GitHub, for instance) and that can be configured with different permissions (read-only, read-write).
It is also possible that the API key can be configured and restricted to some clients, according to the possibility of the client itself.
For example some of the Google Maps APIs allow you to configure a trusted origin that it is allowed to perform requests using your specific API key, however this protection works by checking the referrer header of the request and it could be spoofed by arbitrary clients. Browsers should still honor the convention and send the correct referrer, protecting you from people that want to use your API key on their website.
Another example in the mobile application world: there are some vendors that allow you to bind your API key to a specific package name that it is then validated at runtime by the vendor's SDK, however this kind of protection is usually as a licensing mechanism, to avoid developers to configure for free an SDK with a leaked API key.
Most generally, if the API key is intended to be used on public clients, then the developers of the API already considered the threat of having this leaked and you should not have a repercussion. This means that you will be covered from huge API usage billings or from rate-limit/usage quota limit (but better check yourself!).
The general rule is to always check the developer's documentation of the application you're trying to configure and see how to create a proper API key for your use-case and if it's fine for you to have this 'leaked' from your client. Additionally, if the API key allows you to configure permission, remember to follow the Principle of Least Privilege.
Another golden rule is to always threat model your implementation:
What are the capabilities of the API key?
What is the worst an attacker can do if they access the API key?
Am I protecting myself from these threat? How? Can I put more controls or monitors on back-end side (i.e. notification on high usage, etc)?
Finally, if your API key need to be kept secret, then you must not use this on a public client, no matter how hidden it is. There will always be at least one person able to retrieve it (And don't rely on client-side check either!). In this case what you want is probably to have your own back-end service responsible both for querying the APIs using the secret API key and for authenticating and authorizing your customers/users, and also to implement additional security measures like rate limit.
One thing I found very helpful is to always document any generated/used API key and its capabilities along with the threats of having them leaked and some preventive measures to minimize the risk.

Information in .well-known/openid-configuration page is exposed to internet, a security concern?

I am doing a security scan of a client and observed they have implemented OpenID. While reading up I came to know about this URL .well-known/openid-configuration, which has good amount of information(endpoints-{authorize, connect, userinfo, jwks}, scopes etc) exposed to public.
I have 2 questions here:
Exposing these info to public is a security concern ? Isn't there any way to make available only to the required user.
I am new to OpenID connect, a simple and good article to implement Custom OpenID server.
It is pretty standard to expose metadata if needed by the outside world, eg mobile apps. Its main usage is by security libraries in client apps, to look up other endpoints, for authorization and token issuing.
If you don't have internet clients then some providers will allow you to turn the endpoint off, or to only expose it over an internal network. It is usual to avoid exposing more sensitive data such as custom claims and scopes.
Rather than implement an OpenID Server it is usual to use a free one based on standards, then focus on integrating UIs and APIs. There is plenty of work there, since OAuth is very architectural.
At Curity we have a full featured free version and the quick way to get started is via the docker tutorial. Then log into the developer portal and download a license file.
After running the install you can browse to these URLs. Then focus on integrating your apps:,
http://localhost:6749/admin
http://localhost:8443/oauth/v2/oauth-anonymous/.well-known/openid-configuration
Alternatively choose another provider - and follow the same approach of using large building blocks.

How to secure a simple Node.js RESTful API

i'm developing a simple news App where users can see latest news without login, i don't know how to make it secure, i have read that JWT with OAuth2 should be used but from my understanding the user have to login into a provider to get the token but i want users to be able to read data without login.
my concern right now is how to prevent other people from using my API in their apps, i'm concerned also about DoS attacks.
THE CHALLENGE
i'm developing a simple news App where users can see latest news without login, i don't know how to make it secure
Well you bought yourself a really huge challenge, because even if you required your users to login, it would continue to be a huge challenge, because the web as we know was designed in their earlier days with the naive assumption that only good faith people would use it, thus it becomes a very hard task to secure something that was not designed to be secure in first place.
Securing and locking an API server to a specific app requires that some kind of secret needs to be used in every request in order to authenticate What is doing the request, but once you release a web app or mobile app into the public any secret on it is now in the public domain, therefore not a secret anymore, as it's best you can use it as a weak identifier.
Web App
A web app runs in the browser, thus all an attacker needs to do is to inspect the page source and extract the secret, and then use it in automated scripts or in manual requests from curl or tools like Postman.
Mobile App
Some developers think that because a mobile app is released as a binary that they can just put the secret there and no one will find it... Well I have to say that in the past I was one of them, but then I came to learn that a lot of open source tools exist to make this task trivial that even a script kid can do it. My preferred tool to do this is the MobSF, and you can see an example of using it in this article I wrote How to Extract an API Key from a Mobile App with Static Binary Analysis:
The range of open source tools available for reverse engineering is huge, and we really can't scratch the surface of this topic in this article, but instead we will focus in using the Mobile Security Framework(MobSF) to demonstrate how to reverse engineer the APK of our mobile app. MobSF is a collection of open source tools that present their results in an attractive dashboard, but the same tools used under the hood within MobSF and elsewhere can be used individually to achieve the same results.
MobSF - Mobile Security Framework:
Mobile Security Framework is an automated, all-in-one mobile application (Android/iOS/Windows) pen-testing framework capable of performing static analysis, dynamic analysis, malware analysis and web API testing.
The take away is that once an app is released any sensitive information shipped within it must be considered compromised.
JWT and OAUTH2
i have read that JWT with OAuth2 should be used but from my understanding the user have to login into a provider to get the token
Yes, the user would be required to login to get the OAuth token, but any type of token that comes from a user login successfully just identifies Who is in the request, not What is doing the request, and in my experience this is a very common misconception among developers, no matter if they are a junior or a senior developer.
The Difference Between WHO and WHAT is Accessing the API Server
I wrote a series of articles about Mobile API security, and in the article Why Does Your Mobile App Need An Api Key? you can read in detail the difference between Who and What is making the reques to your API server:
The what is the thing making the request to the API server. Is it really a genuine instance of your mobile app, or is it a bot, an automated script or an attacker manually poking around your API server with a tool like Postman?
The who is the user of the mobile app that we can authenticate, authorize and identify in several ways, like using OpenID Connect or OAUTH2 flows.
You may be surprised that sometimes even your legit users may be the ones attacking your API server in order to try to get benefits from your service that otherwise they wouldn't have access.
SECURING AND LOCKING THE API SERVER TO AN APP
but i want users to be able to read data without login.
my concern right now is how to prevent other people from using my API in their apps
To achieve this requirements in your app you need to find ways to secure and lock your API server to only serve requests from genuine instances of your web and mobile apps.
I have to say that for mobile apps this can be achieved with a very high degree of confidence when a Mobile App Attestation concept is employed, but for web apps we just can do it in a best effort basis, by using Artificial Intelligence solutions.
To understand how you can do it for a web app please read this answer I gave to the question Secure api data from calls out of the app, specifically the section entitled Defending The API Server.
For a mobile app you should read this answer I gave to the question How to secure an API REST for mobile app?, more specifically at the section Securing the API Server and the section A Possible Better Solution.
If you have read both the answers I linked above you may understand now better why I said initially that was a huge challenge.
DoS ATTACKS
u'm concerned also about DoS attacks.
This is not normally addressed at the application level, instead it his best handled at the infrastructure level, like in the Firewall, where rules can be applied to identify and drop DoS packets, but if they are to strict they may also block legit users, while if they are too relaxed they let pass DoS packets. To have more effective DoS attacks protections you need to resort to specialized software, and even this ones may need manual intervention during an huge scale DoS attack.
So my advice here is that you start by adding to the Firewall some rules to drop DoS packets, and/or if you are using a cloud provider you may want to see what level of DoS protection they can offer in your account. I know for example that some CDN providers do offer DoS protection for free until some extent, thus may worth you consider to have all your traffic routed through a CDN, that also brings the other traditional benefits of a CDN, aka serving assets from a closest location to your customers.
DO YOU WANT TO GO THE EXTRA MILE?
In any response to a security question I don't resist to reference the excellent work from the OWASP foundation.
For Web Apps
OWASP Web Top 10 Risks
The OWASP Top 10 is a powerful awareness document for web application security. It represents a broad consensus about the most critical security risks to web applications. Project members include a variety of security experts from around the world who have shared their expertise to produce this list.
The Web Security Testing Guide:
The OWASP Web Security Testing Guide includes a "best practice" penetration testing framework which users can implement in their own organizations and a "low level" penetration testing guide that describes techniques for testing most common web application and web service security issues.
For Mobile Apps
OWASP Mobile Security Project - Top 10 risks
The OWASP Mobile Security Project is a centralized resource intended to give developers and security teams the resources they need to build and maintain secure mobile applications. Through the project, our goal is to classify mobile security risks and provide developmental controls to reduce their impact or likelihood of exploitation.
OWASP - Mobile Security Testing Guide:
The Mobile Security Testing Guide (MSTG) is a comprehensive manual for mobile app security development, testing and reverse engineering.
For APIS
OWASP API Security Top 10
The OWASP API Security Project seeks to provide value to software developers and security assessors by underscoring the potential risks in insecure APIs, and illustrating how these risks may be mitigated. In order to facilitate this goal, the OWASP API Security Project will create and maintain a Top 10 API Security Risks document, as well as a documentation portal for best practices when creating or assessing APIs.

How do I secure rest api?

I'm working an app with Angular.I want to get the data to be listed from rest api. However, I don't want users to access the resource. Which language, library or framework can I secure it with? And users are using the app without membership.
I tried jwt but I didn't get the result I wanted. Maybe I couldn't.
Here is express.js
const app = require('express')()
const express = require('express')
const fs = require('fs')
const cors = require('cors')
const bodyParser = require('body-parser');
app.use(cors())
app.use(bodyParser.json())
app.get('/', (req, res) => {
res.json({message: 'Rest API Work'})
})
app.get('/list', (req, res) => {
fs.readFile('data1.json','utf-8',(err,data)=>{
res.setHeader("Content-Type", "application/json; charset=utf-8")
data = JSON.parse(data)
console.log(data)
res.end(JSON.stringify(data,null,4))
})
})
app.listen(3002, function(){
console.log('Server OK')
})
I want a simple security method where I can connect with Angular.
Best way to secure your API is start using a reverse proxy like Nginx. Javascript frameworks are all basically the same in terms of security. They all have a basic router handler, dispatcher (based of native Node.js HTTP library) and some basic helper methods, they give it a nice catchy name and that's it. I've checked the source code of almost all major frameworks.
Now, some basic configuration params of Nginx are: client_body_buffer_size proxy_buffers etc. All your directives should regex input data too. Generally anything that could "filter" the malicious code is useful. Cloudflare can somehow help and some other companies that could secure your app but they're expensive.
Another good example is containerizing your app using Docker.
If you have a basic piece of code in Node.js, the most easy way to hack it is through your app's logic. You should use anti-XSS modules like xss or express-sanitizer. If you're using SQL database you should always escape the query values.
ASSUMPTIONS
I'm working an app with Angular.
I am assuming that you are doing a Web App, and not a mobile app with something like NativeScript.
I want to get the data to be listed from rest api. However, I don't want users to access the resource
I assume here that you want that only the web app to have access to the API, and not anyone else.
LETS TACKLE YOUR QUESTIONS
Which language, library or framework can I secure it with?
The problem is not the programming language or framework, but what you are trying to achieve, and I honestly have to tell you a cruel truth... In the context of the web is not possible to lock down an API to a Web app, and this is just because of the way the web was built, you know you hit F12 and you can see all the code running in the browser, therefore any secret you put there to identify your web app in each request it does to the API, will be up for grabs and reuse by anyone who wants to replicate your web app, and your API will not be able to distinguish the WHO is doing the request from WHAT is doing the request.
And users are using the app without membership.
Contrary to what many developers may think, authenticated users don't lock-down a web app or mobile app to the API server, because the user is only one part of the equation, he represents the WHO is accessing the API, but you still need to address WHAT is accessing it.
Wait, wait a second... You keep referring to the WHO and the WHAT, do you care to explain it in more detail?
Glad you asked ;)
The Difference Between WHO and WHAT is Accessing the API Server
So let's clear a common misconception, among developers, about WHO and WHAT is accessing an API server.
To better understand the differences between the WHO and the WHAT are accessing an API server, let’s use this picture:
So replace the mobile app by web app, and keep following my analogy around this picture.
The Intended Communication Channel represents the web app being used as you expected, by a legit user without any malicious intentions, communicating with the API server from the browser, not using Postman or using any other tool to perform a man in the middle(MitM) attack.
The actual channel may represent several different scenarios, like a legit user with malicious intentions that may be using Curl or a tool like Postman to perform the requests, a hacker using a MitM attack tool, like MitmProxy, to understand how the communication between the web app and the API server is being done in order to be able to replay the requests or even automate attacks against the API server. Many other scenarios are possible, but we will not enumerate each one here.
I hope that by now you may already have a clue why the WHO and the WHAT are not the same, but if not it will become clear in a moment.
The WHO is the user of the web app that we can authenticate, authorize and identify in several ways, like using OpenID Connect or OAUTH2 flows.
OAUTH
Generally, OAuth provides to clients a "secure delegated access" to server resources on behalf of a resource owner. It specifies a process for resource owners to authorize third-party access to their server resources without sharing their credentials. Designed specifically to work with Hypertext Transfer Protocol (HTTP), OAuth essentially allows access tokens to be issued to third-party clients by an authorization server, with the approval of the resource owner. The third party then uses the access token to access the protected resources hosted by the resource server.
OpenID Connect
OpenID Connect 1.0 is a simple identity layer on top of the OAuth 2.0 protocol. It allows Clients to verify the identity of the End-User based on the authentication performed by an Authorization Server, as well as to obtain basic profile information about the End-User in an interoperable and REST-like manner.
While user authentication may let the API server know WHO is using the API, it cannot guarantee that the requests have originated from WHAT you expect, the browser were your web app should be running from, with a real user.
Now we need a way to identify WHAT is calling the API server, and here things become more tricky than most developers may think. The WHAT is the thing making the request to the API server. Is it really a genuine instance of the web app, or is a bot, an automated script or an attacker manually poking around with the API server, using a tool like Postman?
For your surprise, you may end up discovering that It can be one of the legit users manipulating manually the requests or an automated script that is trying to gamify and take advantage of the service provided by the web app.
Well, to identify the WHAT, developers tend to resort to an API key that usually is sent in the headers of the web app. Some developers go the extra mile and compute the key at run-time in the web app, inside obfuscated javascript, thus it becomes a runtime secret, that can be reverse engineered by deobusfaction tools, and by inspecting the traffic between the web app and API server with the F12 or MitM tools.
The above write-up was extracted from an article I wrote, entitled WHY DOES YOUR MOBILE APP NEED AN API KEY?. While in the context of a Mobile App, the overall idea is still valid in the context of a web app. You wish you can read the article in full here, that is the first article in a series of articles about API keys.
Now you may ask... If I can not lock down the API server to my web app only, how can I defend it?
Defending an API Server
To start with a web app or even a mobile should only communicate with an API server that is under your control and any access to third part APIs services must be done by this same API server you control. This way you limit the attack surface to only one place, where you will employ as many layers of defense as what you are protecting is worth.
So anything that runs on the client side and needs some secret to access an API can be abused in different ways and you can learn more on this series of articles about Mobile API Security Techniques. While this articles are in the context of an API serving a mobile app, some of the content are applicable for an API serving a web app to, and will help you to understand how fragile an API is when it comes to distinguish from WHO and WHAT is accessing it. So this series of articles will teach you how API Keys, User Access Tokens, HMAC and TLS Pinning can be used to protect the API and how they can be bypassed.
Now that you are more aware of the pains of defending an API server, let's see what can be done to mitigate the security risks is facing in the context of a web app. For an API serving a web app, you can employ several layers of dense, starting with reCaptcha V3, followed by Web Application Firewall(WAF) and finally if you can afford it a User Behavior Analytics(UBA) solution.
Google reCAPTCHA V3:
reCAPTCHA is a free service that protects your website from spam and abuse. reCAPTCHA uses an advanced risk analysis engine and adaptive challenges to keep automated software from engaging in abusive activities on your site. It does this while letting your valid users pass through with ease.
...helps you detect abusive traffic on your website without any user friction. It returns a score based on the interactions with your website and provides you more flexibility to take appropriate actions.
WAF - Web Application Firewall:
A web application firewall (or WAF) filters, monitors, and blocks HTTP traffic to and from a web application. A WAF is differentiated from a regular firewall in that a WAF is able to filter the content of specific web applications while regular firewalls serve as a safety gate between servers. By inspecting HTTP traffic, it can prevent attacks stemming from web application security flaws, such as SQL injection, cross-site scripting (XSS), file inclusion, and security misconfigurations.
UBA - User Behavior Analytics:
User behavior analytics (UBA) as defined by Gartner is a cybersecurity process about the detection of insider threats, targeted attacks, and financial fraud. UBA solutions look at patterns of human behavior, and then apply algorithms and statistical analysis to detect meaningful anomalies from those patterns—anomalies that indicate potential threats. Instead of tracking devices or security events, UBA tracks a system's users. Big data platforms like Apache Hadoop are increasing UBA functionality by allowing them to analyze petabytes worth of data to detect insider threats and advanced persistent threats.
All these solutions work based on a negative identification model, by other words they try their best to differentiate the bad from the good by identifying what is bad, not what is good, thus they are prone to false positives, despite the advanced technology used by some of them, like machine learning and artificial intelligence.
So you may find yourself more often than not in having to relax how you block the access to the API server in order to not affect the good users. This also means that these solutions require constant monitoring to validate that the false positives are not blocking your legit users and that at the same time they are properly keeping at bay the unauthorized ones.
CONCLUSION
I want a simple security method where I can connect with Angular.
So as may have realized already, you are not able to achieve a simple security method to lock down your Angular app with the API server. That's it, a simple security method does not do the trick, and instead you need to resort to several solutions, that will reduce the attack surface, but will not eliminate it.
So In the end, the solution to use in order to protect your API server must be chosen in accordance with the value of what you are trying to protect and the legal requirements for that type of data, like the GDPR regulations in Europe.

How do I secure a REST-API?

I've set up an API with authentication but I want to only allow certain applications and websites to access it. What do I do?
I've got authentication set up for users that are Logged in only being able to access the API, however, how do I prevent them from just logging in from anywhere?
Before I address your question, I think is important that first we clear a common misconception among developers, regarding WHO and WHAT is accessing an API.
THE DIFFERENCE BETWEEN WHO AND WHAT IS COMMUNICATING WITH YOUR API SERVER
To better understand the differences between the WHO and the WHAT are accessing your mobile app, let’s use this picture:
The Intended Communication Channel represents your mobile being used as you expected, by a legit user without any malicious intentions, using an untampered version of your mobile app, and communicating directly with your API server without being man in the middle attacked.
The actual channel may represent several different scenarios, like a legit user with malicious intentions that may be using a repackaged version of your mobile app, a hacker using the genuine version of you mobile app while man in the middle attacking it to understand how the communication between the mobile app and the API server is being done in order to be able to automate attacks against your API. Many other scenarios are possible, but we will not enumerate each one here.
I hope that by now you may already have a clue why the WHO and the WHAT are not the same, but if not it will become clear in a moment.
The WHO is the user of the mobile app that we can authenticate, authorize and identify in several ways, like using OpenID Connect or OAUTH2 flows.
OAUTH
Generally, OAuth provides to clients a "secure delegated access" to server resources on behalf of a resource owner. It specifies a process for resource owners to authorize third-party access to their server resources without sharing their credentials. Designed specifically to work with Hypertext Transfer Protocol (HTTP), OAuth essentially allows access tokens to be issued to third-party clients by an authorization server, with the approval of the resource owner. The third party then uses the access token to access the protected resources hosted by the resource server.
OpenID Connect
OpenID Connect 1.0 is a simple identity layer on top of the OAuth 2.0 protocol. It allows Clients to verify the identity of the End-User based on the authentication performed by an Authorization Server, as well as to obtain basic profile information about the End-User in an interoperable and REST-like manner.
While user authentication may let your API server know WHO is using the API, it cannot guarantee that the requests have originated from WHAT you expect, your mobile app.
Now we need a way to identify WHAT is calling your API server, and here things become more tricky than most developers may think. The WHAT is the thing making the request to the API server. Is it really a genuine instance of your mobile app, or is a bot, an automated script or an attacker manually poking around your API server with a tool like Postman?
For your surprise you may end up discovering that It can be one of your legit users using a repackaged version of your mobile app or an automated script trying to gamify and take advantage of your service.
Well, to identify the WHAT, developers tend to resort to an API key that usually they hard-code in the code of their mobile app. Some developers go the extra mile and compute the key at run-time in the mobile app, thus it becomes a runtime secret as opposed to the former approach when a static secret is embedded in the code.
The above write-up was extracted from an article I wrote, entitled WHY DOES YOUR MOBILE APP NEED AN API KEY?, and that you can read in full here, that is the first article in a series of articles about API keys.
YOUR QUESTIONS
I've got authentication set up for users that are Logged in only being able to access the API, however, how do I prevent them from just logging in from anywhere?
If by logging in from anywhere you mean any physical location, then you can use blocking by IP address as already suggested by #hanshenrik, but if you mean blocking from logging from other applications, that are not the ones you have issued the API keys for, then you have a very hard problem in your hands to solve, that leads to your first question:
I've set up an API with authentication but I want to only allow certain applications and websites to access it. What do I do?
This will depend if WHAT is accessing the API is a web or a mobile application.
Web application
In a web app we only need to inspect the source code with the browser dev tools or by right click on view page source and search for the API key, and then use it in any tool, like Postman or in any kind of automation we want, just by replicating the calls as we saw them being made in the network tab of the browser.
For an API serving a web app you can employ several layers of dense, starting with reCaptcha V3, followed by Web Application Firewall(WAF) and finally if you can afford it a User Behavior Analytics(UBA) solution.
Google reCAPTCHA V3:
reCAPTCHA is a free service that protects your website from spam and abuse. reCAPTCHA uses an advanced risk analysis engine and adaptive challenges to keep automated software from engaging in abusive activities on your site. It does this while letting your valid users pass through with ease.
...helps you detect abusive traffic on your website without any user friction. It returns a score based on the interactions with your website and provides you more flexibility to take appropriate actions.
WAF - Web Application Firewall:
A web application firewall (or WAF) filters, monitors, and blocks HTTP traffic to and from a web application. A WAF is differentiated from a regular firewall in that a WAF is able to filter the content of specific web applications while regular firewalls serve as a safety gate between servers. By inspecting HTTP traffic, it can prevent attacks stemming from web application security flaws, such as SQL injection, cross-site scripting (XSS), file inclusion, and security misconfigurations.
UBA - User Behavior Analytics:
User behavior analytics (UBA) as defined by Gartner is a cybersecurity process about detection of insider threats, targeted attacks, and financial fraud. UBA solutions look at patterns of human behavior, and then apply algorithms and statistical analysis to detect meaningful anomalies from those patterns—anomalies that indicate potential threats. Instead of tracking devices or security events, UBA tracks a system's users. Big data platforms like Apache Hadoop are increasing UBA functionality by allowing them to analyze petabytes worth of data to detect insider threats and advanced persistent threats.
All this solutions work based on a negative identification model, by other words they try their best to differentiate the bad from the good by identifying WHAT is bad, not WHAT is good, thus they are prone to false positives, despite of the advanced technology used by some of them, like machine learning and artificial intelligence.
So you may find yourself more often than not in having to relax how you block the access to the API server in order to not affect the good users. This also means that this solutions require constant monitoring to validate that the false positives are not blocking your legit users and that at same time they are properly keeping at bay the unauthorized ones.
Mobile Application
From your reply to a comment:
What about for mobile applications?
Some may think that once a mobile app is released in a binary format that their API key will be safe, but turns out that is not true, and extracting it from a binary is sometimes almost as easy as extracting it from a web application.
Reverse engineering a mobile app is made easy by plethora of open source tools, like the Mobile Security Framework(MobSF), Frida, XPosed, MitmProxy, and many other more, but as you can see in this article, it can be done with MobSF or with the strings utility that is installed in a normal Linux distribution.
Mobile Security Framework
Mobile Security Framework is an automated, all-in-one mobile application (Android/iOS/Windows) pen-testing framework capable of performing static analysis, dynamic analysis, malware analysis and web API testing.
Frida
Inject your own scripts into black box processes. Hook any function, spy on crypto APIs or trace private application code, no source code needed. Edit, hit save, and instantly see the results. All without compilation steps or program restarts.
xPosed
Xposed is a framework for modules that can change the behavior of the system and apps without touching any APKs. That's great because it means that modules can work for different versions and even ROMs without any changes (as long as the original code was not changed too much). It's also easy to undo.
MiTM Proxy
An interactive TLS-capable intercepting HTTP proxy for penetration testers and software developers.
Regarding APIs serving mobile apps a positive identification model can be used by using a Mobile App Attestation solution that guarantees to the API server that WHAT is making the requests can be trusted, without the possibility of false positives.
The Mobile App Attestation
The role of a Mobile App Attestation service is to guarantee at run-time that your mobile app was not tampered or is not running in a rooted device by running a SDK in the background that will communicate with a service running in the cloud to attest the integrity of the mobile app and device is running on.
On successful attestation of the mobile app integrity a short time lived JWT token is issued and signed with a secret that only the API server and the Mobile App Attestation service in the cloud are aware. In the case of failure on the mobile app attestation the JWT token is signed with a secret that the API server does not know.
Now the App must sent with every API call the JWT token in the headers of the request. This will allow the API server to only serve requests when it can verify the signature and expiration time in the JWT token and refuse them when it fails the verification.
Once the secret used by the Mobile App Attestation service is not known by the mobile app, is not possible to reverse engineer it at run-time even when the App is tampered, running in a rooted device or communicating over a connection that is being the target of a Man in the Middle Attack.
The Mobile App Attestation service already exists as a SAAS solution at Approov(I work here) that provides SDKs for several platforms, including iOS, Android, React Native and others. The integration will also need a small check in the API server code to verify the JWT token issued by the cloud service. This check is necessary for the API server to be able to decide what requests to serve and what ones to deny.
CONCLUSION
In the end the solution to use in order to protect your API server must be chosen in accordance with the value of what you are trying to protect and the legal requirements for that type of data, like the GDPR regulations in Europe.
So using API keys may sound like locking the door of your home and leave the key under the mat, but not using them is liking leaving your car parked with the door closed, but the key in the ignition.

Resources