DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workkloads.

Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Securing REST APIs With Nest.js: A Step-by-Step Guide
  • Securing RESTful Endpoints
  • What Is API-First?
  • Creating a Secure REST API in Node.js

Trending

  • Emerging Data Architectures: The Future of Data Management
  • Doris: Unifying SQL Dialects for a Seamless Data Query Ecosystem
  • *You* Can Shape Trend Reports: Join DZone's Software Supply Chain Security Research
  • Zero Trust for AWS NLBs: Why It Matters and How to Do It
  1. DZone
  2. Software Design and Architecture
  3. Integration
  4. RESTful API Security

RESTful API Security

John Vester discusses the importance of API security and security adoption measures like authentication, API keys, access control, and input validation.

By 
John Vester user avatar
John Vester
DZone Core CORE ·
Jul. 26, 17 · Opinion
Likes (32)
Comment
Save
Tweet
Share
280.2K Views

Join the DZone community and get the full member experience.

Join For Free

This article is featured in the new DZone Guide to Integration: API Design and Management. Get your free copy for more insightful articles, industry statistics, and more!

API Design – Documentation First

According to TechTarget, a RESTful API is “an application program interface (API) that uses
HTTP requests to GET, PUT, POST, and DELETE data. A RESTful API — also referred to as a RESTful web service — is based on representational state transfer (REST) technology, an architectural style and approach to communications often used in web services development.”

With the explosive growth of RESTful APIs, the security layer is often the one that is most overlooked in the architectural design of the API.

Why Does Security Matter?

There are three core reasons why security should be a serious consideration when designing and deploying a RESTful API.

Data Protection

A RESTful API is the way in which a given service can present value to the world. As a result, protection of the data provided via RESTful endpoints should always be a high priority.

DOS Attacks

Denial of Service (DOS) attacks can render a RESTful API into a non-functional state if the right security measures are not taken. Consider the case where an entry-level RESTful API is provided for public consumption. While it’s often a great marketing idea to generate usage of your API, it can also lead to catastrophic results when a consumer opts to perform DOS attacks on the API.

Anti-Farming

Today, there are several marketing-heavy websites that offer consumers the best deal on everything from flights to vehicles and even groceries. In many of these cases, the aggregated service is taking advantage of other APIs to obtain the information they want you to utilize. When this happens, the RESTful API is being farmed out for the benefit of another entity.

Security Adoption Measures

Below are some key concepts that should be part of any RESTful API design.

Session Management and Authentication

Aside from use of TLS/HTTPS, the most important level of RESTful API security is centered around session management and authentication. For this article, the focus is going to be on API keys, OpenID Connect/OAuth2/SAML, and session state considerations.

API Keys

The concept of API keys provides the consumer of the endpoint(s) with a unique string (a key) that is part of their HTTP requests. While not a complete security solution, the use of API keys yields a higher level of knowing who is using the API when compared to anonymous usage.

API keys can also be used to provide additional services. As an example, the service may opt to have Silver, Gold, and Platinum levels for the RESTful API. At the Silver level, end-users are granted free access, but only to a limited set of endpoints. Gold and Platinum would require some
level of payment, with the Platinum level providing more benefits over the Gold option.

The preferred manner to use API keys is to include them in the request header. As an example, the API key of 67a73dde1bdd1d90210ba is set to the X-API-KEY key/value pair in the HTTP header when calling the widget's end-point:

curl -H “X-API-KEY: 67a73dde1bdd1d90210ba”
https://www.example.com/v1/widgets

Another common use of an API key is to include the key in the URI itself:

https://www.example.com/v1/widgets?api_key
=67a73dde1bdd1d90210ba

The problem with this approach is that the API key is revealed in both the browser history and in logs at the API server — exposing the unique key to all who have access to these elements.

OpenID Connect, OAuth2, and SAML

OpenID Connect, OAuth2, and SAML use HTTP protocols as a transport and are used for security
purposes. Authentication provides the verification of the individual, while authorization performs the task of granting or revoking access.

From an authentication perspective, the following
options exist:

  • OpenID Connect: Can leverage an existing identity provider (like Google or Facebook) to obtain a token used to validate the end-user’s credentials.

  • OAuth2: Can perform pseudo-authentication through the authorization process through delegation (explained below).

  • SAML: Uses assertions, protocols, bindings, and profiles to manage authentication, including an identity provider, but is not well-suited for mobile applications.

