SlideShare uma empresa Scribd logo
1 de 33
SECURING RESTFUL API
Muhammad Zbeedat
Software and Data Quality
IBM Research – Haifa
2017
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
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
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
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
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
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
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
TOKEN STRUCTURE
9
Tech CBT - https://www.youtube.com/watch?v=oXxbB5kv9OA
TOKEN EXAMPLE:
10
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
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
PROCESS:
13
Tech CBT - https://www.youtube.com/watch?v=oXxbB5kv9OA
DEMONSTRATION:
Create JWT
http://jwtbuilder.jamiekurtz.com/
Verify JWT
https://jwt.io/
Base64 encode/decode
https://www.base64encode.org/
https://www.base64decode.org/
14
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
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
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
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
19
https://www.digitalocean.com/community/tutorials/an-introduction-to-oauth-2
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
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
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
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
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
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
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
The user sees the authorization prompt:
27
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
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
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
OAUTH DANCE
31
RestCase - http://blog.restcase.com/restful-api-authentication-basics/
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
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

Mais conteúdo relacionado

Mais procurados

Stateless authentication with OAuth 2 and JWT - JavaZone 2015
Stateless authentication with OAuth 2 and JWT - JavaZone 2015Stateless authentication with OAuth 2 and JWT - JavaZone 2015
Stateless authentication with OAuth 2 and JWT - JavaZone 2015
Alvaro Sanchez-Mariscal
 

Mais procurados (20)

Stateless authentication for microservices - GR8Conf 2015
Stateless authentication for microservices - GR8Conf 2015Stateless authentication for microservices - GR8Conf 2015
Stateless authentication for microservices - GR8Conf 2015
 
Stateless authentication with OAuth 2 and JWT - JavaZone 2015
Stateless authentication with OAuth 2 and JWT - JavaZone 2015Stateless authentication with OAuth 2 and JWT - JavaZone 2015
Stateless authentication with OAuth 2 and JWT - JavaZone 2015
 
OAuth 2.0 and Mobile Devices: Is that a token in your phone in your pocket or...
OAuth 2.0 and Mobile Devices: Is that a token in your phone in your pocket or...OAuth 2.0 and Mobile Devices: Is that a token in your phone in your pocket or...
OAuth 2.0 and Mobile Devices: Is that a token in your phone in your pocket or...
 
The Client is not always right! How to secure OAuth authentication from your...
The Client is not always right!  How to secure OAuth authentication from your...The Client is not always right!  How to secure OAuth authentication from your...
The Client is not always right! How to secure OAuth authentication from your...
 
CIS14: Consolidating Authorization for API and Web SSO using OpenID Connect
CIS14: Consolidating Authorization for API and Web SSO using OpenID ConnectCIS14: Consolidating Authorization for API and Web SSO using OpenID Connect
CIS14: Consolidating Authorization for API and Web SSO using OpenID Connect
 
Rest API Security - A quick understanding of Rest API Security
Rest API Security - A quick understanding of Rest API SecurityRest API Security - A quick understanding of Rest API Security
Rest API Security - A quick understanding of Rest API Security
 
CIS 2012 - Going Mobile with PingFederate and OAuth 2
CIS 2012 - Going Mobile with PingFederate and OAuth 2CIS 2012 - Going Mobile with PingFederate and OAuth 2
CIS 2012 - Going Mobile with PingFederate and OAuth 2
 
Full stack security
Full stack securityFull stack security
Full stack security
 
Authentication and Authorization Architecture in the MEAN Stack
Authentication and Authorization Architecture in the MEAN StackAuthentication and Authorization Architecture in the MEAN Stack
Authentication and Authorization Architecture in the MEAN Stack
 
REST Service Authetication with TLS & JWTs
REST Service Authetication with TLS & JWTsREST Service Authetication with TLS & JWTs
REST Service Authetication with TLS & JWTs
 
Stateless Auth using OAuth2 & JWT
Stateless Auth using OAuth2 & JWTStateless Auth using OAuth2 & JWT
Stateless Auth using OAuth2 & JWT
 
LASCON 2017: SAML v. OpenID v. Oauth
LASCON 2017: SAML v. OpenID v. OauthLASCON 2017: SAML v. OpenID v. Oauth
LASCON 2017: SAML v. OpenID v. Oauth
 
Securing Single-Page Applications with OAuth 2.0
Securing Single-Page Applications with OAuth 2.0Securing Single-Page Applications with OAuth 2.0
Securing Single-Page Applications with OAuth 2.0
 
Single Sign On with OAuth and OpenID
Single Sign On with OAuth and OpenIDSingle Sign On with OAuth and OpenID
Single Sign On with OAuth and OpenID
 
An introduction to OAuth 2
An introduction to OAuth 2An introduction to OAuth 2
An introduction to OAuth 2
 
Mit 2014 introduction to open id connect and o-auth 2
Mit 2014   introduction to open id connect and o-auth 2Mit 2014   introduction to open id connect and o-auth 2
Mit 2014 introduction to open id connect and o-auth 2
 
Enabling Cloud Native Security with OAuth2 and Multi-Tenant UAA
Enabling Cloud Native Security with OAuth2 and Multi-Tenant UAA Enabling Cloud Native Security with OAuth2 and Multi-Tenant UAA
Enabling Cloud Native Security with OAuth2 and Multi-Tenant UAA
 
Protecting Your APIs Against Attack & Hijack
Protecting Your APIs Against Attack & Hijack Protecting Your APIs Against Attack & Hijack
Protecting Your APIs Against Attack & Hijack
 
An Authentication and Authorization Architecture for a Microservices World
An Authentication and Authorization Architecture for a Microservices WorldAn Authentication and Authorization Architecture for a Microservices World
An Authentication and Authorization Architecture for a Microservices World
 
