2. Overview
Designing Web APIs
● What is API Design (And Why Does It
Matter?)
● API Hierarchy of Needs
● The Developer Experience
● Web API Architectural Styles
● Architectural Layers
● The USE paradigm
● Pagination
● API Security
● Versioning Web API
● Best Practices in API Design
3. What is API Design
(And Why Does It
Matter?)
When I first heard the term, I thought it meant
writing the syntax and code in such a way that it’s
aesthetically appealing. While that’s part of it, API
design involves a lot more than the way you write
your syntax. Designing an API means providing an
effective interface that helps your API’s consumers
better understand, use and integrate with them
while helping you maintain it effectively. Every
product needs a usage manual, and your API is no
exception
let's start with understanding the importance of
why your API should have a great design.
6. API Hierarchy of Needs
● [Usability]Is your API easy to setup and useby developers? You should
make sure that any developer doesn’t take more than 3 secondsto
understand what your API does, 30 secondsto find the correct endpoint
and 3 minutesto start consuming it.
● [Functionality]Does your API workas expected? Your API endpoints
should behave exactly as announced on the documentation. In situations
where unexpected things happen, you should offer easy to consume error
codes. .There are tools that help you test your API thoroughly, so you
don’t have an excuse not to make sure what you ship really works.
SmartBear and Runscope should be under your radar, if you really care
about your API.
7. API Hierarchy of Needs
● [Reliability] Doesyour API workflawlessly repeatedly? You should care
about uptime, rate limiting and throttling, to make sure that every API
call is handled properly according to your usage policies. If you have a
business model around your API, then you should pay extra attention to
this reliability. Products like 3scale offer all these tools so you can sleep
better without worrying if your API is down.
● [Proficiency] Doesyour API increasedevelopers skills? After fulfilling all
the previous needs, you should provide ready to consume documentation
and libraries that educate developers, amplifying their skills. If possible,
offer tools that encourage discussion and participation.You should take a
look at tools like apiary.io and Swagger, that let you describe and
document your API programmatically.
8. API Hierarchy of Needs
● [Creativity] The last layer of the pyramid is related with all the new
things developers can build with your API. Can your API be usedin
unexpectedways?You should foster innovation among your API
developer community so new products can be built by mixing different
APIs together. If you’re too rigid about what developers can or cannot
do, your API popularity will certainly decrease.
So, does yourAPI offer all thecharacteristics fromthe
hierarchyof needs?
10. The Developer Experience
One of the key principles of good API design is that an interface must
provide a seamless and user-friendly developer experience (DX) if it is
to facilitate the creation of applications that add value to the API
owner’s business.
There are a number of key goals that an API designer hoping to create
an excellent DX must be aware of :-
● Facilitating troubleshooting (e.g. providing useful error
messages)
● Simplifying change management (e.g. implementing an API
versioning strategy)
● Improving visibility (e.g. providing log and usage access)
● Establishing trust (e.g. communicating a sense of stability and
longevity)
● important area of focus for DX-friendly API design is minimizing
the learning curve, making it simple for developers to create
powerful applications,
12. Web API Architectural Styles
Generally speaking, the term “Web API” describes any software
interface that is exposed over the Web using the HTTP protocol in
order to facilitate application development (but not limited to any
particular message format, pattern or implementation). In this
lesson, we provide a detailed overview of the main Web API
design styles:
● Tunneling(aka Web Service)
● URI
● Hypermedia
● Event-Driven
13. Web API Architectural Styles
TunnelingStyle The most well-known implementation of the Tunneling API
style (also known as the WebServicestyle) is the SOAPmessaging standard.
SOAP defines an RPC-like interface for application integration and utilizes a
standard called WSDLto describe the interface. Client applications can
generate proxy code based on a WSDLdocument and make calls as if the
remote component is local. A Tunneling/Web Service API normally:
● Exposes an RPC-like interface and provides an interface descriptor for
binding
● Uses an XML-centricmessage format
● Uses HTTP as a transport protocol for a higher application-level
protocol
One of the great advantages of this style is that it is transport-agnostic.
Applications are free to deliver thesameSOAP message over HTTP,JMS or
raw TCP/IPconnections , In addition, SOAP and the WS-* specification set
may be unfamiliar to mobile and Web application developers, resulting in
decreased usage and increased development costs in these communities
14. Web API Architectural Styles
URI StyleThe URI style, arguably the most familiar to application developers,
exhibits these properties:
● An object- or resource-centric API is exposed
● URIs and query parameters are used to identify and filter objects
● CRUD (create, read, update, delete) operations are mapped to HTTP
methods
Thechallengein designinga URI-styleAPI is that:-
it is difficult to map a complex set of application interactions to the simplified
set of four HTTP operations acting upon a resource. This challenge can lead to
URI designs that become increasingly complex, resulting in a steeper learning
curve for developers.
15. Web API Architectural Styles
HypermediaStyle This is similar to the URI style but it utilizes hypermedia to
create interactions focused on tasks rather than on objects. Essentially, these
are browser-based interaction for machines. In much the same way that you
use links to navigate the Web and forms to provide input, a Hypermedia API
provides links to navigate a workflow and template input to request
information. A Hypermedia API:
● Exposes a task-based interface, often incorporating a workflow or
state machine
● Uses media to describe link semantics, template-based input and
message structures
● Provides its own URIs
A key benefit of this style is that it favors long-running services. When
designed correctly, a Hypermedia API can evolve over many years and
continue to support applications that have been developed during its infancy.
However, there is a lack of mature tooling and support for this type of API.
Consequently, some developers see hypermedia APIs as excessively complex.
16. Web API Architectural Styles
Event-DrivenStyleAPI interactions based on event-driven
architectures have gained in popularity recently. A popular example of
the event-driven style is the WebSocket protocol standard that has
been incorporated into the HTML 5 specification. WebSockets provide
a useful way of transmitting data with low overhead, in both directions
between a client and server. A Web API designed using the Event-
Driven style will typically exhibit both of the following key properties:
● The client and/or the server listen for new events
● Events are transmitted via asynchronous messages, as they
occur
While some Event-Based APIs utilize the HTTP protocol, there is a
growing body of network-based protocols like WebSocket that favour
low overhead, asynchronous communication. This style of API can be
very effective for applications that need to frequently update UI
widgets or for bi-directional, message-intensive applications such as
multiplayer video games.
17. SOAP vs. REST comparison
SOAP REST
Meaning Simple Object Access Protocol Representational State Transfer
Design Standardized protocol with pre-defined
rules to follow.
Architectural style with loose
guidelines and recommendations.
Approach Function-driven (data available as services,
e.g.: “getUser”)
Data-driven (data available as
resources, e.g. “user”).
Statefulness Stateless by default, but it’s possible to
make a SOAP API stateful.
Stateless (no server-side sessions).
18. SOAP vs. REST comparison
SOAP REST
Caching API calls cannot be cached. API calls can be cached.
Security WS-Security with SSL support. Built-in ACID
compliance.
Supports HTTPS and SSL.
Performance Requires more bandwidth and computing
power.
Requires fewer resources.
Message format Only XML. Plain text, HTML, XML, JSON,
YAML, and others.
Transfer
protocol(s)
HTTP, SMTP, UDP, and others. Only HTTP
19. SOAP vs. REST comparison
SOAP REST
Recommended
for
Enterprise apps, high-security apps,
distributed environment, financial services,
payment gateways, telecommunication
services.
Public APIs for web services, mobile
services, social networks.
Advantages High security, standardized, extensibility. Scalability, better performance,
browser-friendliness, flexibility.
Disadvantages Poorer performance, more complexity,
less flexibility.
Less security, not suitable for
distributed environments.
20. SOAP vs. REST comparison
SOAP Example RESTFUL Example
22. Architectural Layers
No matter what API design style you choose, there are
certain key qualities you will want your interface to have.
Designing API architecture able to encompass all these
qualities can be challenging. In this lesson, we outline a
layered architectural style that simplifies the process of
implementing a full-functioned Web API design.
For a Web API to function effectively, it must meet a range of
functional and non-functional requirements. These requirements,
which are essentially software qualities the interface should
display, will vary depending on the context but are likely to
include:
● Security – Protected against attack and misuse
● Usability – Easy for developers to effectively leverage
● Scalability – Able to handle rapid spikes in traffic
● Testability– Designed to help devs experiment with
functionality
● Reliability– Robust enough to minimize downtime
24. Architectural Layers
The SecurityLayer Establishing Web API security is
challenging and requires a special focus. Creating a
specialized layer to enforce security is a good way of
abstracting the intricacies of security away from the
design of the API itself.
Security enforcement works best at the edges and
access control components should be the first to act
upon all API requests. The security layer should
function as a gatekeeper for the API architecture.
25. Architectural Layers
The Caching Layer A server-based caching
implementation should be capable of delivering
content decorated with caching instructions. It
should also be able to act upon caching validation
metadata from client applications.
Caching can be implemented in many locations
within any API architecture. Positioning at least one
caching layer close to the edge will help reduce
resource utilization when cached versions of a
response can be delivered.
26. Architectural Layers
The Representation Layer A representation layer
provides a consumer-centric view of the data or service
that an API is exposing. Implementing a representation
layer makes it possible to isolate the interface from the
data and services that support it.
This will go a long way towards improving the usability
of the API by making it possible to focus on improving
the interface without impacting the implementation of
the underlying module that serves the data. This layer
also allows an architect to build new interfaces for existing
legacy services that may not be suitable for new
consumers. For example, a common challenge faced by
enterprise architects is how to adapt a SOAP-based
Web service for mobile client applications.
27. Architectural Layers
The Orchestration Layer While many API requests
may be served by a single backend component, it is
often the case that data will need to be aggregated
or composed from multiple backend sources. This is
where the orchestration layer comes in.
An orchestration layer can abstract this composition
work in a way that makes it easy to create new APIs
by selectively joining together existing data
elements. An orchestration layer may also call
external APIs to provide enriched responses to
client applications.
29. TheUSE
Paradigm
To work effectively, a Web API must display a range of specific
software qualities. In this lesson, we outline what we call the
“USE Paradigm” – a principle of API design, which states that
interface designers should prioritize three particularly important
software qualities: usability, scalability and evolvability.
The USE Paradigm states that, by focusing on designing a Web
API that exhibits these three qualities, you can create an
interface that offers a better experience both for the developers
who build client apps against your API and the end users who
consume these apps, while also extending the longevity of these
apps.
30. The USE Paradigm (USABILITY)
USABILITY The Design of Everyday Things, a book by
cognitive scientist and usability engineer Donald Norman,
describes the way people interact with things in the world as
an execution-evaluation loop. First, they execute an action,
then they evaluate whether the action achieved the effect they
were seeking. Then they execute a follow-up action, evaluate
that and so on.
So, as developers try to determine how they can use your API,
they take actions to achieve a result and then evaluate how
successful each action was. They are continuously making
usability judgments and assessing how usable your interface is.
By keeping this in mind, you will get a sense of how you can
improve the usability of your API.
31. The USE Paradigm (USABILITY)
Design for usability When you design your interface, you need to take into consideration: who your target
developersare, what they are interested in doing and what skill level they have. But how do you actually tell whether
you are addressing these factors effectively in order to create an interface that is truly usable?
This challenge is best approached in three stages:
● An early focus on users and tasks
● Empirical measurement
● Iterative design
From the very beginning of the API design process, it is crucial that you make every decision with a clear focus on
your users and the tasks they need to accomplish. If you begin with this in mind, you will find it easier to ensure that,
throughout the design process, you remain focused on making it easy for them to accomplish those tasks.
32. The USE Paradigm (USABILITY)
Along the way, you should empirically measure the actual usability of your API by testing how developers interact
with it. In the same way you might test a user interface, you can ask developers to perform a task and then measure
the number of mistakesthey make, how many API calls they make and how many steps they have to go through to
finally accomplish the task.
As you receive feedback from these empirical measurements, you should be prepared to enter a process of iterative
design. Based on your findings, you can address problem areas and then repeat the execution-evaluation cycle of
testing and redesigning as you gather additional feedback on each new iteration of your API.
To get a broader perspective on the usability of your interface, you can test it on a variety of different developer
communities – ranging from experienced programmers who have knowledge of sophisticated languages and
compiling tools, to eager college students building their first mobile apps.
34. The USE
Paradigm
(SCALABILITY)
SCALABILITYA well-designed API will be able to effectively
handle a growing workload over time. Scalability should be
addressed early in the API development process. If you wait
until later to address scalability, you may have to throw
hardware at the problem (e.g. by adding more memory or disk
power), which will inevitably be less effective than dealing with
it at the design stage.
Scale out, not up Scaling up by adding memory, processor power
etc. – making the same machine bigger – is easier but less
effective. Scaling out by adding more machines requires greater
upfront coordination but is more reliable. Virtualization and
cloudtechnologies should be factored into your design from the
beginning to enable the quick addition of more machines if
necessary.
35. The USE Paradigm
(SCALABILITY)
Take advantage of DevOps practices to support scaling
By integrating software development and operations,
● DevOps has taught us that virtualizing
infrastructure and making it more flexible
enables scalability.
● DevOps makes it cheaper and easier not only to
add more machines but also to deploy code – in
other words, scaling out not just your hardware
but your deployment as well.
With the process of deployment simplified, you can
deploy APIs multiple times, enabling the iterative
design process discussed above. Companies that are
the most successful at scaling out do so not only with
their hardware or their software design but also with
their human resources and processes.
36. The USE
Paradigm
(EVOLVABILITY
)
EVOLVABILITY As well as being able to grow and handle extra
load over time, your API should be able to evolve and adapt to
changing circumstances. an API must adhere to the following
rules:
● Existing elements cannot be removed
● The meaning/processing of existing elements cannot be
changed
● New elements must be optional
Removing or even changing existing elements of your API will
negatively impact – or even break – the functioning of
existing apps that leverage those elements. Similarly, any new
elements you add must be optional. Requiring developers to
use new elements will create a strong risk of breaking
existing apps.
37. The USE
Paradigm
(EVOLVABILITY
)
Choose extending over versioning whenever possible It is still
common to introduce a new version of an API every time
additional functionality is introduced. However, the most
successful API providers choose to extend their existing
APIs – incrementally adding optional new functionality
without removing or altering existing elements. This allows
them to evolve their interfaces without breaking anyone’s app.
By contrast, versioning APIs without breaking anything
requires a “forking” approach where multiple unrelated
versions must be supported. This creates a less-than-ideal
developer experience and is also more difficult and costly to
maintain. Therefore, versioning should be avoided whenever
possible and only used as a last resort (e.g. if there is a
security breach).
39. Pagination
Pagination is a ubiquitous method for handling large datasets and
responses in the browser-based Web but developers of API-based
apps also turn to pagination in order to minimize response times for
requests and generally improve the end-user experience. In this
lesson, we will explore some common methods for enabling
pagination in APIs.
There are two main design decisions involved in implementing
pagination for APIs:
1. How to partition the response data that the API generates.
2. How the client application will select and navigate to the data
page it needs. For page selection, including a query parameter
in the URI is the recommended method with the majority of use
cases.
40. Pagination
For partitioning response data, on the other hand, there are various
methods you might use, each of which has its own advantages and
disadvantages, depending on the use case. (However, whichever
method you choose, being consistent across the API will make for a
better overall experience, from the developer and end-user
perspectives alike.)
Partitioning methods include:
1. HTTP range header
2. Fixed data pages
3. Flexible data pages
4. Offset and count
5. Default values
41. Pagination (HTTP Range Header)
The HTTP protocol has a built-in feature for splitting up data, known as the range header. Using this
method, the client application requests a specific byte range from the server and the server returns that
data. While it is tempting to use an HTTP range header, the range header was not designed to operate on
the level that is necessary for API design.
The HTTPrange headeris based on byte range, makingit very useful for binarydata. However, it is not as
useful for text-based data. Therefore, in practice, paginating data in this way is likely to be significantly less
meaningful to any developer building a Web or mobile application against the API.
42. Pagination (Fixed Data Pages)
Of all the methods an API designer can use to facilitate pagination in client applications, using fixed
data pages is probably the easiest method to grasp conceptually. This simply means splitting results
into pages of a predetermined size and partitioning scheme then having the client application
request a specific page.
With fixed data pages, the developer writes an app that requests a specific page of data by page
number and the server partitions the data and responds. This method is easy to navigate – you just
pick a page. But for this gain in usability,
we lose flexibility: the page size is the same
for everyone and there is little ability for
developers to customize their results.
Determining the right size of data to select
per page can be difficult because the answer
depends on a number of factors, including
The platform that the app is deployed on,
43. Pagination (Flexible Data Pages)
Another option, which provides client application developers with additional flexibility, is to give
them control of the data page sizes, rather than having these sizes dictated by the server. In this
scenario, the client application not only requests a specific page but it also indicates what the
page size should be.
While using flexible data pages preserves ease of navigation and increases flexibility by splitting
up the data according to the client application’s needs, it makes the implementation more
difficult for the developer by
increasing the interface complexity
(with more parameters) as well as
the partitioning complexity.
44. Pagination (Offset & Count)
To provide the greatest level of flexibility for client applications, you can eliminate the concept of
pages altogether and use an offset scheme. Rather than splitting data up into discrete pages, you
consider data as a collection of items and allow the client application to request a specific starting
index as well as the number of items the server should return.
This is obviously the most complex approach
from the developer perspective because
devs can no longer think abstractly in terms
of pages. Not only does the developer have
to think about which specific item should be
requested but the client application must
also pay attention to a “cursor” position and
keep track of where the next offset should be.
45. Pagination (Default Values)
While each of these methods has advantages and
disadvantages, another approach manages to retain the
flexibility of flexible data pages or offsets while retaining
the usability of fixed data pages. This is achieved by
starting with one of the flexible methods and putting
default values in place when there is an absence of page
instructions and specific values are not indicated.
By doing this, you can take something like an offset
mechanism and prescribe default values that will satisfy
90 percent of developers (who will want pagination in a
standard way) but still provide the 10 percent who have
special requirements with additional controls that will
allow them to be very precise.
46. Pagination
Navigation Considerations Just like human users, applications using your API will need a
way to navigate through these pages. To make navigation easier, you need to provide
metadata with each page response. For instance, this may include the number of pages or
items available, the last time the dataset was updated or the current location within the
dataset.
In addition to this basic information, providing hyperlinks to other pages within the
dataset will make it easier for applications to navigate through your API. In particular, it
will mean they will not have to construct their own URLs or calculate their own offsets.
When making these links, remember to make the interface simple for devs by using
common naming standards.
48. API Security
In this lesson, we examine
typical areas of vulnerability
and share best practices for
securing APIs
APIs give client-side developers
(and potential hackers) much more
finely-grained access into the
backend than a typical Web site or
application does. Because APIs shift
the granularity boundary from
relatively-secure internal tiers out
to a client application residing on a
user’s device, the potential attack
surface is significantly increased.
49. API Security
There are three broad security
categories organizations that
publish APIs need to be aware
of:
1. API parameters
2. Identity
3. Cryptography and Public
Key Infrastructure (PKI)
API Parameters In conventional Web scenarios, parameters (the pieces of data sent to a
remote server) are limited and indirect.
APIs, in contrast, offer much more explicit parameterization and open up more of the
HTTP protocol. This creates a greater potential attack surface, as parameter attacks
exploit the data sent into an API – including URL, query parameters, HTTP headers
and/or post content.
Typical parameter attacks include:
● Script insertions, which exploit systems that interpret submitted parameter
content as a script (e.g. when a snippet of JavaScript is submitted into a posting
on a Web forum)
● SQL injections, where parameters that are designed to load a certain input into a
database query are manipulated to change the intent of an underlying SQL
template
● Bounds or buffer overflow attacks, which provide data beyond the expected type
or range and can lead to system crashes or offer access to memory space
Best practices to avoid parameter attacks include:
● Strictly constraining all the consumer-supplied inputs by default and rigorously
validating all data going in and out of an API
● Rather than using blacklists, creating a whitelist of expected inputs and ensuring
these cannot be exploited
● Taking care to limit error messages and leakage to avoid revealing excessive
information about the underlying system
50. API Security
There are three broad security
categories organizations that
publish APIs need to be aware
of:
1. API parameters
2. Identity
3. Cryptography and Public
Key Infrastructure (PKI)
Identity Identity-based authentication and authorization (Authentication is the
process of verifying who you are. When you log on to a PC with a username and password
you are authenticating , Authorization is the process of verifying that you have access to
something. Gaining access to a resource (e.g. directory on a hard disk) because the
permissions configured on it allow you access is authorization.)
is relatively simple on the Web as it is mostly centered on username/password
combinations, with interaction limited to a single person’s browser session. With
APIs, interactions can include machine identities and multiple identity layers
(the user’s logins for various apps and sites, details of various devices etc.)
Consequently, new identity standards have emerged that aim to address some
of the complex federation and delegation scenarios common in API-based apps.
Of these, OAuth has emerged as the key standard able to solve a wide range of
challenges. However, implementing OAuth can be complex for app developers
and even for enterprise API publishers.
To further complicate matters, many APIs require client apps to use API keys in
order to access their functionality. API keys are unique identifiers that tag onto
the end of a query to identify the particular application that is making the call.
They do not, however, identify the specific app user; nor do they identify a unique
instance of the application.
51. API Security
There are three broad security
categories organizations that
publish APIs need to be aware
of:
1. API parameters
2. Identity
3. Cryptography and Public
Key Infrastructure (PKI)
All this complexity makes APIs particularly vulnerable to identity-based attacks.
These attacks exploit flaws in authentication, authorization and session tracking. Many
of these flaws occur when poor Web development practices are carried over into the
API realm.
Typically, risks are created by bad practices such as:
● Using API keys instead of user credentials. API keys should only be used
as a non-authoritative tracking mechanism. Not only do they not identify a
user but – because they are often visible in server logs and even included
in URLs – they can be extracted by a hacker and cannot be used securely
on the client like a password would be.
● Poor session management. Developers coming from the Web world can
be reluctant to include formation credentials on every transaction.
Browsers maintain sessions using cookies or other opaque session IDs
but APIs rarely take a consistent approach to session management, which
leaves developers to create their own methods.
Best practices to mitigate identity risks include:
● Using HTTPS everywhere – it is not that expensive anymore
● Making sure API keys, passwords and session IDs never show up in a URL
● Using OAuth for people or app instances and using API keys only for the
app class
52. API Security
There are three broad security
categories organizations that
publish APIs need to be aware
of:
1. API parameters
2. Identity
3. Cryptography and Public
Key Infrastructure (PKI)
Cryptography & PKI Cryptography is reasonably mature on the Web
but it has proved to have surprisingly limited use patterns. With APIs,
there is a growing requirement for more sophisticated cryptography.
Unfortunately, because so many developers were never trained on
how to work with encrypted systems, important best practices are
being glossed over.
Bad habits include:
● Risky key distribution practices Sending codes and tokens (API
keys, OAuth and JSON Web Tokens etc.) over email
● Neglected lifecycle management Ignoring or overlooking the
formalized method for managing keys
Best practices to mitigate these bad habits include:
● Using SSL everywhere
● Not trying to reinvent PKI – it was developed by experts with
real-world experience
● Using hardware security modules (HSMs) to protect critical keys
53. API Security
There are three broad security
categories organizations that
publish APIs need to be aware
of:
1. API parameters
2. Identity
3. Cryptography and Public
Key Infrastructure (PKI)
Cryptography & PKI Cryptography is reasonably mature on the Web
but it has proved to have surprisingly limited use patterns. With APIs,
there is a growing requirement for more sophisticated cryptography.
Unfortunately, because so many developers were never trained on
how to work with encrypted systems, important best practices are
being glossed over.
Bad habits include:
● Risky key distribution practices Sending codes and tokens (API
keys, OAuth and JSON Web Tokens etc.) over email
● Neglected lifecycle management Ignoring or overlooking the
formalized method for managing keys
Best practices to mitigate these bad habits include:
● Using SSL everywhere
● Not trying to reinvent PKI – it was developed by experts with
real-world experience
● Using hardware security modules (HSMs) to protect critical keys
54.
55. API Security
Top 10 Application Security Risks
A1 – Injection
Injection attacks happen when untrusted data is sent to a
code interpreter through a form input or some other data
submission to a web application. For example, an attacker
could enter SQL database code into a form that expects a
plaintext username. If that form input is not properly
secured, this would result in that SQL code being
executed. This is known as an SQL injection attack.
Injection attacks can be prevented by validating and/or
sanitizing user-submitted data. (Validation means
rejecting suspicious-looking data, while sanitization refers
to cleaning up the suspicious-looking parts of the data.) In
addition, a database admin can set controls to minimize
the amount of information an injection attack can expose.
56. API Security
Top 10 Application Security RisksA2 – Broken Authentication
Vulnerabilities in authentication (login) systems can give
attackers access to user accounts and even the ability to
compromise an entire system using an admin account.
For example, an cattacker an take a list containing
thousands of known username/password combinations
obtained during a data breach and use a script to try all
those combinations on a login system to see if there are
any that work.
Some strategies to mitigate authentication vulnerabilities
are requiring 2-factor authentication (2FA) as well as
limiting or delaying repeated login attempts using rate
limiting.
57. API Security
Top 10 Application Security Risks
A3 – Sensitive Data Exposure
If web applications don’t protect sensitive data such as
financial information and passwords, attackers can gain
access to that data and sellor utilize it for nefarious
purposes. One popular method for stealing sensitive
information is using a man-in-the-middle attack.
Data exposure risk can be minimized by encrypting all
sensitive data as well as disabling the caching* of any
sensitive information. Additionally, web application
developers should take care to ensure that they are not
unnecessarily storing any sensitive data.
58. API Security
Top 10 Application Security Risks
A4 – XML External Entities (XXE)
This is an attack against a web application that parses
XML input. This input can reference an external
entity, attempting to exploit a vulnerability in the
parser. An ‘external entity’ in this context refers to a
storage unit, such as a hard drive. An XML parser can
be duped into sending data to an unauthorized
external entity, which can pass sensitive data directly
to an attacker.
The best ways to prevent XEE attacks are to have web
applications accept a less complex type of data, such
as JSON, or at the very least to patch XML parsers and
disable the use of external entities in an XML
application.
59. API Security
Top 10 Application Security Risks
A5 – Broken Access Control
Access control refers a system that controls access to
information or functionality. Broken access controls
allow attackers to bypass authorization and perform
tasks as though they were privileged users such as
administrators. For example a web application could
allow a user to change which account they are logged
in as simply by changing part of a url, without any
other verification.
Access controls can be secured by ensuring that a web
application uses authorization tokens* and sets tight
controls on them.
60. API Security
Top 10 Application Security Risks
A6 – SecurityMisconfiguration
Security misconfiguration is the most common
vulnerability on the list, and is often the result of using
default configurations or displaying excessively
verbose errors. For instance, an application could
show a user overly-descriptive errors which may
reveal vulnerabilities in the application.
This can be mitigated by removing any unused
features in the code and ensuring that error messages
are more general.
61. API Security
Top 10 Application Security Risks
A7– Cross-Site Scripting (XSS)
Cross-site scripting vulnerabilities occur when web
applications allow users to add custom code into a url
path or onto a website that will be seen by other users.
This vulnerability can be exploited to run malicious
JavaScript code on a victim’s browser.
Mitigation strategies for cross-site scriptinginclude
escapinguntrustedHTTPrequests as well as validating
and/or sanitizing user-generated content. Using
modern web development frameworks like ReactJS
and Ruby on Rails also provides some built-in cross-
site scripting protection.
62. API Security
Top 10 Application Security Risks
A8– InsecureDeserialization
This threat targets the many web applications which frequently
serialize and deserialize data. Serializationmeans taking objects
from the application code and converting them into a format that
can be used for another purpose, such as storing the data to disk
or streaming it. Deserializationis just the opposite: converting
serialized data back into objects the application can use.
An insecure deserialization exploit is the result of deserializing
data from untrusted sources, and can result in serious
consequences like DDoS attacks and remote code execution
attacks. While steps can be taken to try and catch attackers, such
as monitoring deserialization and implementing type checks,
theonlysurewayto protectagainstinsecuredeserialization
attacks is to prohibit the deserialization of data from untrusted
sources.
63. API Security
Top 10 Application Security Risks
A9– UsingComponents With KnownVulnerabilities
Many modern web developers use components such
as libraries and frameworks in their web
applications. These components are pieces of
software that help developers avoid redundant work
and provide needed functionality. Some attackers
look for vulnerabilities in these components which
they can then use to orchestrate attacks.
To minimize the risk of running components with
known vulnerabilities, developers should remove
unused components from their projects, as well as
ensuring that they are receiving components from a
trusted source and ensuring they are up to date.
64. API Security
Top 10 Application Security Risks
A10– InsufficientLoggingAnd Monitoring
Many web applications are not taking enough steps
to detect data breaches. The average discovery time
for a breach is around 200 days after it has
happened.
This gives attackers a lot of time to cause damage
before there is any response.
OWASP recommends that web developers should
implement logging and monitoring as well as
incident response plans to ensure that they are made
aware of attacks on their applications.
66. Versioning
WebAPI
Change is inevitable and growth is a good thing. When your API has
reached the point of expanding beyond it’s original intent and capacity,
it’s time to consider the next version.
There are a number of ways changes can be introduced to the API that are beneficial to
the user and do not constitute a breaking change. These include:
● A new resource or API endpoint
● A new optional parameter
● A change to a non-public API endpoint
● A new optional key in the JSON POST body
● A new key returned in the JSON response body
Conversely, a breaking change included anything that could break a user’s integration
such as:
● A new required parameter
● A new required key in POST bodies
● Removal of an existing endpoint
● Removal of an existing endpoint request method
● A materially different internal behavior of an API call—such as a change to the
default behavior.
67. Versioning
WebAPI
1. Create a new URL with version.
2. Handle new version using query string.
3. Handle new version using http header.
4. Handle new version using accept header.
5. Handle new version using media type.
You can version your Web API in one of the following
ways:
68. Versioning
WebAPI
This is one of the ways where you use API/v1, API/v2 to handle multiple version. In
this approach you need to create Version 2 of your model and factory maker. you
can create a new version of the model and inherit from the original version to
extend the new fields available.
public class InterestV2Model : InterestModel
Step 2 you configure the routing table to achieve it. E.g. All api/v2 will go to the new
v2 controller.
config.Routes.MapHttpRoute(
name: "Interests2",
routeTemplate: "api/v2/users/{userid}/interests",
defaults: new { controller = "interestsv2", id =
RouteParameter.Optional }
);
The con of this approach is you cannot tell what is the current latest version.
1- Create a new URL with version.
69. Versioning
WebAPI
This is to use querystring to indicate what version of API to trigger. Since it is
querystring you can handle default case (no querystring case) as the latest version.
You can trigger version 1.2 of the api using the below url
api/users/1/interests?v=1.2
Alternatively, you can also trigger the latest version of the api using the below url.
api/users/1/interests
As you can see the problemfor this approach is that if you roll out version 1 that
does not have v=1.2 in the query string, it will route to the latest API version,
which might break the older API that is running.
2- Handle new version using query string
70. Versioning
WebAPI This is similar to query string but you indicate version in header
instead of querystring. This approach is better because the API url
remain the same regardless version.
X-YourName-Version : 1
Not all developers familiar with http header implementation, this might
add challenges to your developers.
3- Handle new version using http header
71. Versioning
WebAPI This is similar to querystring but you indicate version in header
instead of query string.
Accept : application/json; version=2
This will have the same pro and con as http header.
4- Handle new version using accept header
72. Versioning
WebAPI
This approach is about creating a custom media type to handle
versioning.
And you use regular expression to extract the version from media
type. This approach is similar with the previous accept or other header
approach.
application/vnd.yourname.user.v1+json
application/vnd.yourname.user.v2+json
application/vnd.yourname.user.interest.v1+json
application/vnd.yourname.user.interest.v2+json
5- Handle new version using media type
73. Versioning
WebAPI
Versioning Recommendation
● Specify the version with a 'v' prefix, don't use the dot notation.
– /v1/dogs
– /v2/customers
● How many version should you maintain?
– At least one version back
● Should version and format be in URL or headers?
– If it logic, put in URL
– If it doesn't change logic (like Oauth), put it in the header
75. Best
Practices in
RESTful API
Design
1. Learn the basics of HTTP applied to REST.
2. Use nouns but no verbs.
3. GET method and query parameters should not alter the state.
4. Use plural nouns.
5. Use sub-resources for relations.
6. Use HTTP headers for serialization formats.
7. Use HATEOAS.
8. Provide filtering, sorting, field selection and paging for collections.
9. Version your API.
10. Handle Errors with HTTP status codes.
11. Allow overriding HTTP method.
12. Don't return plain text.
13. Return error details in the response body.
14. Handle trailing slashes gracefully.
15. Learn the difference between 401 Unauthorized and 403 Forbidden.
What is OWASP?
The Open Web Application Security Project, or OWASP, is an international non-profit organization dedicated to web application security
For example, an attacker could send an email to a victim that appears to be from a trusted bank, with a link to that bank’s website. This link could have some malicious JavaScript code tagged onto the end of the url. If the bank’s site is not properly protected against cross-site scripting, then that malicious code will be run in the victim’s web browser when they click on the link.
Serialization is sort of like packing furniture away into boxes before a move, and deserialization is like unpacking the boxes and assembling the furniture after the move. An insecure deserialization attack is like having the movers tamper with the contents of the boxes before they are unpacked.
common example include front-end frameworks like React and smaller libraries that used to add share icons or a/b testing
common example include front-end frameworks like React and smaller libraries that used to add share icons or a/b testing