REST API Tutorial

  • REST
  • JSON

REST API Security Essentials

Security isn’t an afterthought. It has to be an integral part of any development project and also for REST APIs. There are multiple ways to secure a RESTful API e.g. basic auth, OAuth etc. but one thing is sure that RESTful APIs should be stateless – so request authentication/authorization should not depend on cookies or sessions. Instead, each API request should come with some sort authentication credentials which must be validated on the server for each and every request.

REST Security Design Principles

The paper “The Protection of Information in Computer Systems” by Jerome Saltzer and Michael Schroeder, put forth eight design principles for securing information in computer systems, as described in the following sections:

  1. Least Privilege: An entity should only have the required set of permissions to perform the actions for which they are authorized, and no more. Permissions can be added as needed and should be revoked when no longer in use.
  2. Fail-Safe Defaults: A user’s default access level to any resource in the system should be “denied” unless they’ve been granted a “permit” explicitly.
  3. Economy of Mechanism: The design should be as simple as possible. All the component interfaces and the interactions between them should be simple enough to understand.
  4. Complete Mediation: A system should validate access rights to all its resources to ensure that they’re allowed and should not rely on cached permission matrix. If the access level to a given resource is being revoked, but that isn’t reflected in the permission matrix, it would violate the security.
  5. Open Design: This principle highlights the importance of building a system in an open manner—with no secret, confidential algorithms.
  6. Separation of Privilege: Granting permissions to an entity should not be purely based on a single condition, a combination of conditions based on the type of resource is a better idea.
  7. Least Common Mechanism: It concerns the risk of sharing state among different components. If one can corrupt the shared state, it can then corrupt all the other components that depend on it.
  8. Psychological Acceptability: It states that security mechanisms should not make the resource more difficult to access than if the security mechanisms were not present. In short, security should not make worse the user experience.

Best Practices to Secure REST APIs

Below given points may serve as a checklist for designing the security mechanism for REST APIs.

Keep it Simple

Secure an API/System – just how secure it needs to be. Every time you make the solution more complex “unnecessarily”, you are also likely to leave a hole.

Always Use HTTPS

By always using SSL, the authentication credentials can be simplified to a randomly generated access token that is delivered in the username field of HTTP Basic Auth. It’s relatively simple to use, and you get a lot of security features for free.

If you use HTTP 2, to improve performance – you can even send multiple requests over a single connection, that way you avoid the complete TCP and SSL handshake overhead on later requests.

Use Password Hash

Passwords must always be hashed to protect the system (or minimize the damage) even if it is compromised in some hacking attempt. There are many such hashing algorithms which can prove really effective for password security e.g. MD5, SHA, PBKDF2, bcrypt and scrypt algorithms.

Never expose information on URLs

Usernames, passwords, session tokens, and API keys should not appear in the URL, as this can be captured in web server logs, which makes them easily exploitable.

https://api.domain.com/user-management/users/{id}/someAction?apiKey=abcd123456789  //Very BAD !!

Above URL exposes API key So, never use this form of security.

Consider OAuth

Though basic auth is good enough for most of the APIs and if implemented correctly, it’s secure as well – yet you may want to consider OAuth as well. The OAuth 2.0 authorization framework enables a third-party application to obtain limited access to an HTTP service, either on behalf of a resource owner by orchestrating an approval interaction between the resource owner and the HTTP service, or by allowing the third-party application to obtain access on its own behalf.

Consider Adding Timestamp in Request

Along with other request parameters, you may add a request timestamp as HTTP custom header in API request. The server will compare the current timestamp to the request timestamp, and only accepts the request if it is within a reasonable timeframe (1-2 minutes, perhaps).

This will prevent very basic replay attacks from people who are trying to brute force your system without changing this timestamp.

Input Parameter Validation

Validate request parameters on the very first step, before it reaches to application logic. Put strong validation checks and reject the request immediately if validation fails. In API response, send relevant error messages and example of correct input format to improve user experience.

TwitterFacebookLinkedinReddit

Comments

  1. Christopher K says

    August 9, 2019 at 8:47 pm

    Great Documentation. We are implementing a sessionless solution where Basic Auth consists of the encoded ‘username:password’. We are limiting the operations to GETs only. We have noted, after working with the developer, that the session is not logged on the server. May I ask if this is common in similar REST features you have reviewed in the past?

    Reply
  2. Manoj says

    July 11, 2019 at 11:58 am

    Hi,

    https://api.domain.com/user-management/users/{id}/someAction?apiKey=abcd123456789 //Very BAD !!

    I didn’t understand please can you explain this, why is very bad practice. What is correct way.

    Reply
    • Admin says

      July 11, 2019 at 4:25 pm

      As the title says that never expose information on URLs.

      Reply
    • William Bowen says

      July 17, 2019 at 3:19 am

      I know it’s been a few days, but just in case you are still looking for more information, a more correct way is to send the api key as a header. When paired with SSL, this helps ensure the api key is kept hidden from prying eyes.

      Reply
  3. Ignacio says

    July 10, 2019 at 11:35 am

    Great article! Thanks!

    I want to do a comment if you allow me.

    I think that adding a timestamp with a hash will not help at all if you are using SSL/TLS transmission because that session protocol will take care of reply attacks. Am I right?

    Best regards,
    Ignacio

    Reply
  4. Vikki says

    March 23, 2019 at 6:04 am

    We can use JWT to securely transfer information

    Reply
    • Showemimo Olarewaju says

      July 10, 2019 at 11:01 am

      Yes, you can combine JWT token with OAuth 2 for enriched token validation

      Reply
  5. Narayana katooru says

    March 14, 2019 at 2:12 am

    what are the alternatives to exposing key in URL?

    Reply
    • Benjamin says

      March 18, 2019 at 1:39 pm

      Parsing it as a header value.

      Reply
    • Chris says

      May 15, 2019 at 12:52 am

      Pass it as a POST, data is stored in the request body

      Reply
    • Kangkan says

      June 6, 2019 at 4:54 am

      Anything that we do not wish to include in URL should be put either as a request body in case of POST/PUT requests or in HTTP Headers for GET or any other HTTP Verb.

      Reply
    • Showemimo Olarewaju says

      July 10, 2019 at 11:03 am

      in case of applications with UI I think you can use hidden fields, but in rest, better you make use of Headers and/or have it in your post body

      Reply
  6. Akhilesh Shukla says

    March 4, 2019 at 9:52 am

    Good Checklist. Thanks!

    Reply
  7. Vladimir Lashchev says

    January 23, 2019 at 9:37 pm

    Adding timestamp to the request seems like a very small security improvement if at all. Unless that timestamp is signed by client and server can check that signature, it won’t help because MITM can inject updated timestamp in every replay.

    Reply
    • Amri Shodiq says

      February 27, 2019 at 9:31 am

      Add timestamp is actually really helps, if it is combined with a hash. Means, the timestamp parameter should be included into the object to be hashed. This way, a REST API request wouldn’t be fabricated. IMO.

      Reply
  8. Anonymous says

    January 18, 2019 at 3:55 pm

    “which can prove really effective for password security e.g. MD5, […]”

    You should really omit MD5 and SHA. Not sure about the others.

    Reply
    • Mustafa Çağatay Tulun says

      August 10, 2019 at 4:19 pm

      Well said! We are in 2019 and we should not use any MD (e.g. MD5) or SHA (e.g. SHA-1) algorithm to hash password. PBKDF2, bcrypt and scrypt are good choices.

      If @Admin updates the article, it would be great!

      Reply
  9. Tim Maes says

    July 20, 2018 at 9:41 am

    In best practices section, typo: ‘Never expose “informtion” on URLs’.

    Great documentation. Thanks!

    Reply

Ask Questions & Share Feedback Cancel reply

Please do not submit a comment only to say "Thank you"

*Want to Post Code Snippets or XML content? Please use [java] ... [/java] tags otherwise code may not appear partially or even fully. e.g.
[java] 
public static void main (String[] args) {
...
}
[/java]

Learn REST

  • What is REST?
  • REST Constraints
  • REST Resource Naming Guide

Guides

  • Caching
  • Compression
  • Content Negotiation
  • HATEOAS
  • Idempotence
  • Security Essentials
  • Versioning
  • Statelessness

Tech – How To

  • REST API Design Tutorial
  • Create REST APIs with JAX-RS 2.0

FAQs

  • PUT vs POST
  • N+1 Problem
  • ‘q’ Parameter

Resources

  • Comparing SOAP vs REST APIs
  • HTTP Methods
  • Richardson Maturity Model
  • HTTP Response Codes
    • 200 (OK)
    • 201 (Created)
    • 202 (Accepted)
    • 204 (No Content)

References

  • The dissertation by Roy Thomas Fielding
  • Uniform Resource Identifier (URI, URL, URN) [RFC 3986]
  • Internet MediaTypes
  • Web Application Description Language (WADL)

Meta Links

  • About
  • Contact Us
  • Privacy Policy

Blogs

  • How To Do In Java
Creative Commons License
This work by RESTfulAPI.net is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License.