To provide authorization services, the following strategies are employed:

OAuth2: Provides secure delegated access, allowing actions to be taken on behalf of the user by allowing tokens to be issued by a third-party identity provider. Since OAuth2 must know about the delegated user, authentication is achieved in a pseudo fashion (as noted above).

SAML: Performs assertions to trusted services, including a token to provide the authorization.

Session State Considerations

RESTful API endpoints should always maintain a stateless session state, meaning everything about the session must be held at the client. Each request from the client must contain all the necessary information for the server to understand the request. In order to streamline the process, the API token along with a session token can be included to provide a “session blob” as part of each transaction.

Access Control

As noted above, authorization for RESTful services can introduce security into provided end-points so that there are limits for those who can issue a HTTP DELETE request to the API.

In the simple Java example below, only members of the Admin and Manager roles (i.e. groups) can perform the DELETE request to delete all users, but all users can perform the GET request to obtain a list of users:

@Path(“/”)
@PermitAll
public class userExample {
  @DELETE
  @Path(“users”)
  @Produces(“text/plain”)
  @RolesAllowed({“Admin”, “Manager”})
  public String deleteAllUsers() {
    return userService.deleteAllUsers();
  }

  @GET
  @Path(“users”)
  @Produces(“text/plain”)
  public String getAllUsers() {
    return userService.getAllUsers();
  }
}

Rate Limits

As noted above, an API key is a valuable strategy to provide a level of identity to consumers of a RESTful API. In addition to providing tiered services, another benefit of using API key is the ability to throttle usage of the API.

API management solutions like TIBCO Mashery, MuleSoft, and Dell Boomi allow the ability to throttle API requests, leveraging API key for this functionality. As a result, a consumer who attempts to perform a DOS attack (intentionally or unintentionally) will reach a set threshold at which time all future requests will be rejected.

Input Validation and HTTP Return Codes

Input validation should always be a consideration when securing RESTful APIs. While the client calling the end-point may be handling validation, the assumption cannot always be relied upon with RESTful APIs.

As an example, if the end-user is attempting to POST data a collection of JSON data related to an address, the service within the RESTful end-point should validate the data and use HTTP return codes to reflect the correct status. In the simplified Java example, Jersey and Jackson are used to call a very basic addressService to both validate and persist the address:

public class addressExample {
    @POST
    @Path(“/address”)
    @Consumes(“application/json”)
    @Produces(“application/json”)
    public Address createAddress(Address newAddress) {
        if (!addressService.isValidAddress(newAddress))
        {
            return Response
                .status(Response.Status.BAD_REQUEST)
                .entity(“Invalid address provided.”)
                .type(MediaType.APPLICATION_JSON)
                .build();
        } else {
            String jsonAddress = addressService.convertAddress(newAddress);
            return Response
                .status(Response.Status.CREATED)
                .entity(jsonAddress)
                .build();
        }
    }
}

In the example above, the newAddress object (marshalled from JSON to the Address Java object) is validated using the isValidAddress() method. If the address is not valid, an HTTP 401 (Bad Request) code is returned to the user with the text “Invalid address provided.” If the address is considered valid, the convertAddress() will perform the necessary actions, then return a String-based JSON rending of the Address object to be included back to the user, along with a HTTP
201 (Created) return code.

Conclusion

Protecting RESTful APIs should always be at the forefront of the API design effort. The risks associated not protecting sensitive data, allowing DOS attacks, and not considering farming usage of RESTful APIs could easily put a business at a disadvantage, if not damage the business permanently.

Authorization and authentication can provide the necessary security to RESTful APIs, with implementation of an API key strategy adding significant value — with a low cost to implement.

Input validation should always be a part of the RESTful API since there is no guarantee the consumer of the API will be performing any necessary validation. Communication back to the calling client should implement HTTP return codes beyond simply success (200) and error (404).

This article is featured in the new DZone Guide to Integration: API Design and Management. Get your free copy for more insightful articles, industry statistics, and more!

API REST Web Protocols security authentication

Opinions expressed by DZone contributors are their own.

Related

  • Securing REST APIs With Nest.js: A Step-by-Step Guide
  • Securing RESTful Endpoints
  • What Is API-First?
  • Creating a Secure REST API in Node.js

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!