© 2014 IBM Corporation
Securing your Restful APIs using Data PowerJagadish Vemugunta
Technical Architect (Availity)
Agenda
• Why Web APIs?
• Typical Web application security
• DataPower known capabilities
• DataPower as first line of defense for APIs
• DataPower Authentication workflow for APIs
• Integrating DataPower with your corporate Single Sign-On (SSO) servers
• Consume JSON Web Signature(JWS) in DataPower
• Single DataPower endpoint that supports multiple authentication schemes
• HTTP basic authentication
• Cookie based authentication
• JSON Web Token (JWT) based authentication
• OAUTH2
• Custom Security
• Logging Web API for transaction logging and reporting
• Real-time demo
• Questions and closing
1
Why Web APIs?
2
Wide range of clients available for consuming Web APIs
iPhone Android Windows
Tablet
WEB API
Web APIs cont’d
• REST(REpresentational State Transfer) is a simple stateless architecture that generally
runs over HTTP transport. When an Web API uses this architecture, it is known as
REST API.
• APIs that adhere to REST architectural style are called RESTful APIs.
• HTTP based RESTful APIs are defined with these aspects:
• base URL, such as http://example.com/resources/
• an Internet media type for the data. This is often JSON but can be any other valid Internet
media type (e.g. XML, Atom, microformats, images, etc.)
• standard HTTP methods (e.g., GET, PUT, POST, or DELETE)
• CRUD(create, read, update and delete) operations can be easily performed as they map
to standard HTTP methods.
• Examples:
3
URI HTTP Verb Functionality
/v1/login GET Logging in
/v1/users POST Signing up new user
/v1/users/<userID> GET Retrieve user
/v1/users/<userID> DELETE Delete user
Typical Web Application Security for Enterprises
4
Web
Server (+Config)
Web Client
SSO ServerWeb Site Policy Agent
1
2
34
5
1. The web client (browser) requests access to a protected
resource.
2. The web server runs the request through its policy agent that
protects the resource according to SSO policy. The policy
agent acts to enforce policy, whereas the policy
configuration and decisions are handled by SSO server.
3. The policy agent communicates with SSO Server to get the
policy decision to enforce.
4. For a resource to which SSO Server approves access, the
policy agent allows access.
5. The web server returns the requested access to the web
client.
Load Balancer
SSO – Single Sign-On
Data Power XI52 known capabilities
• Centralized Security
• Simplifies connectivity with vendors
• Advanced transformation and routing
• Advanced security (ws-security standards)
• Best in business - With HTTPs connections, encryption and digital signature
• Custom security - Custom connections can be written very easily.
• SLM peering – Global connection pool across the cluster of servers
• Throttling – Throttling can be done using SLM policies and/or Load balancer
groups
• Easy integration with JMS/MQ based systems
5
Data Power as first line of defense for APIs
6
Load Balancer
Data PowerWeb Server
API Application
ServersAPI Application
Servers
LDAP
SSO
Server
JWT
URI starts with /api For web traffic
Policy
Agent
SSO – Single Sign-On
Data Power Authentication for APIs- Workflow
7
Start: API Request Enters Data
Power from Load Balancer
Request contains
SSO cookie
header?Perform SSO
authentication request
Authenticated forward to API clusteryes
pass
Request contains
JWS
header?
Perform JWS
authentication request
yes pass
Authenticated forward to API cluster
Reject: HTTP 419: Authentication Timeout
Reject: HTTP 401: Unauthorized
JWS expired
fail
No
Request contains
Basic
Authentication
header?
Perform authentication
against LDAP
yes
Authenticated forward to API cluster
Reject: HTTP 401: Unauthorized
pass
fail
No
Do Not terminate failure here because
cookies are automatically sent by the browsers
fail
Integrating Data Power with your SSO servers
Most modern SSO servers support JSON or XML payloads on HTTP transport for SSO
cookie validation
8
Data Power
SSO
Server
SSO
Server
SSO
Server
Integrating Data Power with your SSO serverscont’d
Sample REST API call to SSO server
Request:
curl
"https://sso.example.com:sso/ssoserver/identity/attributes?subjectid=AQIC5wM2LY4SfcxuxI
P0VnP2lVjs7ypEM6VDx6srk56CN1Q.*AAJTSQACMDE.*&attributenames=mail&attributena
mes=uid"
Response:
userdetails.token.id=AQIC5wM2LY4SfcxuxIP0VnP2lVjs7ypEM6VDx6srk56CN1Q.*AAJTSQ
ACMDE.*
userdetails.attribute.name=uid
userdetails.attribute.value=jvemugunta
userdetails.attribute.name=mail
9
SSO – Single Sign-On
Integrating Data Power with your SSO serverscont’d
XSL code for making call to SSO server
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:dp="http://www.datapower.com/extensions"
xmlns:af="http://availity.com/functions" extension-element-prefixes="dp"
exclude-result-prefixes="date dp af">
<xsl:template match="/">
<xsl:variable name="subject">
<xsl:variable name="iplanetCookie"
select="substring-after(dp:request-header('Cookie'),'iPlanetDirectoryPro=')"></xsl:variable>
<xsl:choose>
<xsl:when test="contains($iplanetCookie,';')">
<xsl:value-of select="substring-before($iplanetCookie,';')"></xsl:value-of>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="$iplanetCookie"></xsl:value-of>
</xsl:otherwise>
</xsl:choose>
</xsl:variable>
<xsl:variable name="url" select="concat('http://', $ldap_lbgroup , '/openam/identity/attributes')" />
<xsl:variable name="binaryResponse">
<dp:url-open target="{$url}" response="responsecode-binary"
http-method="post" http-headers="$httpHeaders" timeout="10">
<xsl:text>subjectid=</xsl:text>
<xsl:value-of select="$subject"></xsl:value-of>
</dp:url-open>
</xsl:variable>
<xsl:variable name="encodedData"
select="dp:binary-encode($binaryResponse/result/binary)" />
<xsl:variable name="payload" select="dp:decode( $encodedData, 'base-64' )" />
</xsl:template>
</xsl:stylesheet>
10
Consume JSON Web Signature(JWS) in Data Power
What is JWT?
JSON Web Token (JWT) is a compact claims representation format intended for space
constrained environments such as HTTP Authorization headers and URI query parameters.
JWTs encode claims to be transmitted as a JavaScript Object Notation (JSON) object that is
used as the payload of a JSON Web Signature (JWS) structure.
JWT structure - base64 concatenated strings (JWT Header + JWT Claims Set + HMAC
SHA-256 Signature)
eyJ0eXAiOiJKV1QiLA0KICJhbGciOiJIUzI1NiJ9 (JWT Header)
.
eyJpc3MiOiJqb2UiLA0KICJleHAiOjEzMDA4MTkzODAsDQogImh0dHA6Ly9leGFtcGxlLmNvbS9pc19yb290Ijp0c
nVlfQ (JWT Claims Set)
.
dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk (HMAC SHA-256 signature)
JWT Header
{"typ":"JWT",
"alg":"HS256"}
11
Consume JSON Web Signature(JWS) in Data Power(cont’d)JWT Claims Set
{"iss":"joe",
"exp":1300819380,
"http://example.com/is_root":true}
HMAC SHA-256 signature
Computing the MAC of the encoded JWT Header and encoded JWT Claims Set with
the HMAC SHA-256 algorithm and base64url encoding the HMAC value yields this
encoded JWS Signature.
12
Consume JSON Web Signature(JWS) in Data Power(cont’d)DataPower JWS XSL functions
Custom XSL JWS functions
1. isJWSHeaderValid()
2. getClientSecretFromLDAP()
3. isJWSSignatureValid()
• isJWSHeaderValid– Validates the incoming JWS signature (JWT header + Claims Set+
HMAC signature ) are in the correct order and adhere to JWS specification.
• getClientSecretFromLDAP – extracts the client secret from LDAP based on the appID
from the incoming request
• isJWSSignatureValid – Generate the HMAC signature from the incoming request
elements (JWT header + Claims Set) using the client secret from
“getClientSecretFromLDAP “ and compare the signature with the input signature
13
Consume JSON Web Signature(JWS) in Data Power(cont’d)isJWSSignatureValid code snippet
<f:function name="af:isJWSSignatureValid">
<xsl:param name="jwtHeader" />
<xsl:param name="jwtPayload" />
<xsl:param name="jwtSignature" />
<xsl:param name="clientSecret" />
<xsl:variable name="jwsInput" select="concat($jwtHeader,'.',$jwtPayload)"></xsl:variable>
<xsl:variable name="jwsGeneratedSignature"
select="af:generateHMAC256Signature($jwsInput,$clientSecret)"></xsl:variable>
<xsl:variable name="var1"
select="regexp:replace($jwsGeneratedSignature, '=', 'g', '')" />
<xsl:variable name="var2" select="regexp:replace($var1, '/', 'g', '_')" />
<xsl:variable name="var3"
select="regexp:replace($var2, '\+', 'g', '-')" />
<dp:set-variable name="'var://context/api/dpjwsSignature'"
value="$var3" />
<xsl:choose>
<xsl:when test="$var3 = $jwtSignature">
<f:result select="true()" />
</xsl:when>
<xsl:otherwise>
<f:result select="false()" />
</xsl:otherwise>
</xsl:choose>
</f:function>
14
Consume JSON Web Signature(JWS) in Data Power(cont’d)generateHMAC256Signature code snippet
<f:function name="af:generateHMAC256Signature">
<xsl:param name="data" />
<xsl:param name="clientSecret" />
<xsl:variable name="algorithm"
select="'http://www.w3.org/2001/04/xmldsig-more#hmac-
sha256'"></xsl:variable>
<xsl:variable name="key" select="concat('key:',$clientSecret)" />
<xsl:variable name="result"
select="dp:hmac($algorithm,$key,$data)"></xsl:variable>
<f:result select="$result" />
</f:function>
15
Logging Web API for transaction logging and reporting
• DataPower support many out-of-box target types for off-device logging. Some of the log targets include syslog , sylog-tcp, SOAP, NFS etc.
• All of our API off-device logging is done to Splunk using syslog UDP log target
• Once the logging is done, all of the real-time transaction logging and reporting is available through splunk.
Example of the sample audit log function
<f:function name="af:audit">
<xsl:variable name="auditMessage">
<xsl:value-of
select="af:addQuotes('ti',dp:variable('var://context/api/receivedTimeStamp'))" />
<xsl:value-of
select="af:addQuotes('apiid',dp:variable('var://context/api/apiID'))" />
<xsl:value-of
select="af:addQuotes('dur',dp:variable('var://context/api/duration'))" />
<xsl:value-of select="af:addQuotes('appID',af:getAPPID())" />
<xsl:value-of
select="af:addQuotes('gtid',dp:variable('var://context/api/gtid'))" />
<xsl:value-of select="af:addQuotes('error',af:getDPError(),false())" />
</xsl:variable>
<xsl:message dp:type="{$dpAuditLogCategory}" dp:priority="notice">
<xsl:value-of select="$auditMessage"
disable-output-escaping="yes" />
</xsl:message>
<f:result select="$auditMessage" />
</f:function>
16
Single Data Power endpoint (Basic Authentication example)
API endpoint can be accessed using a simple user ID and password
curl -i -k --user 'jvemugunta:test' https://tst.api.availity.com/v1/users/me;echo
HTTP/1.1 200 OK
Content-Type: application/json
x-api-id: f390fa30-495e-4e51-9883-2cbf378a4b2f
X-Session-ID: f390fa30-495e-4e51-9883-2cbf378a4b2f
Cache-Control: private, no-store, max-age=0, must-revalidate
Date: Tue, 06 Jan 2015 19:10:59 GMT
Connection: close
{
"metadata" : {
"totalCount" : 1
},
"user" : {
"id" : "aka12485434583",
"firstName" : "Jagadish",
"lastName" : "Vemugunta",
"emailAddress" : "[email protected]",
"states" : [ {
"code" : "AL",
"value" : "Alabama"
}, {
"code" : "AZ",
"value" : "Arizona"
},{
"code" : "WI",
"value" : "Wisconsin"
} ],
"userSettings" : {
"currentGeography" : "AL",
"verificationEmailSentDate" : "2014-07-01T11:59:56.000+0000",
"verificationEmailStatus" : true
}
}
}
17
Single Data Power endpoint (SSO Cookie example)
API endpoint can be accessed using an SSO cookie
curl -i -k -H 'Cookie:iPlanetDirectoryPro=AQIC5wM2LY4SfcwtUeB2acxnvXZNT3GSO4LSUPufyGHyvn4.*AAJTSQACMDIAAlNLABQtMTQ1MDU1MzczNDIzOTQzNjAzMwACUzEAAjAx*' https://test-apps.availity.com/api/v1/users/me;echo
HTTP/1.1 200 OK
Connection: close
Transfer-Encoding: chunked
Content-Type: application/json
x-api-id: 4d0d50e9-5272-4cb1-85b5-63fdd3ee61ce
X-Session-ID: 4d0d50e9-5272-4cb1-85b5-63fdd3ee61ce
Cache-Control: private, no-store, max-age=0, must-revalidate
Date: Tue, 06 Jan 2015 19:21:10 GMT
{
"metadata" : {
"totalCount" : 1
},
"user" : {
"id" : "aka12485434583",
"firstName" : "Jagadish",
"lastName" : "Vemugunta",
"emailAddress" : "[email protected]",
"states" : [ {
"code" : "AL",
"value" : "Alabama"
},{
"code" : "WI",
"value" : "Wisconsin"
} ],
"userSettings" : {
"currentGeography" : "AL",
"verificationEmailSentDate" : "2014-07-01T11:59:56.000+0000",
"verificationEmailStatus" : true
}
}
}
18
SSO – Single Sign-On
Single Data Power endpoint (JWT example)
API endpoint can be accessed using an JSON Web Token (JWT) example
curl -i -k -H 'Authorization:JWSeyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJhYmMiLCJpc3MiOiJSQ00iLCJpYXQiOjE0MjA4MzA0OTl9.JzbvdiChStsvD3kcAs6lzxMvaPzVVYHmAqydrwGh_E4' 'https://tst.api.availity.com/v1/coverages/0258142559210370832182890069792126425125811246098542362277902409'
HTTP/1.1 200 OK
Content-Type: application/json
x-api-id: 70090e6f-3253-4d1b-b1b8-ee38137dfcac
X-Session-ID: 70090e6f-3253-4d1b-b1b8-ee38137dfcac
Cache-Control: private, no-store, max-age=0, must-revalidate
Date: Fri, 09 Jan 2015 19:11:31 GMT
Connection: close
{
"links" : {
"batch" : {
"href" : "https://tst.api.availity.com/v1/batches/0258142147168524851540185564449286134397469506581557230672792059"
},
"coverageResponse" : {
"href" : "https://tst.api.availity.com/sdk/v1/documents/14190028690820172516473000004046"
},
"coverageRequest" : {
"href" : "https://tst.api.availity.com/sdk/v1/documents/14190027777590172516473000003556"
},
"self" : {
"href" : "https://tst.api.availity.com/v1/coverages/0258142559210370832182890069792126425125811246098542362277902409"
},
"coverageTransaction" : {
"href" : "https://tst.api.availity.com/sdk/v1/transactions/14190027698650172516473000004745"
}
}
}
19
Questions?
Live Demo
Thank YouYour Feedback is
Important!
Access the InterConnect 2015
Conference CONNECT Attendee Portal
to complete your session surveys from
your smartphone, laptop or conference
kiosk.