REST API Security Guide

Knowledge of how to secure REST APIs is as much necessary as writing the APIs themselves. Mostly REST APIs are HTTP protocol-based, and any user having an internet connection can access them, and so can bad users as well. It is crucial to write secure APIs to protect the business.

Before starting to secure RESTful APIs, let’s understand what our options are as developers. What will be a good fit for our usecase?

1. Difference between Authentication and Authorization

Before jumping into the main discussion, let’s make our facts straight about what authentication is and what authorization is.

In plain simple English, authentication is the process of ascertaining “the user is really someone who he claims to be“. In technical terms, it’s the process of login into the system through a username/password or any similar mechanisms e.g. fingerprint scanning, security token, security questions or SAML token received from SSO login. There must be something that can identify the user from others.

Once the user enters inside the system, authorization refers to rules that determine “what the user is allowed to do” and what he is not e.g. a normal user can post a message in any public group, but users only with an editor role will be able to delete something. Authorization is often seen as both the introductory setting up of permissions by a system administrator and the checking of the permission values that have already been set up when a user gets access to the system.

When we secure RESTful web services, we must take care of both factors. The two concepts are entirely orthogonal and independent, but both are central to security design, and the failure to get either correct increases the chances of a compromised system.

2. Four Ways to Secure RESTful Web Services

There are multiple ways to secure a RESTful API in Java. Let’s go through 4 most popular choices:

2.1. Basic-Authentication

It’s the simplest of all techniques and probably the most used as well. You use login/password forms – it’s basic authentication only. You input your username and password and submit the form to the server, and the application identifies you as a user – you are allowed to use the system – else you get an error.

The main problem with this security implementation is that credentials are propagated in a plain way from the client to the server. Credentials are merely encoded with Base64 in transit, but not encrypted or hashed in any way. This way, any sniffer could read the sent packages over the network.

HTTPS is, therefore, typically preferred over or used in conjunction with Basic Authentication which makes the conversation with the web server entirely encrypted. The best part is that nobody can even guess from the outside that Basic Auth is taking place.

2.2. DIGEST Authentication

This authentication method uses hashing algorithms to encrypt the password (called password hash) entered by the user before sending it to the server. This, obviously, makes it much safer than the basic authentication method, in which the user’s password travels in plain text that can be easily read by whoever intercepts it.

Read More: Generate Encrypted Passwords

There are many such hashing algorithms in java also, which can prove really effective for password security such as MD5, SHA, BCrypt, SCrypt and PBKDF2WithHmacSHA1 algorithms.

Please remember that once this password hash is generated and stored in the database, you can not convert it back to the original password. Each time the user login into the application, you have to regenerate the password hash again and match it with the hash stored in the database. So, if user forgot his/her password, you will have to send him a temporary password and ask him to change it with his new password. Well, it’s a common trend nowadays.

2.3. Client CERT Authentication

This is a mechanism in which a trust agreement is established between the server and the client through certificates. They must be signed by an agency established to ensure that the certificate presented for authentication is legitimate, which is known as CA.

Using this technique, when the client attempts to access a protected resource, instead of providing a username or password, it presents the certificate to the server. The certificate contains the user information for authentication including security credentials, besides a unique private-public key pair. The server then determines if the user is legitimate through the CA. Additionally, it must verify whether the user has access to the resource.

This mechanism must use HTTPS as the communication protocol as we don’t have a secure channel to prevent anyone from stealing the client’s identity.

You can find a complete tutorial for generating security certificate in official oracle docs.

2.4. OAuth2

If you have ever developed applications that interact other with other applications over the cloud e.g. Facebook integration or Twitter authentication etc. then you have already used this. They require you to provide an API key and API secret to rightly identify you. These API keys and secrets are some random encoded string that is impossible to guess.

To understand how it works, let’s assume you are using Flickr (photo sharing application) and want to post some of your photos using its REST API. You build the request as documented in Flickr docs, then send it.

Then, when receiving the request, Flickr authenticates the user by reading the information from the API key with the secret key that belongs to the user. Once these validations are successful, the server delivers the response to the client. Thus, we obtain a response with all the photos that have been recently posted on Flickr.

As you’ll notice, this way, you can easily create applications using the provider’s API. Also, the provider will allow you to authenticate, and access public information.

If someone starts disrespecting agreements e.g. sending junk traffic or any policy violation, the provider withdraws the API key and prevents the abusive use of its APIs.

3. REST API Security Implementations

Apart from the above concepts, you will usually need to secure your RESTful APIs in your company using the below methods.

3.1. SecurityContext

The javax.ws.rs.core.SecurityContext interface provides access to security-related information for a request and is very similar to javax.servlet.http.HttpServletRequest.

You access the SecurityContext by injecting an instance into a class field, setter method, or method parameter using the javax.ws.rs.core.Context annotation e.g. in below code sc.isUserInRole() is used to check authorization for user.

@GET
@Produces("text/plain;charset=UTF-8")
@Path("/hello")
public String sayHello(@Context SecurityContext sc) {

  if (sc.isUserInRole("admin"))
    return "Hello World!";
  throw new SecurityException("User is unauthorized.");
}

3.2. Method-level Authorization

This technique is widely used in enterprise applications and used to verify the roles and responsibilities of an authenticated user – for any particular operation. JAX-RS provides the below annotations for this purpose.

An example use of annotation can be:

@RolesAllowed("ADMIN")
@PUT
@Path("/users/{id}")
public Response updateUserById(@PathParam("id") int id) {

    UserDatabase.updateUser(id);
    return Response.status(200).build();
}

Read More : JAX-RS authentication and authorization example

4. REST API Security Best Practices

Let’s note down some essential points while designing security for your RESTful web services.

  • Use only HTTPS protocol so that your whole communication is always encrypted.
  • Never send auth credentials or API keys as a query param. They appear in the URL and can be logged or tracked easily.
  • Use the most challenging encryption level always. It will help in having more confidence.
  • For resources exposed by RESTful web services, ensuring any PUT, POST, and DELETE request is protected from Cross-Site Request Forgery is essential.
  • Always validate the input data asap it is received in the server method. Use only primitive data as an input parameter as much as possible.
  • Rely on framework-provided validation features as they are tested by a large community already.

Let me know your thoughts and experiences on securing RESTful web services in your organization.

Happy Learning !!

Comments

Subscribe
Notify of
guest
8 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial

Dark Mode

Dark Mode