Repost: oAuth 2 (Google) and CFML without cfoauth

Hopefully, this will save someone a bunch of time. This is a very simple example of how to do oAuth 2 (in this case, with Google) in CFML without using ACF 11’s new oauth tag:

1-time steps:

Use https://console.developers.google.com to add a new Project and then a new Client ID for native application.

Get your code by using your browser to visit:

https://accounts.google.com/o/oauth2/auth?scope=[urlencodedformat of API’s scope from API’s docs]&redirect_uri=urn:ietf:wg:oauth:2.0:oob&response_type=code&client_id=[client ID from above]

Get your refresh_token by dumping the results of this cfhttp:

<cfhttp url="https://accounts.google.com/o/oauth2/token" method="post">
    <cfhttpparam name="code" value="[code from above]" type="formfield">
    <cfhttpparam name="client_id" value="[client ID from above]" type="formfield">
    <cfhttpparam name="client_secret" value="[client secret from above]" type="formfield">
    <cfhttpparam name="redirect_uri" value="urn:ietf:wg:oauth:2.0:oob" type="formfield">
    <cfhttpparam name="grant_type" value="authorization_code" type="formfield">
</cfhttp>

result:

{
"access_token" : "[an access token]",
"token_type" : "Bearer",
"expires_in" : 3600,
"refresh_token" : "[your refresh token]"
}

end of 1-time steps

Now that you have your refresh token (which should not change), you can use it whenever you need a new access token, as follows:

<cfhttp url="https://accounts.google.com/o/oauth2/token" method="post">
    <cfhttpparam name="client_id" value="[client ID from above]" type="formfield">
    <cfhttpparam name="client_secret" value="[client secret from above]" type="formfield">
    <cfhttpparam name="refresh_token" value="[refresh token from above]" type="formfield">
    <cfhttpparam name="grant_type" value="refresh_token" type="formfield">
</cfhttp>

…and then use it in your API calls, like this:

<cfhttp>
    <cfhttpparam name="Authorization" type="header" value="Bearer #deserializejson(cfhttp.filecontent).access_token#"/>
</cfhttp>

Enjoy!


Posted

in

by

Tags: