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

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

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

Related

  • Jakarta Security and REST on Cloud: Part 4 Combining JWT With OAuth2
  • Jakarta Security and REST in the Cloud Part 3: Knowing the OAuth2
  • Best Practices To Secure Stateless REST Applications
  • Securing REST APIs With Nest.js: A Step-by-Step Guide

Trending

  • Secrets Sprawl and AI: Why Your Non-Human Identities Need Attention Before You Deploy That LLM
  • Distributed Consensus: Paxos vs. Raft and Modern Implementations
  • Implementing Explainable AI in CRM Using Stream Processing
  • Securing the Future: Best Practices for Privacy and Data Governance in LLMOps
  1. DZone
  2. Software Design and Architecture
  3. Integration
  4. Security Best Practices for REST APIs

Security Best Practices for REST APIs

In the modern era, REST APIs become an integral part of the applications. Check out some of the best practices for securing APIs.

By 
Anji K user avatar
Anji K
·
Jul. 21, 20 · Analysis
Likes (2)
Comment
Save
Tweet
Share
13.6K Views

Join the DZone community and get the full member experience.

Join For Free

In the modern era, REST APIs become an integral part of the applications. By adopting the REST APIs, you can expose your services to web applications or mobile applications and all other digital platforms.

REST APIs must be built as a stateless service. REST API best practices deserve a separate article. This article primarily focuses only on security best practices for REST APIs.

Below are the key concepts that should be considered while designing the REST APIs.

  • Authentication/authorization
  • Input validations and sanitization
  • Defining content-types
  • Output encoding
  • Rate limiters
  • Security for data in transit and storage
  • Responding with appropriate status codes to avoid the ambiguity

Before delving into details let us first understand authentication and authorization.

  • Authentication: Authentication is the process of identifying whether the credentials passed along with the request are valid or not. here credentials can be passed as user id and password or a token assigned for the user session.
  • Authorization: Authorization is the process of identifying whether the received request is allowed to access the requested endpoint or method.

In the request processing pipeline, authentication comes first and authorization comes next. Authorization occurs only after successful authentication of the request.

Below are the most widely used authentication types when dealing with Remote APIs (REST APIs / Web Services).

Basic Auth is the simplest way of dealing with Authentication when compared to other methodologies.

In the Basic Auth, the user has to send the user id and password in the format of userid:password encoded in base64 format. This method is preferred only over the https protocol only. This is highly discouraged to use over HTTP as your credentials are transferring in plain format.

Plain Text
 




x


 
1
Authorization: Basic base64(userid:password)


Bearer Token Authentication is also known as Token-based Authentication. When the user logs into an application using the credentials, the Authorization server generates a cryptographic token to uniquely identifies the user. the applications can use the token to identify the user after a successful login. i.e. The application is required to send this token when accessing protected resources.

Similar to Basic Authentication, Bearer tokens are only recommended to send over HTTPS only.

Authorization Bearer <your token>

API Tokens are widely used in the web services/REST APIs security before the evaluation of Client-side frameworks. Still, many organizations use the API Tokens as a security measure for the APIs. This is the simplest way of implementing the security in REST APIs.

This is recommended when providing the communication between server to server requests. It is recommended to use the IP Address registration as well when using the API keys. i.e. API Token is uniquely identified along with the IP Address. This is not recommended to use as a methodology for end-user authentication and Authorization.

The API Key key can be sent as part of the query string or Authorization token or custom header or as part of the data.

OAuth2.0 is an authorization framework that allows users to grant a third-party website or application to access the user's protected resources without revealing their credentials or identity. For that purpose, an OAuth 2.0 server issues access tokens that the client applications can use to access protected resources on behalf of the resource owner.

You probably see this option in the form of 'Login using Google', 'Login using Facebook', 'Login using Github' etc.

