Search code examples
coldfusionoauth-2.0http-status-code-405

Google oauth token giving 405 error


I am trying to post using below Code. I expect it to return token but its returning error 405 Method Not Allowed.

<cfhttp method="POST" url="http://accounts.google.com/o/oauth2/token" >
    <cfhttpparam type="Formfield" name="code" value="#url.CODE#">
    <cfhttpparam type="Formfield" name="client_id" value="458381219741.apps.googleusercontent.com">
    <cfhttpparam type="Formfield" name="client_secret" value="XXXXXXX">
    <cfhttpparam type="Formfield" name="redirect_uri" value="http://console.mbwebportal.com/oauth2callback">
    <cfhttpparam type="Formfield" name="grant_type" value="authorization_code">
</cfhttp>

The above code is on http://console.mbwebportal.com/oauth2callback and it gets the Code in url after user allows access to the application.

Please help!!


Solution

  • I found the answer: key was to use cfhttpparam type 'body'. As per livedocs "body: specifies the body of the HTTP request. ColdFusion does not automatically set a content-type header or URL encode the body contents. To specify the content-type, use a separate cfhttp tag with type=header. "

    Below code is returning me access token now :)

    <cfset client_id = "458381219741.apps.googleusercontent.com">
    <cfset client_secret = "**********">
    <cfset callback = "http://console.mbwebportal.com/oauth2callback">
    
    <cfset postBody = "code=" & UrlEncodedFormat(url.code) & "&">
    <cfset postBody = postBody & "client_id=" & UrlEncodedFormat(client_id) & "&">
    <cfset postBody = postBody & "client_secret=" & UrlEncodedFormat(client_secret) & "&">
    <cfset postBody = postBody & "redirect_uri=" & UrlEncodedFormat(callback) & "&">
    <cfset postBody = postBody & "grant_type=authorization_code">
    <cfhttp method="post" url="https://accounts.google.com/o/oauth2/token">
        <cfhttpparam name="Content-Type" type="header" value="application/x-www-form-urlencoded">
        <cfhttpparam type="body" value="#postBody#">
    </cfhttp>