Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
CONTENTS
WHAT IS A RESTFUL API? According to research by SmartBear presented in their State of APIs
An Application Programming Interface (API) is a set of clearly defined Report 2016:
methods of communication between various software components. A
• Security is the #1 technology challenge teams want to see
good API makes it easier to develop a computer program by providing
solved; 41.2% of respondents say security is the biggest API
all the building blocks. While the specifications vary between various
technology challenge they hope to see solved.
APIs, the end goal is to provide value to the programmer through
utilization of the services gained from using an API. • Security is the #4 technology area expected to drive the most
API growth in the next two years; 24% of API providers say digital
REST (or REpresentational State Transfer) is an architectural style that
DZO N E .CO M/ RE FCA RDZ
security will drive the most API growth in the next two years.
evolved as Fielding wrote the HTTP/1.1 and URI specs and has proven
to be well-suited for developing distributed hypermedia applications. • 40.4% of API providers are currently utilizing a tool for testing
While REST is more widely applicable, it is most commonly used API security.
within the context of communicating with services via HTTP.
Request a Demo
API security is the single biggest challenge organizations want to 42C API Protection Firewall
see solved in the years ahead, and solving the security challenge is
expected to be a catalyst for growth in the API world.
1
42Crunch adds the “Sec”
to your DevOps initiative.
Agile, rapid API development and deployment must be secure.
Request a Demo
With the explosive growth of RESTful APIs, the security layer is often requests that have invalid return addresses. DOS attacks can
the one that is most overlooked in the architectural design of the API. render a RESTful API into a non-functional state if the right security
measures are not taken.
Today, even if your API is not exposed to the public, it still might be
accessible by others. This means that REST API security is getting
more and more valuable and important. Consider that someone
succeeds in making a DOS attack- it means that all the connected
clients (partners, apps, mobile devices, and more) will not be able
to access your API.
ANTI-FARMING
methods must be accessed by authenticated users only, and for REST API AUTHENTICATION TYPES OVERVIEW
each such call, an audit must be saved. RESTful applications rely on the underlying security of the API
ecosystem rather than including security within the REST architecture
TLS
style. In addition to securing RESTful API calls with the HTTPS protocol,
Transport Layer Security (TLS) and its predecessor, Secure
session-based authentication should be utilized. Currently, most
Sockets Layer (SSL), are cryptographic protocols that provide
RESTful applications leverage OAuth 2.0 and JWT is the newcomer that
communications security over a computer network.
is gaining more and more popularity with API developers.
• The connection is private (or secure) because symmetric easy to do as parameters, they are more secure as headers.
• The connection ensures integrity because each message To receive authorization, the client sends the userid and password,
transmitted includes a message integrity check using a separated by a single colon (“:”) character, within a Base64
message authentication code to prevent undetected loss or encoded string in the credentials.
alteration of the data during transmission.
If the user agent wishes to send the userid “Aladdin” and password
DOS AT TACKS “open sesame,” it would use the following header field:
In a Denial of Service (DOS) attack, the attacker usually sends
Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==
excessive messages asking the network or server to authenticate
The Basic authentication scheme is not a secure method of user protocol that provides authorization workflow over HTTP and
authentication, nor does it in any way protect the entity, which is authorizes devices, servers, applications, and APIs with access tokens
transmitted in cleartext across the physical network used as the carrier. instead of credentials. OAuth gained popularity thanks to Facebook,
Google, Microsoft, and Twitter, who allow usage of their accounts to
The most serious flaw in Basic authentication is that it results in the
be shared with third-party applications or websites.
essentially cleartext transmission of the user’s password over the
physical network. OAuth 2.0 can be used to read data of a user from another
application without compromising the user’s personal and sensitive
Because Basic authentication involves the cleartext transmission of
data, like user credentials. It also supplies the authorization
passwords, it should be used over TLS or SSL protocols (HTTPS) in
workflow for web, desktop applications, and mobile devices.
order to protect sensitive or valuable information.
The previous versions of this spec, OAuth 1.0 and 1.0a, were much
API KEYS
more complicated than OAuth 2.0. The biggest change in the latest
Not any formal standard, but something in common practice by API
version is that it’s no longer required to sign each call with a keyed
providers, and supported by API management providers. It is the
hash. The most common implementations of OAuth use one or both
usage of one or two keys that accompany every API call. API keys
of these tokens instead:
are really more about identifying the application and user over
being about security, but is perceived as secure by many. • access token: sent like an API key, it allows the application to
access a user’s data; optionally, access tokens can expire.
Public REST services without access control run the risk of being
farmed, leading to excessive bills for bandwidth or compute cycles. • refresh token: optionally part of an OAuth flow, refresh
API keys can be used to mitigate this risk. They are also often used by tokens retrieve a new access token if they have expired.
Since an access token is like a special type of API key, the most likely
clients are given access in accordance to a purchased access plan.
place to put it is the authorization header, like so:
Typically, an API key gives full access to every operation an API can Authorization: Bearer 1234567890abcdef
perform, including writing new data or deleting existing data. If you
use the same API key in multiple apps, a broken app could destroy JSON WEB TOKEN (JWT)
your users’ data without an easy way to stop just that one app. Some JSON Web Token (JWT) is an open standard extension of OAuth 2.0
apps let users generate new API keys, or even have multiple API keys for creating access tokens that assert some number of claims.
with the option to revoke one that may have gone into the wrong
hands. The ability to change an API key limits the security downsides. Whereas API keys and OAuth tokens are always used to access APIs,
JSON Web Tokens (JWT) can be used in many different scenarios.
SECURITY ASSESSMENT MARKUP LANGUAGE (SAML) In fact, JWT can store any type of data, which is where it excels in
The Service Provider agrees to trust the Identity Provider to Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXV
authenticate users. In return, the Identity Provider generates an CJ9. eyJob21lcGFnZSI6Imh0dHBzOi8vemFwaWVyLmNvbSIsInRhZ
aaaaaaaaaa.bbbbbbbbbbb.cccccccccccc
6. iat: Issued At (Type: Number – DateTime). Denotes the
numeric format of issued date and time.
Since there are three parts separated by a (.), each section is
created differently. 7. jti: JWT ID (Type: String). The unique identifier for the
JWT token.
The header carries two parts: the type, which is JWT, and the JSON Web Token Registry or defined as a URI that contains a
{
In this JSON, the value of the “typ” key specifies that the object
“sub”: “AB324901”,
is a JWT, and the value of the “alg” key specifies which hashing “name”: “Michael”,
algorithm is being used to create the JWT signature component. In “admin”: true,
“exp”: 2601638760
our example, we’re using the HMAC-SHA256 algorithm, a hashing
}
algorithm that uses a secret key, to compute the signature.
The Base64 of the above encoded form should look like:
Now all that is left is to Base64 Encode this JSON and we have the
eyJzdWIiOiJBQjMyNDkwMSIsIm5hbWUiOiJNaWNoYWVsIiwiYWRtaW
first part of our JSON web token:
4iOnRydWUsImV4cCI6MjYwMTYzODc2MH0
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9
SIGNATURE
PAYLOAD To create the signature part, you have to take the encoded header,
The second part of the token is the payload, which contains the the encoded payload, a secret, and the algorithm specified in the
claims. Claims are statements about an entity (typically the user) header, and sign it.
and additional metadata. Notice that the claim names are only
For example, if you want to use the HMAC SHA256 algorithm, the
three characters long, as JWT is meant to be compact.
signature will be created in the following way:
There are three types of claims: reserved, public, and private claims.
data = base64urlEncode( header ) + “.” + base64urlEncode(
• Reserved claims: These are a set of predefined claims which payload )
signature = Hash( data, secret );
are not mandatory but recommended, to provide a set of
The signature is used to verify that the sender of the JWT is who Whenever the user wants to access a protected route or resource,
they say they are, and to ensure that the message wasn't changed the user agent should send the JWT, typically in the Authorization
along the way. header using the Bearer schema. The content of the header should
look like the following:
PUTTING IT ALL TOGETHER
The output is three Base64 strings separated by dots that can be Authorization: Bearer <token>
The following shows a JWT that has the previous header and will check for a valid JWT in the Authorization header, and if it's
payload encoded, and it is signed with a secret. present, the user will be allowed to access protected resources.
As JWTs are self-contained, all the necessary information is there,
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJBQjMyNDk reducing the need to query the database multiple times.
wMSIsIm5hbWUiOiJNaWNoYWVsIiwiYWRtaW4iOnRydWUsImV4cCI6MjY
zODc2MH0.o79bwAmsmfxmORr6G_TpAawSv5nGu6UoB9QfT6XYVws
This allows you to fully rely on data APIs that are stateless, and even
make requests to downstream services. It doesn't matter which
domains are serving your APIs, so Cross-Origin Resource Sharing
(CORS) won't be an issue as it doesn't use cookies.
• Information Exchange: JSON Web Tokens are a good way of SECURE YOUR REST API: BEST PRACTICES
securely transmitting information between parties. Because RATE LIMITING
JWTs can be signed—for example, using public/private key An API key is a valuable strategy to provide a level of identity to
pairs—you can be sure the senders are who they say they are. consumers of a RESTful API. In addition to providing tiered services,
Additionally, as the signature is calculated using the header another benefit of using API keys is the ability to throttle usage of the
and the payload, you can also verify that the content hasn't API, and the logging of all API calls made allows API providers to limit
been tampered with. the rate of consumption for all API users. Putting caps on the number
of API calls that can be made for any single API resource, dictating
HOW DO JSON WEB TOKENS WORK?
consumption by the second, minute, day, other relevant constraint.
In authentication, when the user successfully logs in using their
credentials, a JSON Web Token will be returned and must be saved AUTHORIZATION
locally (typically in local storage, but cookies can be also used), PROTECT HT TP METHODS
instead of the traditional approach of creating a session in the RESTful APIs often use GET (read), POST (create), PUT (replace/
server and returning a cookie. update), and DELETE (to delete a record).
Not all of these are valid choices for every single resource collection, the URL, query string, headers, cookies, form fields, and hidden
user, or action. Make sure the incoming HTTP method is valid for fields, to try to bypass the site’s security mechanisms.
the session token/API key and associated resource collection,
Common names for common input tampering attacks include:
action, and record.
forced browsing, command insertion, cross site scripting, buffer
WHITELIST ALLOWABLE METHODS overflows, format string attacks, SQL injection, cookie poisoning,
It is common with RESTful services to allow multiple methods for a and hidden field manipulation.
given URL for different operations on that entity.
XML INPUT VALIDATION
For example, a GET request might read the entity, while PUT would XML-based services must ensure that they are protected against
update an existing entity, POST would create a new entity, and common XML-based attacks by using secure XML-parsing.
DELETE would delete an existing entity.
This typically means protecting against XML External Entity attacks,
It is important for the service to properly restrict the allowable verbs XML-signature wrapping, etc.
such that only the allowed verbs would work, while all others would
See http://ws-attacks.org for examples of such attacks.
return a proper response code (for example, a 403 Forbidden).
Not every user has a right to every web service. This is vital, as you To make sure the content of a given resource is interpreted correctly
don't want administrative web services to be misused: by the browser, the server should always send the Content-Type
header with the correct Content-Type, and the Content-Type header
https://example.com/admin/exportAllData
should preferably include a charset.
Assisting the user makes the most sense, as the most common
HTTP STATUS CODES
scenario is "problem exists between keyboard and chair" (PEBKAC).
HTTP defines status codes. When you design your REST API, don't
URL VALIDATIONS just use 200 for success or 404 for error.
Web applications/web services use input from HTTP requests (and
Here are some guidelines to consider for each REST API status
occasionally files) to determine how to respond.
return code. Proper error handling may help to validate the incoming
Attackers can tamper with any part of an HTTP request, including requests and better identify the potential security risks.
Guy is an architect focusing on distributed and cloud systems with over 20 years of experience in software development
in a variety of sectors, including medical and healthcare, cybersecurity, and fintech.
DZone, Inc.
DZone communities deliver over 6 million pages each 150 Preston Executive Dr. Cary, NC 27513
month to more than 3.3 million software developers, 888.678.0399 919.678.0300
architects and decision makers. DZone offers something for
Copyright © 2017 DZone, Inc. All rights reserved. No part of this publication
everyone, including news, tutorials, cheat sheets, research
may be reproduced, stored in a retrieval system, or transmitted, in any form
guides, feature articles, source code and more. "DZone is a or by means electronic, mechanical, photocopying, or otherwise, without
developer’s dream," says PC Magazine. prior written permission of the publisher.