By default, OAuth generates the access tokens in the format of JWT (JSON web tokens). JWTs contain three parts: a header, a payload, and a signature.

  • Header: metadata about the token like cryptographic algorithms used to generate the token.
  • Payload: payload contains the Subject (usually identifier of the user), claims (also known as permissions or grants), and other information like audience and expiration time, etc.
  • Signature: used to validate the token is trustworthy and has not been tampered with.
  • Below are the OAuth roles you must aware of when dealing OAuth2.0
  • Resource Owner: the entity that can grant access to a protected resource. Typically this is the end-user.
  • Resource Server: The server that is hosting the protected resources
  • Client: the app requesting access to a protected resource on behalf of the Resource Owner.
  • Authorization Server: the server that authenticates the Resource Owner, and issues Access Tokens after getting proper authorization.

OAuth2.0 provides various flows or grant types suitable for different types of API clients. Grant Types are out of scope for this article.

OIDC is a simple identity layer built on top of the OAuth2.0. OIDC defines a sign-in flow that enables a client application to authenticate a user, and to obtain information (or "claims") about that user, such as the user name, email, and so on. User identity information is encoded in a secure JSON Web Token (JWT), called ID token.

In the Open ID Connect, Request flow will happen as below.

  1. user will be navigated to the Authorization server from the client app
  2. The user enters the credentials to identify the user
  3. Upon successful authentication, Server sends back the user to client along with authorization code
  4. Client app requests the Authorization server for tokens (Access Token and Id Token) using the authorization code (we can use nonce here to incorporated additional security)
  5. Authorization server responds back with tokens.

Input validation should be applied to both syntactical and semantic levels.

  • Syntactical: should enforce correct syntax of structured fields (e.g. SSN, date, currency symbol).
  • Semantic: should enforce correctness of their values in the specific business context (e.g. start date is before the end date, price is within expected range).

Basic Input validation guidelines

  • Define an implicit input validation by using strong types like numbers, booleans, dates, times, or fixed data ranges in API parameters.
  • Constrain string inputs with regular expressions.
  • Use whitelisting and blacklisting techniques
  • Define min and maximum lengths as a mandatory
  • Enforce Input validations on client-side and server-side
  • Reject unexpected/illegal content with valid error messages

We must define the allowed content types explicitly. It is always good practice to define the valid content types and share them with the required shareholders. Upon receiving an unexpected or missing content-type header, API must respond with HTTP response status 406 Unacceptable or 415 Unsupported Media Type.

Content of given resources must be interpreted correctly by the browser, the server should always send the Content-Type header with the correct Content-Type, and preferably the Content-Type header should include a charset.

JSON encoders must be used when dealing with JSON Data.

Rate limiters allow you to secure your APIs from the DDoS attacks. When exposing your API to publicly you must define the rate limiters. If you are opt-in for any cloud provider tools, they explicitly provide the rate-limiting capabilities to the public faced resources. you must adjust the configurations accordingly to your needs.

Ensure data is sent over HTTPS only. if any user tries to access over HTTP, you should upgrade it HTTPS and handle the request

Data in storage must be protected using best security practices. All the cloud providers provide you the inbuilt security (Encryption)for your backups.

Below are few common status codes used along with REST APIs

  • 201 - Created
  • 200 - OK
  • 202 - Accepted and queued for processing
  • 204 - No Content
  • 304 - Not Modified
  • 400 - Bad Request
  • 401 - UnAuthorized
  • 403 - Forbidden
  • 404 - Not Found
  • 405 - Method Not Allowed
  • 406 - Not Acceptable (Used with Content Types)
  • 415 - Unsupported Media Type
  • 429 - Two Many requests

Please share your thoughts in the comments box to improve it further.

If you found this helpful please share it on Twitter, Facebook, LinkedIn, and your favorite forums. Big thanks for reading!

references:

https://auth0.com/docs/protocols/oauth2 https://swagger.io/docs/specification/authentication/oauth2/ https://cheatsheetseries.owasp.org/

Please follow and like us!

REST Web Protocols security authentication

Published at DZone with permission of Anji K. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Jakarta Security and REST on Cloud: Part 4 Combining JWT With OAuth2
  • Jakarta Security and REST in the Cloud Part 3: Knowing the OAuth2
  • Best Practices To Secure Stateless REST Applications
  • Securing REST APIs With Nest.js: A Step-by-Step Guide

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!