Rest api authorization best practices

Rest api authorization best practices DEFAULT
API security best practices

With the increasing demand for data-centric projects, companies have quickly opened their data to their ecosystem, through SOAP or REST APIs. APIs are the doors to closely guarded data of a company, creating the following challenge: how can we keep the doors open for the ecosystem and sealed off from hackers at the same time?

API security best practices: 12 simple tips to avoid security risks and secure your APIs.

1. Encryption

Be cryptic. Nothing should be in the clear, for internal or external communications.

You and your partners should cipher all exchanges with TLS (the successor to SSL), whether it is one-way encryption (standard one-way TLS) or even better, mutual encryption (two-way TLS).

Use the latest TLS versions to block the usage of the weakest cipher suites.

2. Authentication

Don’t talk to strangers. You should always know who is calling your APIs, at least through an API key (asymmetric key) or basic access authentication (user/password), to increase the difficulty to hack your system.

3. OAuth & OpenID Connect

Delegate all Responsibility. A good manager delegates responsibility and so does a great API. You should be delegating authorization and/or authentication of your APIs.

What is OAuth? It is a magical mechanism preventing you from having to remember ten thousand passwords. Instead of creating an account on every website, you can connect through another provider’s credentials, for example, Facebook or Google.

For APIs, it works the same way: the API provider relies on a third-party server to manage authorizations. The consumer doesn’t give their credentials, but instead gives a token provided by the third-party server. It protects the consumer as they don’t disclose their credentials, and the API provider doesn’t need to care about protecting authorization data, as it only receives tokens.

OAuth is a commonly used delegation protocol to convey authorizations. To secure your APIs even further and add authentication, you can add an identity layer on top of it: this is the Open Id Connect standard, extending OAuth 2.0 with ID tokens.

4. Call Security Experts

You should use experienced Antivirus systems or ICAP (Internet Content Adaptation Protocol) servers to help you with security.

5. Monitoring: Audit, Log, and Version

Be a stalker. You need to be ready to troubleshoot in case of error: to audit and log relevant information on the server — and keep that history as long as it is reasonable in terms of capacity for your production servers. You should turn your logs into resources for debugging in case of any incidents. Also, monitoring dashboards are highly recommended tools to track your API consumption.

Do not forget to add the version on all APIs, preferably in the path of the API, to offer several APIs of different versions working and to retire and depreciate one version over the other.

6. Share as Little as Possible

Be paranoid. Display as little information as possible in your answers, especially in error messages. Lock down email subjects and content to pre-defined messages that can’t be customized. Because IP addresses can give locations, keep them for yourself.

Use IP Whitelist and IP Blacklist, if possible, to restrict access to your resources. Limit the number of administrators, separate access into different roles, and hide sensitive information in all your interfaces.

7. System Protection with Throttling and Quotas

Throttle yourself. You should restrict access to your system to a limited number of messages per second, to protect your backend system bandwidth according to your servers’ capacity.

You should also restrict access by API and by the user (or application) to be sure that no one will abuse the system or anyone API in particular.

Throttling limits and quotas – when well set – are crucial to prevent attacks coming from different sources flooding your system with multiple requests (DDOS – Distributed Denial of Service Attack).

8. Data Validation

Be picky and refuse surprise gifts, especially if they are big. You should check everything your server accepts. Be careful to refuse any added content, data that is too big, and always check the content that consumers are sending you. Use JSON or XML schema validation and check that your parameters are what they should be (string, integer…) to prevent any SQL injection or XML bomb.

9. Infrastructure

Network and be up to date. A good API should lean on a good security network, infrastructure, and up-to-date software (for servers, load balancers) to be solid and always benefit from the latest security fixes.

10. OWASP top 10

Avoid wasps. The OWASP (Open Web Application Security Project) top 10 is a list of the 10 worst vulnerabilities, ranked according to their exploitability and impact. In addition to the above points, to review your system, make sure you have secured all the OWASP vulnerabilities.

11. API Firewalling

Build a wall. For some people, building a wall can solve all the immigration problems. This is the case, for APIs at least! Your API security should be organized into two layers:

    • The first layer is in DMZ, with an API firewall to execute basic security mechanisms like checking the message size, SQL injections, and any security based on the HTTP layer, blocking intruders early. Then forward the message to the second layer.
    • The secondlayer is in LAN with advanced security mechanisms on the content of data.

12. API Gateway (API Management)

Gateway to heaven. All the above mechanisms are long to implement and maintain. Instead of reinventing the wheel, you should opt for a mature and performant API Management solution with all these options to save your money, time and resources, and increase your time to market. An API Gateway will help you secure, control, and monitor your traffic.

In addition to helping you secure your APIs easily, an API Management solution will help you make sense of your API data, to take technical and business decisions: the key to success!

Now you know more about the basic mechanisms to protect your APIs! Have fun securing your APIs, hopefully with a great API Management solution.

Read about how AI helps secure your APIs.

Click Here

Carole Kennel

Digital Success Specialist  Carole has more than 10 years of experience working with different Axway products (Integrator, Interchange, Financial Exchange, Accounting Integrator, API Management_ from a Support, Presales and Training point of view. She now is happy to help customers on their digital journey.  

Sours: https://blog.axway.com/api-security/api-security-best-practices

Nearly every API needs to know the identity of the application or person making a request. This foundation of API security can be used to track rate limits, ensure proper audit logs are in place, and to authorize the appropriate access for each identity. 

In this post, we’ll explore authentication methods, how to keep tokens safe, and what comes next.

Common API Authentication Methods

You may be authenticating to an existing system, an API gateway, or both. What your internal infrastructure looks like should not impact how the API is seen by clients. There are a few common patterns, which can be generalized into static and dynamic approaches. 

As you review APIs, you’ll see these various approaches:

  • Static token: Your classic API key, this identifier is a difficult-to-guess alphanumeric string. When supplied with a request (usually in a header, but other methods are possible), you can typically identify the application, if not the end user. If this static token is discovered, another party could have access until revoked.
  • Static token and secret: An alternative to the API key is to pair it with another token. The two must be used in combination. They could be sent over Basic Auth, which essentially makes them a username and password. Or, you can use the secret to cryptographically sign a request.
  • Generated access token: Lastly, you can use short-lived tokens, which are generated from static tokens. This approach is used by OAuth 2.0, for example, to provide access with less possibility of token exposure.

You can see the security tradeoffs within these methods. Yet, any authentication method can be securely implemented if both parties can keep keys or tokens protected.

Consumers and Providers Must Protect the Keys

You wouldn’t keep the keys to your house taped to your front door. Similarly, you need to keep your API keys and tokens from becoming compromised. By their nature, these are shared secrets between the API provider and consumer. That makes for additional difficulty, because there are at least two parties that need to safely store the credentials.

There are some basics that apply to both consumer and provider: don’t check secrets into code repositories, especially those that are public. Even if it’s hard to discover, security by obscurity is not a long-term strategy. In fact, some API and cloud providers routinely search public resources for private keys, so they can proactively deactivate them and alert the API consumer.

On the provider side, you’ll need a secure key store as part of your API management solution. You will use it to confirm credentials with each request and manage token expiration. It’s technically possible to run your own encrypted database for keys, but a generic solution could be difficult to maintain.

In addition to both sides storing the keys securely, you’ll need to consider situations where a key must be public. The most common example is an API request that originates from a web browser. For example, Google Maps embeds keys in JavaScript, which any end user can discover via View Source.

One solution is to include different access levels for keys. Those that must be public should be restricted to read-only and perhaps only certain resources. That brings the discussion beyond authentication to the next step, authorization.

Choose an API Auth Standard

OAuth 2.0 does not technically perform authentication. This authorization standard is used alongside authentication—and this step of determining privilege is an important part of your API security.

Perhaps the biggest mistake API providers can make with security is rolling their own approach. Use existing standards because of their advantages:

  • Tooling exists to implement them easily and correctly
  • Engineers are more likely to be familiar with them (as consumers and providers)
  • They are hardened by the scrutiny of the security community

There are multiple flavors of OAuth, which allow for the various authentication methods mentioned earlier. OAuth can be used at the application level, or be used to determine user-level access. That means end users of applications will not need to copy keys or even know the protocols used to exchange data behind the scenes. In addition, scopes allow you to restrict or expand the access level.

To take the next steps with your API authentication and authorization, you can read the OAuth Overview Series on API Academy.

Recent Posts

Sours: https://apiacademy.co/2021/03/api-authentication-best-practices/
  1. Fowler, ca real estate
  2. Rubber mulch calculator home depot
  3. Gears 5 won t launch
  4. People get ready lyrics

Best practices for REST API security: Authentication and authorization

Most apps that use a modern web framework will have one or more REST APIs. REST is a simple and flexible way of structuring a web API. It’s not a standard or protocol, but rather a set of architectural constraints.

There are three reasons you might find yourself writing a REST API:

  • To give a networked client that you built—for instance, a single-page app in the browser or on a mobile app on a phone—access to data on your server.
  • To give end users, both people and programs, programmatic access to data managed by your application.
  • To let the many services that make up your app’s infrastructure communicate with each other.

Any API built for these reasons can be abused by malicious or reckless actors. Your app will need an access policy—who can view or modify data on your server? For instance, only the author [Editor’s note: the editors, too] of a blog post should be able to edit it, and readers should only be able to view it. If anyone could edit the post you’re reading, then we’d get vandals, link farmers, and others changing and deleting things willy nilly. 

This process of defining access policies for your app is called authorization. In this article, we’ll show you our best practices for implementing authorization in REST APIs.

Always use TLS

Every web API should use TLS (Transport Layer Security). TLS protects the information your API sends (and the information that users send to your API) by encrypting your messages while they’re in transit. You might know TLS by its predecessor’s name, SSL. You’ll know a website has TLS enabled when its URL starts with instead of .

Without TLS, a third party could intercept and read sensitive information in transit, like API credentials and private data! That undermines any of the authentication measures you put in place.

TLS requires a certificate issued by a certificate authority, which also lets users know that your API is legitimate and protected. Most cloud providers and hosting services will manage your certificates and enable TLS for you. If you host a website on Heroku, enabling TLS is a matter of clicking a button. If you host on AWS, AWS Certificate Manager combined with AWS Cloudfront will take care of you. If you can, let your host manage your certificates for you—it means no hassle at all and every API call will be automatically secured.

If you’re running your own web server without any third-party services, you’ll have to manage your own certificates. The easiest way to do this is with Let’s Encrypt, an automated certificate authority. Let’s Encrypt has a helpful getting started guide.

Use OAuth2 for single sign on (SSO) with OpenID Connect

Nearly every app will need to associate some private data with a single person. That means user accounts, and that means logging in and logging out. In the past, you may have written login code yourself, but there’s a simpler way: use OAuth2 to integrate with existing single sign-on providers (which we’ll refer to as “SSO”).

SSO lets your users verify themselves with a trusted third party (like Google, Microsoft Azure, or AWS) by way of token exchange to get access to a resource. They’ll log in to their Google account, for instance, and be granted access to your app.

Using SSO means that:

  • You don’t have to manage passwords yourself! This reduces the user data you store and therefore less data to be exposed in the event of a data breach.
  • Not only do you avoid implementing login and logout, but you also avoid implementing multi-factor authentication.
  • Your users don’t need a new account and new password—they’ve already got an account with an SSO provider like Google. Less friction at signup means more users for you.

OAuth2 is a standard that describes how a third-party application can access data from an application on behalf of a user. OAuth2 doesn’t directly handle authentication and is a more general framework built primarily for authorization. For example, a user might grant an application access to view their calendar in order to schedule a meeting for you. This would involve an OAuth2 interaction between the user, their calendar provider, and the scheduling application.

In the above example, OAuth2 is providing the mechanism to coordinate between the three parties. The scheduling application wants to get an access token so that it can fetch the calendar data from the provider. It obtains this by sending the user to the calendar provider at a specific URL with the request parameters encoded. The calendar provider asks the user to consent to this access, then redirects the user back to the scheduling application with an authorization code. This code can be exchanged for an access token Here’s a good article on the details of OAuth token exchange..

You can implement authentication on top of OAuth2 by fetching information that uniquely identifies the user, like an email address.

However, you should prefer to use OpenID Connect. The OpenID Connect specification is built on top of OAuth2 and provides a protocol for authenticating your users. Here’s a getting started guide on OAuth2 with OpenID Connect. 

Unfortunately, not every identity provider supports OpenID Connect. GitHub, for instance, won’t let you use OpenID Connect. In that case, you’ll have to deal with OAuth2 yourself. But good news—there’s an OAuth2 library for your programming language of choice and plenty of good documentation!

Tips for OAuth

You can use OAuth2 in either stateless or stateful modes. Here’s a good summary on the differences. 

The short version: it is typically easier to correctly implement a stateful backend to handle OAuth flows, since you can handle more of the sensitive data on the server and avoid the risk of leaking credentials. However, REST APIs are meant to be stateless. So if you want to keep the backend this way, you either need to use a stateless approach or add an additional stateful server to handle authentication.

If you opt to implement the stateless approach, make sure to use its Proof Key for Code Exchange mode, which prevents cross-site request forgery and code injection attacks.

You’ll need to store users’ OAuth credentials. Don’t put them in local storage—that can be accessed by any JavaScript running on the page! Instead, store tokens as secure cookies. That will protect against cross-site scripting (XSS) attacks. However, cookies can be vulnerable to cross-site request forgery (CSRF), so you should make sure your cookies use .

Use API keys to give existing users programmatic access

While your REST endpoints can serve your own website, a big advantage of REST is that it provides a standard way for other programs to interact with your service. To keep things simple, don’t make your users do OAuth2 locally or make them provide a username/password combo—that would defeat the point of having used OAuth2 for authentication in the first place. Instead, keep things simple for yourself and your users, and issue API keys. Here’s how:

  1. When a user signs up for access to your API, generate an API key:


  2. Store this in your database, associated with your user.
  3. Carefully share this with your user, making sure to keep it as hidden as possible. You might want to show it only once before regenerating it, for instance.
  4. Have your users provide their API keys as a header, like


  5. To authenticate a user’s API request, look up their API key in the database.

When a user generates an API key, let them give that key a label or name for their own records. Make it possible to later delete or regenerate those keys, so your user can recover from compromised credentials.

Encourage using good secrets management for API keys

It’s the user’s responsibility to keep their secrets safe, but you can also help! Encourage your users to follow best practices by writing good sample code. When showing API examples, show your examples using environment variables, like .

from requests.auth import HTTPBasicAuth

import requests

import os

api_key = os.environ.get(“MY_APP_API_KEY”)

auth = HTTPBasicAuth(‘apikey’, api_key)

req = requests.get(“<https://myapp.example.com>,

        headers={‘Accept’: ‘application/json’},

        auth=auth)

(If you, like Stripe, write interactive tutorials that include someone’s API key, make sure it’s a key to a test environment and never their key to production.)

Choose when to enforce authorization with request-level authorization

We’ve been speaking about API authorization as if it will apply to every request, but it doesn’t necessarily need to. You might want to add request-level authorization: looking at an incoming request to decide if the user has access to your resources or not. That way, you can let everyone see resources in , or choose certain kinds of requests that a user needs to be authenticated to make.

The best way to do this is with request middleware. Kelvin Nguyen over at Caffeine Coding has a nice example here.

Configure different permissions for different API keys

You’ll give users programmatic API access for many different reasons. Some API endpoints might be for script access, some intended for dashboards, and so on. Not every endpoint will need the user’s full account access. Consider having several API keys with different permission levels.

To do this, store permissions in the database alongside the API keys as a list of strings. Keep this simple at first: “read” and “write” are a great start! Then, add a request middleware that fetches the user and the permissions for the key they’ve submitted and checks the token permissions against the API.

Leave the rest of the authorization to the app/business logic

Now that you’ve started adding authorization to your API, it can be tempting to add more and more logic to handle more checks. You may end up with nested if-statements for each resource and permission level. The problem with that is that you may end up duplicating application logic. You’ll find yourself fetching database records in the middleware, which is not ideal!

Instead, leave that level of authorization logic to your application code. Any authorization checks made on resources should happen in the app, not in the middleware. If you need to handle complex authorization logic in your app, use a tool like Oso, which will let you reduce your authorization policy to a few simple rules.

There’s always more to discuss with authentication and authorization, but that’s enough to get started! We hope these tips help you design useful and secure API endpoints.

In summary: use good libraries

We’ve given you plenty of specific advice, but it all comes back to one point—try to offload as much work as you can to trusted libraries. Authorization is tricky, and we’d like to minimize the number of places in which we can make a mistake. You have plenty of great tools at hand to help with authorization, so make the best use of them that you can! Much like with cryptography: study up, and then do as little as possible yourself.

Tags: api, authentication, authorization, rest api
Sours: https://stackoverflow.blog/2021/10/06/best-practices-for-authentication-and-authorization-for-rest-apis/
🔐 API Security Best Practices - How to protect your RESTful APIs

Dear Geek,

 

We are building an API and I am confused as to what kind of security we need? There are so many out there being used (OAuth 1.0a, OAuth 2.0, SAML, username/password, API Key, JWT, and plenty of others) and I am not sure what the best practices are for implementing API authentication. What advice to you have?

 

—   OVERWHELMED BY SECURITY OPTIONS

Dear Overwhelmed,

There really are a lot of options for security when designing and architecting APIs, but I can help you narrow down things and point you to some best practices for API authentication!

API Strategy

There are several things to take into consideration when looking at security for APIs and it is important to make sure it aligns with your organization’s overall security strategy.

Let’s look at a few of the most frequently used methods of API authentication.

No Security

You may be thinking about opening up your API to everyone with no security. I would not do this. API security risks are more common than you think. Even if your data is non-sensitive and you may not care who sees your data, you should be thinking about rate limiting in order to protect your resources.

Instead, look into using , which I talk about next.

API Key

This is an option if the data you are presenting is non-sensitive. An  is a unique value generated for use by an API client.  is not really authentication as it is a way of filtering requests by client. You still have no idea who is using your API with that . Adding an  requirement to your API will at least allow you to limit the number of requests per registered client.

Allowing the client to reset the API Key is an important feature as the key might become compromised.

Most APIs will require true authentication which is when a lot architects find themselves looking at  which I cover next.

OAuth 2.0

You will see this form of Authentication used on a lot of APIs. This involves an end user authenticating and getting a token that can be used by the client to authenticate with your API. I won’t go into details here as the  process can be challenging to understand if you’re new to this. I will tell you that there are several different OAuth flows and you will need to work with your  provider to see which flows they support.  does have flows that support server-to-server communication but not all organizations and providers will have these flows enabled.

The one downside to some  flows is that it can get pretty ugly. You probably have some awesome designs showing a nice branded login flow for your app or website. But the reality is you will get thrown out of that into something much less branded before completing and getting back to your app.

The other downside is the additional screens themselves. Depending on what the timeout is for your app or website. You might have 3-5 screens and a lot more clicks just to open a link.

There is not much you can do about the downsides as security is more important than aesthetics.

My only point to pointing out the downsides is that you do want to be aware of what  flows are supported (and enabled) for your API and what it means for your clients if they are turned off.

Username/Password

Some APIs authenticate with username and password, often in the form of Basic Auth in the header. Even when combined with SSL, this is not a recommended solution for securing your API. You will often see this with older APIs that were created using a webpage paradigm. This also often led to APIs being created that were session-based (or worse, session-based with cookies).

Speaking of session-based APIs. Please don’t do this! RESTful APIs are designed to be stateless!

If you are thinking about doing this, first see if your API falls into the one exception to this rule:

THERE IS NO EXCEPTION.

Don’t do it.

For the love of all that is good. Just don’t.

Others

Here are a few of the other authentication methods you might find out there.

AuthComments
JWTUses a JWT to authenticate. Easy to setup and use but user must manually manage token creation, etc. More secure alternative to API Keys.
OAuth 1.0aLess secure than OAuth 2.0. Just use OAuth 2.0
SAMLUsed for some SSO system. Difficult to use and manage for APIs

API Authentication Recommendations

  • Use  but with flows enabled to support server-to-server, device authorization, etc., so you can ensure your API Client are secure while also enabling a great user experience!
  • Use API Key authentication with caution if publishing non-sensitive data
  • Avoid username/password authentication.
  • Avoid maintaining state in your API calls.

Check out more questions and answers here!


Ask-a-Geek questions are answered by Brenton House, an API and Mobile Geek who has been working in the development community for 25+ years.

Want to learn more about practical to-do’s when developing APIs? Read the top 10 security considerations for APIs.

Brenton House

https://brenton.house

Axway Developer Relations Lead - With 25 years of experience in the development world, Brenton House leads Developer Relations for Axway's API and mobile products. He has worked closely with many clients across various industries including broadcasting, advertising, retail, financial services, transportation, publishing, supply chain, and non-profits. Brenton's passion for everything API and mobile combined with his strategy and design experience has enabled him to help developers create captivating products that inspire and delight audiences.

Sours: https://blog.axway.com/api-security/api-authentication-best-practices

Practices best api rest authorization

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.

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.

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 or .

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/oauth2https://swagger.io/docs/specification/authentication/oauth2/https://cheatsheetseries.owasp.org/

Please follow and like us!

Sours: https://dzone.com/articles/security-best-practices-for-rest-apis
9 best practices of REST API development

REST API 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 sessions.

Instead, each API request should come with some sort of authentication credentials that must be validated on the server for every request.

1. 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:

  • 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.
  • 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.
  • The 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.
  • Complete Mediation: A system should validate access rights to all its resources to ensure that they’re allowed and should not rely on the 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.
  • Open Design: This principle highlights the importance of building a system in an open manner—with no secret, confidential algorithms.
  • 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.
  • 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.
  • 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.

2. Best Practices to Secure REST APIs

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

2.1. 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.

2.2. Always Use HTTPS

By always using SSL, the authentication credentials can be simplified to a randomly generated access token. The token 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.

2.3. Use Password Hash

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

2.4. 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.

The above URL exposes the API key. So, never use this form of security.

2.5. 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 behalf.

2.6. Consider Adding Timestamp in Request

Along with other request parameters, you may add a request timestamp as an HTTP custom header in API requests.

The server will compare the current timestamp to the request timestamp and only accepts the request if it is after a reasonable timeframe (30 seconds, perhaps).

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

2.7. Input Parameter Validation

Validate request parameters on the very first step, before it reaches application logic. Put strong validation checks and reject the request immediately if validation fails.

In API response, send relevant error messages and examples of correct input format to improve user experience.

Sours: https://restfulapi.net/security-essentials/

Similar news:

When machines ask each other for information online, they don’t need elaborate browser interfaces or clickable buttons. They just need raw data in a machine-readable format. Today, many applications get the data they need via a REST API–a powerful way of serving up information online that underpins many modern online services.

Like any technology, REST APIs bring their own unique security challenges. The question that remains is how to reduce those vulnerabilities.

What is a REST API?

REST stands for Representational State Transfer, and it’s more of an approach to design and communication than a single tool or programming library. RESTful programming is stateless and provides a uniform interface, commonly using HTTP-based URLs with query parameters that mask the back-end infrastructure from the user. Responses typically come back as simple JSON-based key/value pairs, but APIs can support any type of content, including XML, test documents, or even images. Front-end software can then serve that data up in a format appropriate for the user.

REST APIs are the glue that holds the modern cloud-based software economy together. They can serve straightforward information, even from a large data set. Your software can query Amazon’s API to get product pricing, for example, or get a geographic location from Google Maps. Alternatively, it can query a complex back-end service requiring lots of computing power. You want a service to tag a photograph with descriptive words or recognize someone’s face? Microsoft’s REST-based API does that.

All those examples have something in common: they provide access to information that would be impossible or prohibitively expensive for an individual company to build on its own. Companies can take that third-party information and use it to create new applications that would have been out of reach before. Of course, many of those third-parties charge for the privilege, pricing their API by query volume or by the feature set that a customer uses.

That data needs to be secure, though. A poorly protected API can be a major point of vulnerability for an organization, particularly those handling sensitive data. Making public pricing data available to anyone via an API call for convenience is fine. Letting everyone query patient records at your medical clinic? Not so much.

How do you secure a REST API?

The first step in securing an API is to ensure that you only accept queries sent over a secure channel, like TLS (formerly known as SSL). Communicating with a TLS certificate protects all access credentials and API data in transit using end-to-end encryption.

API keys are another step toward securing a REST API. You can use them for authentication. You can also use them to track an account’s usage of an API, enabling you to charge by volume and features. An API key is a unique string that serves as the access credential for the API, and you’ll often create it manually using a web interface to the service that you’re querying.

The problem with API keys is that they’re supposed to be secret, but often aren’t. Once someone else sees it, you have to revoke it (assuming you know it’s compromised). Just ask GitHub, which saw users leaking thousands of new API keys every day through exposed repositories.

An alternative form of authentication for REST APIs are tokens. Tokens are typically used by client-side apps and issued by the server. Token authentication differs from cookie-based session management in that it’s typically stateless, allowing you to avoid the need to store session details on the server. This makes it easier to scale out back-end systems using cloud infrastructure, which is exactly what REST APIs are suitable for.

OAuth 2 is a secure token-based authentication mechanism that you can use in an API for secure user authentication and authorization. After initially authorizing a requesting party with passwords or API keys, it then issues an access token. A common token architecture you can use along with OAuth 2 is the JSON Web Token (JWT). JWTs are digitally-signed authentication tokens containing JSON-formatted data about the user.

JWTs can hold more data than traditional API keys thanks to a feature called claims, which is a set of key/value pairs. These key/value pairs hold information such as the token’s expiry date (), the issuer (), the audience for the token (), and the earliest time and date to use it (, or not before time). The claims feature is extensible, so you can create custom claims that you agree with other parties.

That’s useful when federating identity with JWTs. If another online service trusts yours, it can accept a JWT that you already issued for one of your users without ID verification. Given the propensity for developers to mash up multiple REST APIs in a single application, federation is a neat use case for this token-based system.

What are some best practices for developing and testing a REST API?

Rock-solid authentication mechanisms are the beginning for REST API security, but not the end. There are other security best practices to consider during development.

Always use TLS and a security framework that’s well-established and has a large community behind it.

Validate parameter-based inputs for queries. Attackers can change URL parameters, JSON request data, and XML input. Fuzzers can pummel REST APIs with subtle input changes, so be diligent here.

Provide another layer of defence by whitelisting permitted HTTP methods (for example GET, POST, and PUT), and blocking by default those that you might never want someone to access via a public API (like DELETE). Similarly, authenticate individual users for specific actions. You might allow external users a single query, but not the ability to export all data, for example.

Log all failed requests and look for patterns to identify sustained attacks. Also, send relevant error messages with appropriate HTTP status codes to help developers connecting to your service.

Perhaps one of the most important best practices is not to roll your own REST API security. Use an established security framework that applies policies to decide whether the querying party can see the data.

You can create your own REST API using existing SDKs specific to the application framework you’re using. Pythonistas can use Flask or Django, while Java folks can use Spring. These have some security features built-in.

How does Okta use or implement REST APIs?

Okta’s core authentication service is a REST API, which serves a variety of client types. Our mobile applications access it, and we have also created user interfaces that consume API responses and display them in a browser. The Okta API provides functions including multi-factor enrollment and verification, password recovery, and account unlocking.

You can use our REST API to provide identity services for your own applications. If you have an API of your own that you want to protect, you can use our API Access Management service to authenticate access to your own APIs.

Conclusion

REST APIs have lowered the friction that developers used to face when building applications that used remote services. As a de facto approach to sharing and consuming services, they’ve opened up a world of opportunities for startups to build powerful new online services with minimal upfront cost. But whenever you reduce friction, you introduce security dangers. Use APIs to their fullest extent–just be sure you tick all the security boxes along the way.

Learn More

Has this article piqued your interest in REST APIs and authentication? Here is some related content from the Okta developer blog.

We’ve also got a dedicated security site where we’re publishing in-depth security articles and guides that you might find interesting.

Sours: https://developer.okta.com/blog/2019/09/04/securing-rest-apis


6612 6613 6614 6615 6616