Securing RESTful API
- 2. CHOOSE THE RIGHT API
SECURITY PROTOCOL
Security isn’t an afterthought. It has to be an integral part of
any development project and also for REST APIs.
There are multiple ways to secure a RESTful API e.g.
basic auth, OAuth etc. but one thing is sure that RESTful APIs
should be stateless – so request authentication/authorization
should not depend on cookies or sessions. Instead, each API
request should come with some sort authentication credentials
which must be validated on server for each and every request.
2
- 3. AUTHENTICATION VS.
AUTHORIZATION
Authentication is the verification of the credentials of the
connection attempt. This process consists of sending the
credentials from the remote access client to the remote access
server in an either plaintext or encrypted form by using an
authentication protocol.
Authorization is the verification that the connection attempt is
allowed. Authorization occurs after successful authentication.
In other words: Authentication is stating that you are who are
you are and Authorization is asking if you have access to a certain
resource. 3
- 4. WHY USE API KEYS VS.
USERNAME/PASSWORD
AUTHENTICATION
Entropy
API keys/secrets are usually a long series of random characters that are
difficult to guess. Username/password are typically much smaller in length,
use common words, are generally insecure, and can be subject to brute
force and dictionary attacks.
Password Reset Problems
Passwords are reset often. If you use the password as part of your API
authentication scheme, API access would fail every time the password is
changed.
Speed
Best practices say to encrypt your passwords in the database to limit a
potential data breach. This increases overhead for each request when
authenticating a user. Unique API keys authentication skips the hashing
step and therefore speeds up your calls. If you want to know more about
storing passwords, read more here.
4
- 5. STORING YOUR API
SECURITY KEY
It’s recommended to store the API key/secret in a file only
readable by the owner. When the key/secret pair is
downloaded, it is saved to the local file system. Then
permissions are changed so that only the user can read the
file.
5
- 6. 1) BASIC API
AUTHENTICATION W/ TLS
Basic API authentication is the easiest, because the majority of
the time, it can be implemented without additional libraries.
Everything needed to implement basic authentication is usually
included in your standard framework or language library.
The problem with basic authentication is that it is, well “basic”, and
it offers the lowest security options of the common protocols.
There are no advanced options for using this protocol, so you are
just sending a username and password that is Base64 encoded.
Basic authentication should never be used without TLS (formerly
known as SSL) encryption because the username and password
combination can be easily decoded otherwise.
6
- 7. 2) JWT – JSON WEB
TOKENS
JSON Web Token (JWT) is an open standard (RFC 7519) that
defines a compact and self-contained way for securely
transmitting information between parties as a JSON object. This
information can be verified and trusted because it is digitally
signed. JWTs can be signed using a secret (with
the HMAC algorithm) or a public/private key pair using RSA.
Compact: Because of their smaller size, JWTs can be sent
through a URL, POST parameter, or inside an HTTP header.
Additionally, the smaller size means transmission is fast.
Self-contained: The payload contains all the required information
about the user, avoiding the need to query the database more
than once.
7
- 8. JWT STRUCTURE
Header
The header typically consists of two parts: the type of the token,
which is JWT, and the hashing algorithm being used, such as
HMAC SHA256 or RSA.
Payload
The second part of the token is the payload, which contains the
claims. Claims are statements about an entity (typically, the user)
and additional metadata. There are three types of
claims: reserved, public, and private claims.
Signature
To create the signature part you have to take the encoded header,
the encoded payload, a secret, the algorithm specified in the
header, and sign that.
8
- 11. HOW DO JSON WEB
TOKENS WORK?
In authentication, when users successfully logs in using their
credentials, a JSON Web Token will be returned and must be
saved locally (typically in local storage, but cookies can be also
used), instead of the traditional approach of creating a session
in the server and returning a cookie.
Whenever the user wants to access a protected route or
resource, the user agent should send the JWT, typically in
the Authorization header using the Bearer schema. The
content of the header should look like the following:
Authorization: Bearer <Token>
11
- 12. JWT BENEFITS
This is a stateless authentication mechanism as the user state
is never saved in server memory. The server's protected
routes will check for a valid JWT in the Authorization header,
and if it's present, the user will be allowed to access protected
resources. As JWTs are self-contained, all the necessary
information is there, reducing the need to query the database
multiple times.
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.
12
- 15. 3) OAUTH1.0A
OAuth 1.0a is the most secure of the common protocols. OAuth1
is a widely-used, tested, secure, signature-based protocol. The
protocol uses a cryptographic signature, (usually HMAC-SHA1)
value that combines the token secret, nonce, and other request
based information.
The great advantage of OAuth 1 is you never directly pass the
token secret across the wire, which completely eliminates the
possibility of anyone seeing a password in transit. This is the
only that can be safely used without SSL (although you
should still use SSL if the data transferred is sensitive).
However, this level of security comes with a price: generating and
validating signatures can be a complex process. You have to use
specific hashing algorithms with a strict set of steps.
15
- 16. 4) OAUTH2
Introduction
OAuth 2 is an authorization framework that enables
applications to obtain limited access to user accounts on an
HTTP service, such as Facebook, GitHub, and DigitalOcean. It
works by delegating user authentication to the service that
hosts the user account, and authorizing third-party applications
to access the user account. OAuth 2 provides authorization
flows for web and desktop applications, and mobile devices.
16
- 17. WHAT IS OAUTH2?
OAuth2 sounds like an evolution of OAuth1, but in reality it is a
completely different take on authentication that attempts to
reduce complexity.
OAuth2’s current specification removes signatures, so you no
longer need to use cryptographic algorithms to create,
generate, and validate signatures.
All the encryption is now handled by TLS, which is required.
There are not as many OAuth2 libraries as there are OAuth1a
libraries, so leveraging this protocol for REST API security may
be more challenging.
17
- 18. OAUTH ROLES
The Third-Party Application: "Client“
The client is the application that is attempting to get access to the user's
account. It needs to get permission from the user before it can do so.
The API: "Resource Server“
The resource server is the API server used to access the user's information.
The Authorization Server
This is the server that presents the interface where the user approves or
denies the request. In smaller implementations, this may be the same server
as the API server, but larger scale deployments will often build this as a
separate component.
The User: "Resource Owner“
The resource owner is the person who is giving access to some portion of their
account. 18
- 20. CREATING AN APP
(WEB/MOBILE)
Before you can begin the OAuth process, you must first register a
new app with the service. When registering a new app, you
usually register basic information such as application name,
website, a logo, etc. In addition, you must register a redirect
URI to be used for redirecting users to for web server, browser-
based, or mobile apps.
Redirect URIs
The service will only redirect users to a registered URI, which helps
prevent some attacks. Any HTTP redirect URIs must be protected
with TLS security, so the service will only redirect to URIs
beginning with "https". This prevents tokens from being intercepted
during the authorization process.
Native apps may register a redirect URI with a custom URL
scheme for the application, which may look like demoapp://redirect.
20
- 21. After registering your app, you will receive a client ID and a client secret.
The client ID is considered public information, and is used to build login
URLs, or included in Javascript source code on a page.
The client secret must be kept confidential. If a deployed app cannot keep
the secret confidential, such as single-page Javascript apps or native
apps, then the secret is not used, and ideally the service shouldn't issue a
secret to these types of apps in the first place.
21
CLIENT ID AND SECRET
- 22. APP TYPES (SEE ARTICLE
)
Web Server Apps
Web server apps are the most common type of application you
encounter when dealing with OAuth servers. Web apps are written
in a server-side language and run on a server where the source
code of the application is not available to the public. This means
the application is able to use its client secret when communicating
with the authorization server, which can help avoid some attack
vectors.
Single-Page Apps
Single-page apps (or browser-based apps) run entirely in the
browser after loading the source code from a web page. Since the
entire source code is available to the browser, they cannot
maintain the confidentiality of their client secret, so the secret is
not used in this case. The flow is exactly the same as the
authorization code flow above, but at the last step, the
authorization code is exchanged for an access token without using
the client secret.
22
- 23. WEB SERVER APPS:
Authorization:
The first step of OAuth 2 is to get authorization from the user. For
browser-based or mobile apps, this is usually accomplished by
displaying an interface provided by the service to the user.
OAuth 2 provides several "grant types" for different use cases. The
grant types defined are:
Authorization Code for apps running on a web server, browser-based
and mobile apps
Password for logging in with a username and password
Client credentials for application access
Implicit was previously recommended for clients without a secret, but has been
superseded by using the Authorization Code grant with no secret.
23
- 24. WHICH OAUTH 2.0 GRANT
SHOULD WE USE?
A grant is a method of acquiring an access token. Deciding
which grants to implement depends on the type of client the
end user will be using, and the experience you want for your
users.
Access Token Owner?
An access token represents a permission granted to a client to
access some protected resources:
If you are authorizing a machine to access resources and you don’t require
the permission of a user to access said resources you should implement the
client credentials grant.
If you require the permission of a user to access resources you need to
determine the client type.
24
- 25. CLIENT TYPE?
Depending on whether or not the client is capable of keeping a
secret will depend on which grant the client should use:
If the client is a web application that has a server side component
then you should implement the authorization code grant.
If the client is a web application that has runs entirely on the front
end (e.g. a single page web application) you should implement the
password grant for a first party clients and the implicit grant for a
third party clients.
If the client is a native application such as a mobile app you should
implement the password grant.
25
- 26. PROCESS:
Create a "Log In" link sending the user to:
https://authorization-server.com/auth?
response_type=code&client_id=CLIENT_ID&redirect_uri=REDIRECT_
URI&scope=photos&state=1234zyx
code - Indicates that your server expects to receive an authorization code
client_id - The client ID you received when you first created the application
redirect_uri - Indicates the URI to return the user to after authorization is
complete
scope - One or more scope values indicating which parts of the user's
account you wish to access
state - A random string generated by your application, which you'll verify
later
26
- 28. If the user clicks "Allow," the service redirects the user back to
your site with an auth code:
https://example-app.com/cb?
code=AUTH_CODE_HERE&state=1234zyx
code - The server returns the authorization code in the query string
state - The server returns the same state value that you passed
You should first compare this state value to ensure it matches
the one you started with. You can typically store the state
value in a cookie or session, and compare it when the user
comes back. This ensures your redirection endpoint isn't able
to be tricked into attempting to exchange arbitrary
authorization codes.
28
- 29. Token exchange:
Your server exchanges the auth code for an access token:
POST https://api.authorization-
server.com/tokengrant_type=authorization_code&code=AUTH_CODE
_HERE&redirect_uri=REDIRECT_URI&client_id=CLIENT_ID&client_s
ecret=CLIENT_SECRET
grant_type=authorization_code - The grant type for this flow is
authorization_code
code=AUTH_CODE_HERE - This is the code you received in the query
string
redirect_uri=REDIRECT_URI - Must be identical to the redirect URI
provided in the original link
client_id=CLIENT_ID - The client ID you received when you first created
the application
client_secret=CLIENT_SECRET - Since this request is made from
server-side code, the secret is included
29
- 30. The server replies with an access token and expiration time:
{
"access_token":"RsT5OjbzRn430zqMLgV3Ia",
"expires_in":3600
}
Or if there is an error:
{
"error":"invalid_request"
}
30
- 32. JWT “VS” OUTH2
JWT is an authentication protocol
This means it is a strict set of instructions for the issuing and validating of signed
access tokens. The tokens contain claims that are used by an app to limit access
to a user.
OAuth2 is an authentication framework
OAuth2 on the other hand is a framework, think very detailed guideline, for letting
users and applications authorize specific permissions to other applications in both
private and public settings.
What’s with the ‘VS’ in the title?
The ‘vs’ in the title is misleading, the two are not incompatible with each other. It
is possible to have an OAuth2 implementation that issues JSON Web Tokens as
an authentication mechanism.
http://www.seedbox.com/en/blog/2015/06/05/oauth-2-vs-json-web-tokens-comment-securiser-un-api/
32
- 33. WRAP UP
Never use Basic Authentication, if possible
Favor HMAC-SHA256 digest algorithms over bearer token
Use Oauth 1.0a or Oath 2 (preferably MAC)
“Only use a custom scheme if you really, really know what you’re doing”
“Oauth is an authorization protocol, NOT an authentication or SSP protocol”. But there
are those that still try to use Oauth for authentication – for example, OpenID Connect.
JSON Web Token (JWT) is “a very new spec, but clean and simple.
33