Thursday, September 19, 2013

How to Get an OAuth 2.0 Token's Scopes

Occasionally, you may have an OAuth 2.0 refresh token for a Google account and need to know which scopes it's valid for.

What you'll need:
  • A refresh token or a session token.
  • The client ID
  • The client secret

First, if we have a refresh token instead of a session token, we'll need to convert that refresh token into a valid session token (set CLIENT_ID, CLIENT_SECRET, and REFRESH_TOKEN environment variables appropriately):

$ curl -s -S -X POST -H "Host: accounts.google.com" -H "Content-Type: application/x-www-form-urlencoded" -d "client_id=${CLIENT_ID}&client_secret=${CLIENT_SECRET}&refresh_token=${REFRESH_TOKEN}&grant_type=refresh_token" "https://accounts.google.com/o/oauth2/token" | jq .access_token

Bam, session token.

Second, we need to get a list of scopes for which the session token is valid:

curl -s -S "https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=${access_token}" | jq .scope

Bam, list of scopes!

Here's the whole thing as a simple bash script:

<pre  style="font-family:arial;font-size:12px;border:1px dashed #CCCCCC;width:99%;height:auto;overflow:auto;background:#f0f0f0;padding:0px;color:#000000;text-align:left;line-height:20px;"><code style="color:#000000;word-wrap:normal;">#!/bin/bash  
   
 if [ $# -ne 3 ]; then  
  echo  
  echo "Requires 3 arguments: client_id client_secret refresh_token"  
  echo  
  exit 65  
 fi  
   
 echo $1, $2, $3  
   
 CLIENT_ID=$1  
 CLIENT_SECRET=$2  
 REFRESH_TOKEN=$3  
   
 #set -x  
   
 access_token=`curl -s -S -X POST -H "Host: accounts.google.com" -H "Content-Type: application/x-www-form-urlencoded" -d "client_id=${CLIENT_ID}&amp;client_secret=${CLIENT_SECRET}&amp;refresh_token=${REFRESH_TOKEN}&amp;grant_type=refresh_token" "https://accounts.google.com/o/oauth2/token" | jq .access_token`  
 curl -s -S "https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=${access_token}" | jq .scope  
</code></pre>

And here's how we'd invoke it:
$ get_scopes 23482398423892389.googleapps.totallyfake 328238-234asdfasdssdf 1/2323xz8s8se7327

No comments:

Post a Comment