Part 3 — Security in RESTful APIs

Kapi, from LinkApi
6 min readSep 13, 2019

--

Shall we learn a little more about RESTful APIs?

This article will be about an important and polemic theme in the APIs world — Security.

I’ve heard several times, from several companies:

“Is this API thing really secure?”

Besides that, the banking industry (among others), which is security-freak, will be obligated to expose their APIs to the market by 2020, due to a legal change. The well known Open Banking.

Because of that, it’s important to be alert to this theme. Before we can go on, it’s worth mentioning that you should read my previous articles before continuing:

  1. A RESTful API Anatomy
  2. Methods and Status Codes

Authentication vs. Authorization

For Authentication, you can picture the following scenario: you are going to a party, and when you arrive there, the security guard asks you for your credentials (your ID number, for instance), so you can enter the party.

Authorization is when, at that same party, you feel like going to the club’s stage. To do it, you need authorization from the security guy.

Main authentication methods

Basic Authentication

Basic authentication is a simple authentication scheme, specified in the HTTP protocol.

The client sends a request with an (Authorization) header, containing the Basic word, with a username and a password, split by a colon (:), using base64 format.

For instance, in order to authorize thiago user, with thiago@123 as a password, the request’s header would be:

Authorization: Basic dGhpYWdvOnRoaWFnb0AxMjM=

Because the base64 format is very easy to be decoded, basic authentication is only recommended when joined by other security complements, like HTTPS certificates.

Note: I’ve seen cases when the user and password are replaced by a token, but that’s an exception and it’s not recommended by specification.

API Keys

API Keys is another authentication method that, theoretically, was developed to solve Basic Authentication problems.

Its main idea is simple. The server generates a unique access key for its client, and to use that API, the client sends that unique key on every request.

It’s a simple and fast implemented method, and for many years, it was the most used one among developers.

The thing is: this method works only for authentication, but not for authorization. So, theoretically, a user with a valid Key is able to access all of the operations of an API.

Besides that, it works like any other HTTP request, and if some network point is not secured, it can be easily intercepted and used in improper ways.

Usually, this key is used in the header, for instance, think about receiving the following key from the server: “thi123456”, so to authenticate, my request’s header would be:

Api-key: thi123456

It’s worth highlighting that the header parameter can vary according to the API. That can be “x-Api-key” for instance, or, in other cases, this key sending must be done via Query String, not via header, which is something even less secure, because attackers can easily see the information.

OAuth

OAuth is in its 2.0 version, and it isn’t just an authentication method, but a thorough protocol, with many security specifications.

It is extremely useful for the authentication and authorization process, and because of that, it is the most recommended method for APIs.

Some basic OAuth2 concepts:

  • Resource Owner: the entity that owns that resource, therefore, able to control its access. Usually, it’s the user himself.
  • Resource Server: self-explanatory, it’s the server that receives requests.
  • Authorization Server: the server that generates access tokens, so the client can be granted access to authorized resources by the resource owner.
  • Client: the application that accesses the resource server’s resources.

To make it clearer, let’s suppose you have developed an application that uses data from a Facebook user, so let’s simulate a basic authentication flow via OAuth 2.0:

  1. The user accesses your website or application, and it has an “integrate to Facebook” button, so your website or application would be the client.
  2. By clicking on that button, this user is redirected to Facebook’s login screen (authorization server).
  3. The user provides his credentials and Facebook provides an access code to the client.
  4. Then, the client requests authorization to the resources (Facebook’s API endpoints) to the resource owner (which is the user himself) by sending the received access code.
  5. The authorization server verifies if that access code is indeed valid, and if it is, it generates an access token that is returned to the client.
  6. Last, now that the client already has an access token and authorization to the resources, on each request, the resource server (Facebook’s API) will return with the protected data.

This is a massive subject, with many more details. So, here’s a link to a great and detailed article about this protocol.

Some more topics related to oAuth specification and very relevant ones to implement:

OpenID Connect: An extension of OAuth’s Authentication feature. As OAuth was developed to authorization, OpenID Connect is a great complement for securing your APIs, helping on proving that the user is indeed who he claims to be.

JWT: Secure token format, using JSON as a foundation.

SAML

There’s also SAML (Security Assertion Markup Language). It’s an open pattern that allows IDP (Identity Providers) to pass their authorization credentials to SP (service providers).

In other words, the user can use the same credentials to log in to different applications.

What SAML does is activating SSO (Single Sign-On), which is something very interesting regarding user experience, because they can log in once and still browse through all of the applications which apply this pattern.

I don’t see any other scenario for SAML’s application except the ones that single login is necessary. It uses XML in its communication, which is something outdated when compared to others used in today’s web development.

If you want to understand more about the differences and use cases of OAuth, check out this article.

Security Best Practices

Being straight to the point, those are the main recommendations for the majority of cases of building RESTful APIs:

Keep your implementation simple

Always think about the experience for the developer who will consume your API. Many APIs lose engagement due to the consuming complexities caused by security implementations.

Always use HTTPS

This one is a basic Web security tip. HTTPS keeps messages secure and encrypted, making any kind of request interception difficult.

It’s natural facing a performance downgrade, but if you use HTTP2, there are many optimizations workarounds available.

Do not expose sensible data on URLs

Passing security data via URL is a common and bad practice. For instance:

GET https://api.test.com/orders/?apiKey=thiago1234

Anyone with bad intentions will have their job way easier with that.

Consider using OAuth

OAuth is, surely, the most complete specification for RESTful APIs. Because of that, make use of all that is good in OAuth, just keep your developer experience in mind and watch out for too many implementation complexities that can have a bad impact on your API.

Use Rate Limit

This is an interesting practice. It helps to avoid problems regarding attacks that make a high number of requests so your infrastructure gets hindered.

With this header’s implementation, you can restrict your client’s number of requests.

Also, your request’s response will always contain the following headers:

  • X-Rate-Limit-Limit — Allowed requests within a specified period (day, hour, etc.)
  • X-Rate-Limit-Remaining — Remaining requests for that period.
  • X-Rate-Limit-Reset — Remaining seconds for the current period.

Besides that, when clients surpass the request limit, you’ll return status code 429 — Too Many Requests.

Timestamp on requests

If security is critical for your API, creating custom headers with a timestamp is a good way to go. This way, the server can compare the current timestamp and accept only the requests that are closer to a certain period of time (2 minutes, for instance).

It’s a simple procedure and it can help to avoid basic replay attacks with brute force attempts.

Validate requests parameters

For security reasons, you should always validate request parameters before executing your business’s logic.

If the request does not have specified parameters, immediately reject it, because that may indicate the evidence of a malicious attack.

Besides that, in order to keep a good experience for the ones who aren’t malicious, you can return clear error messages, and show examples of correct requests.

Use an API Gateway tool.

There are many tools that can make the implementation of those recommendations easier. They centralize all the security intelligence in a specific architecture layer.

You can see this model in the following image:

Some recommended tools for that architecture: LinkApi, Kong, WSO2, and Apigee.

That’s it, developers! We have reached the end of another RESTful APIs article, with an extremely important subject.

I hope you have liked it, and stay tuned because the next article will be about APIs versioning.

--

--

Kapi, from LinkApi

We’re here to give developers and companies the building blocks they need to enable digital transformation fast without spending a lot of money and time.