I have currently developed a backend app that has some important functionalities. I want to consume my backend endpoints from my frontend but I want to be sure that only my fronted calls the backend endpoint and no other. Currently anyone that access my web-app can take advantage of the functionalities (I do not require any user registration or authentication).
How can I be safe that my backend is not being called form other possible malicious attackers that may try to steal the functionalities of my backend?
I have read some other posts regarding solutions how to secure a backend app that do not require user authentication but none has a precise and secure way for that. Some say enabling CORS but during my experience I can say that CORS can be manipulated easily with the help of a simple browser plugin. (not speaking about mobile apps that do not consider it at all)
I would really appreciate if I would have some opinions in case of a web-frontend-app, mobile app and other backend systems that would try to call my API and how can I stop them.
Typical front-end authentication would be best (OpenID, ...).
If you want something different, you could check on your backend whether a specific header with a specific token is sent in the query. If it is not then you send back a 401 HTTP code.
This requires that your customers somehow get that token (through some registration process, probably) and then keep it long-term (it can be stored in LocalStorage but can be lost when cleaning up the browser)
OWASP Authentication is a good source of information.
I am developing an api that will be eventually behind a paywall - In my scenario, clients would sign up, pay for an api tier/plan and afterwards be able to consume that api from their own apps. Depending on the tier chosen they will have certain usage limits on the api ( e.g. throttling/limits and various apis available depending on tier)
I was thinking of distributing an api_key for ease of use by clients but not sure if thats a good idea or how it would fit in with the Jhipster security model.
I guess I can just have clients sign in to grab JWT access/refresh tokens but that makes things a bit more complex for prospective clients.
Is the answer to go 'full Oauth2' and create separate 'App Clients' of an Okta Authentication server and give each customer their own "clientId + secret" that they can use to obtain access tokens ?
Any advice ?
thank you
I think it would be easy for you to go with jhipster UAA server which It serves as:
An OAuth2 Authorization Server, based on Spring Boot's implementation
An Identity Management Server, exposing a user account CRUD API
it is easy to integrate with your already jhipster tech stack and it is based on OAuth2 standard.
but for the metric and limitation part you’ll need some coding and a separate fast and high available storage to keep track of the usage of API's and a file provided to your HAproxy as a blacklist for people who reached their limit to be redirected to purchase page.
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.
My collegues and I want to build a chat application (ReactJS <-> NodeJS), and we have been looking for the best framework to do so. FeathersJS seems undoubtedly the most stable and feature-rich socket.io wrapper.
However, as we want to allow our application to scale up, we have decided to split this chat feature in a different node process than our main node backend.
The chat functionalities still requires authentication and authorization however, and we would like to avoid duplicating authentication for the two services. Hence what we have come with as a solution is to query the main node backend with the session cookie to authenticate the user before letting them use the chat service.
Does FeathersJS establishes long-lasting socket connections or would it establish a socket connection for every message sent/received? In the first case we could proceed with our architecture, whereas on the second we'd have to review due to the high load this would produce on the main backend.
Thanks!
There are several ways of splitting up services each with their own advantages and drawbacks. One generally important thing for Feathers is that there are no sessions, just JSON web tokens. JWTs are stateless and can be read by any server that shares the same secret so there does not have to be a central session store. The two main options I can think of are:
Have a main application that handles authorization and managing all connected clients but instead of having services that talk to the database they connect to separate simple individual API servers in the internal network. This is the easier setup and the advantage is that the internal API servers can be super simple and don't need authentication at all (since the main application is allowed to do everything and will make queries according to the authenticated users restrictions). The disadvantage is that the main application is still the bottleneck (but with a decreased load since it basically acts as a proxy to internal APIs).
Every client connects to every API server they need using a JWT. The JWT is created by a separate authentication (or user) API. This is the more scalable solution since the only bottleneck is retrieving the most up-to-date user information from a common users service (which might not even always be necessary). The disadvantage is that it is more complex to manage on the client side and authentication (at least for JWT) will have to be configured on every server. Due to the statelessness of JWT however, there does not need to be any shared sessions.
I am busy doing some research into using REST services with mobile applications and would appreciate some insight. The scenario is as follows.
Consider a web application that provides a service to users. The web application will also be the main interaction point for the users. This will be done in Grails, and secured with Spring Security.
Now, we want to provide a REST service so that users can use the service via mobile applications. Since Grails has such nice support for making the existing web application RESTful, we will use the built-in Grails support for that.
My question now is, what would be the "best" way to secure the REST service interface so that it can be use from mobile applications (native- iOS, Andriod, WM7, BB).
The information exchanged are highly sensitive, so the more secure, the better.
Thanks
We decided to split our grails project in three...
model-domain-project (This is the "admin" section with all the views/controller scaffolded, and all the services, domain)
web-app (this is the main application, controllers, views)
api-rest-app (this is the rest controllers)
The model-domain-project is a plugin that it's plugged in the web-app and the api-app, contains the domain model, services, and all the database security, transactions, etc.
The web-app is all the html templates, views and controllers, here we are using the attributes of Spring Security
The api-rest-app we are using grails-filters and we are using Basic-Authorization via https with a token with an expiration date...
if the expiration date of the token is reached you will have to ask for another token with a "request-token" we sent you with the first token... (it's more or less like oauth2)
To get the two first tokens, you will have to confirm the device via a login with user/phone/password then you receive a key via sms that you will have to enter in the app
Do not know if this the best way, but it's the way we do it...
Sometimes we are using the web-app as client and call the api-rest-app...