OAuth2 primer
OAuth2 primerOAuth2 primer
OAuth2 primer
 

Semelhante a Securing RESTful API

OAuth - Don’t Throw the Baby Out with the Bathwater
OAuth - Don’t Throw the Baby Out with the Bathwater OAuth - Don’t Throw the Baby Out with the Bathwater
OAuth - Don’t Throw the Baby Out with the Bathwater
Apigee | Google Cloud
 

Semelhante a Securing RESTful API (20)

Restful api
Restful apiRestful api
Restful api
 
Best Practices for API Security
Best Practices for API SecurityBest Practices for API Security
Best Practices for API Security
 
Best Practices for API Security
Best Practices for API SecurityBest Practices for API Security
Best Practices for API Security
 
UserCentric Identity based Service Invocation
UserCentric Identity based Service InvocationUserCentric Identity based Service Invocation
UserCentric Identity based Service Invocation
 
attacks-oauth-secure-oauth-implementation-33644.pdf
attacks-oauth-secure-oauth-implementation-33644.pdfattacks-oauth-secure-oauth-implementation-33644.pdf
attacks-oauth-secure-oauth-implementation-33644.pdf
 
Designing Secure APIs
Designing Secure APIsDesigning Secure APIs
Designing Secure APIs
 
Webapp security (with notes)
Webapp security (with notes)Webapp security (with notes)
Webapp security (with notes)
 
Oauth Nightmares Abstract OAuth Nightmares
Oauth Nightmares Abstract OAuth Nightmares Oauth Nightmares Abstract OAuth Nightmares
Oauth Nightmares Abstract OAuth Nightmares
 
2022 APIsecure_Why Assertion-based Access Token is preferred to Handle-based ...
2022 APIsecure_Why Assertion-based Access Token is preferred to Handle-based ...2022 APIsecure_Why Assertion-based Access Token is preferred to Handle-based ...
2022 APIsecure_Why Assertion-based Access Token is preferred to Handle-based ...
 
Why Assertion-based Access Token is preferred to Handle-based one?
Why Assertion-based Access Token is preferred to Handle-based one?Why Assertion-based Access Token is preferred to Handle-based one?
Why Assertion-based Access Token is preferred to Handle-based one?
 
OAuth with AngularJS and WebAPI - SoCal Code Camp 2015
OAuth with AngularJS and WebAPI - SoCal Code Camp 2015OAuth with AngularJS and WebAPI - SoCal Code Camp 2015
OAuth with AngularJS and WebAPI - SoCal Code Camp 2015
 
Implementing Microservices Security Patterns & Protocols with Spring
Implementing Microservices Security Patterns & Protocols with SpringImplementing Microservices Security Patterns & Protocols with Spring
Implementing Microservices Security Patterns & Protocols with Spring
 
OAuth - Don’t Throw the Baby Out with the Bathwater
OAuth - Don’t Throw the Baby Out with the Bathwater OAuth - Don’t Throw the Baby Out with the Bathwater
OAuth - Don’t Throw the Baby Out with the Bathwater
 
QA Fest 2019. Диана Пинчук. Тестирование аутентификации и авторизации (AuthN ...
QA Fest 2019. Диана Пинчук. Тестирование аутентификации и авторизации (AuthN ...QA Fest 2019. Диана Пинчук. Тестирование аутентификации и авторизации (AuthN ...
QA Fest 2019. Диана Пинчук. Тестирование аутентификации и авторизации (AuthN ...
 
OAuth in the Real World featuring Webshell
OAuth in the Real World featuring WebshellOAuth in the Real World featuring Webshell
OAuth in the Real World featuring Webshell
 
OAuth with Salesforce - Demystified
OAuth with Salesforce - DemystifiedOAuth with Salesforce - Demystified
OAuth with Salesforce - Demystified
 
REST API Authentication Methods.pdf
REST API Authentication Methods.pdfREST API Authentication Methods.pdf
REST API Authentication Methods.pdf
 
Techniques for securing rest
Techniques for securing restTechniques for securing rest
Techniques for securing rest
 
Lightweight Zero-trust Network Implementation and Transition with Keycloak an...
Lightweight Zero-trust Network Implementation and Transition with Keycloak an...Lightweight Zero-trust Network Implementation and Transition with Keycloak an...
Lightweight Zero-trust Network Implementation and Transition with Keycloak an...
 
Build your APIs with apigility
Build your APIs with apigilityBuild your APIs with apigility
Build your APIs with apigility
 

Último

%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
masabamasaba
 
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Medical / Health Care (+971588192166) Mifepristone and Misoprostol tablets 200mg
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
masabamasaba
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
Health
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
masabamasaba
 

Último (20)

%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand
 
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfPayment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
 
Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the past
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
Announcing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareAnnouncing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK Software
 
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
 
WSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go PlatformlessWSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go Platformless
 
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdf
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
 
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
 

Securing RESTful API

  • 1. SECURING RESTFUL API Muhammad Zbeedat Software and Data Quality IBM Research – Haifa 2017
  • 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
  • 9. TOKEN STRUCTURE 9 Tech CBT - https://www.youtube.com/watch?v=oXxbB5kv9OA
  • 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
  • 13. PROCESS: 13 Tech CBT - https://www.youtube.com/watch?v=oXxbB5kv9OA
  • 14. DEMONSTRATION: Create JWT http://jwtbuilder.jamiekurtz.com/ Verify JWT https://jwt.io/ Base64 encode/decode https://www.base64encode.org/ https://www.base64decode.org/ 14
  • 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
  • 27. The user sees the authorization prompt: 27
  • 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
  • 31. OAUTH DANCE 31 RestCase - http://blog.restcase.com/restful-api-authentication-basics/
  • 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