3
votes

I am trying to connect Azure DocumentDB/CosmosDB through the coldfusion but receiving 401 authorization error. I already installed the certificates but still having the same issue. I tried with PHP, Nodejs, both are performing well except ColdFusion. Also tried using coldfusion script but the error remains same. Here is the code what I wrote:

<cfset x_ms_date="#GetHttpTimeString(now())#"/>
<cfset br = "#chr(13)##chr(10)#">
<cfset signStr="GET#br#dbs#br##br##x_ms_date##br##br#" />
<cfset strBase64ValueKey="BASE64_ENCODED_MASTER_KEY" />
<cfset key=ToString(ToBinary(strBase64ValueKey))/>
<cfset x=ToBase64(hmac(LCase(signStr),LCase(key),"HMACSHA256"))>


<cfhttp method="GET" url="https://APP_URL.documents.azure.com/dbs" throwonerror="Yes">
<cfhttpparam name="Authorization" type="header" value="#URLEncodedFormat("type=master&ver=1.0&sig="&x)#">
<cfhttpparam name="x-ms-date" type="header" value="#x_ms_date#">
<cfhttpparam name="x-ms-version" type="header" value="2017-02-22">
</cfhttp>
<cfoutput>
    #cfhttp.fileContent#
</cfoutput>

Here is the response from the above code:

{"code":"Unauthorized","message":"The input authorization token can't serve the request. Please check that the expected payload is built as per the protocol, and check the key being used. Server used the following payload to sign: 'get\ndbs\n\nthu, 08 feb 2018 19:52:03 gmt\n\n'\r\nActivityId: aab94428-63a0-4eb7-807b-SOMETHING, Microsoft.Azure.Documents.Common/1.20.186.1"}

What is the wrong with that code? Thanks in advance

1

1 Answers

2
votes

This would work if you change the code to something like this:

<cfset x_ms_date = GetHttpTimeString(now()) />

<cfset strBase64ValueKey = "BASE64_ENCODED_MASTER_KEY" />
<cfset br = chr(10)>
<cfset signStr = "GET#br#dbs#br##br##x_ms_date##br##br#" />

<cfset secret = createObject('java', 'javax.crypto.spec.SecretKeySpec' ).Init(BinaryDecode(strBase64ValueKey, "Base64"), 'HmacSHA256')/>
<cfset mac = createObject('java', "javax.crypto.Mac")/>
<cfset mac = mac.getInstance("HmacSHA256")/>
<cfset mac.init(secret)/>
<cfset x = mac.doFinal(LCase(signStr).GetBytes())>
<cfset sig = BinaryEncode(x, "Base64")>
<cfset token = URLEncodedFormat("type=master&ver=1.0&sig=#sig#")>


<cfhttp method="GET" url="https://APP_URL.documents.azure.com/dbs" throwonerror="Yes">
    <cfhttpparam name="Authorization" type="header" value="#token#">
    <cfhttpparam name="x-ms-date" type="header" value="#x_ms_date#">
    <cfhttpparam name="x-ms-version" type="header" value="2017-02-22">
</cfhttp>

<cfoutput>
    #cfhttp.fileContent#
</cfoutput>