Skip to content

Instantly share code, notes, and snippets.

@kimukou
Created February 25, 2012 09:04
Show Gist options
  • Save kimukou/1907438 to your computer and use it in GitHub Desktop.
Save kimukou/1907438 to your computer and use it in GitHub Desktop.
GDataOAuth2.groovy
//
// ref https://gist.github.com/1899391
import java.io.*
import java.net.*
import groovy.transform.Field
//see @Field's Explanation http://d.hatena.ne.jp/uehaj/20110703/1309685397
//see https://docs.google.com/file/d/0B2exfmJ2W9X-VllQVFRTS3pSVm15aEpubnFULXVLUQ/edit P31
//need set CLIENT_ID key & CLIENT_SECRET
@Field String CLIENT_ID = ""
@Field String CLIENT_SECRET = ""
@Field String REDIRECT_URI = "urn:ietf:wg:oauth:2.0:oob" // InstalledApplication
@Field String SCOPES = "https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email"
@Field String ENDPOINT = "https://accounts.google.com/o/oauth2"
def retrieveTokens = {authorizationCode ->
def CLIENT_ID_= CLIENT_ID
def REDIRECT_URI_= REDIRECT_URI
def CLIENT_SECRET_= CLIENT_SECRET
// パラメータを組み立てる
StringBuilder b = new StringBuilder()
b.with{
it << "code=${URLEncoder.encode(authorizationCode, 'utf-8')}"
it << "&client_id=${URLEncoder.encode(CLIENT_ID_, 'utf-8')}"
it << "&client_secret=${URLEncoder.encode(CLIENT_SECRET_, 'utf-8')}"
it << "&redirect_uri=${URLEncoder.encode(REDIRECT_URI_, 'utf-8')}"
it << "&grant_type=authorization_code"
}
byte[] payload = b.toString().getBytes()
// POST メソッドでリクエストする
HttpURLConnection c = (HttpURLConnection) new URL(ENDPOINT + "/token").openConnection()
c.setRequestMethod("POST")
c.setDoOutput(true)
c.setRequestProperty("Content-Length", String.valueOf(payload.length))
c.getOutputStream().write(payload)
c.getOutputStream().flush()
// トークン類が入ったレスポンスボディの内容を返す(JSONで返される)
StringBuilder json = new StringBuilder()
/*
BufferedReader reader = new BufferedReader(new InputStreamReader(c.getInputStream()))
String line = null
while ((line = reader.readLine()) != null) {
json.append(line).append("\n")
}
*/
c.getInputStream().withReader{
it.eachLine{ json << it }
}
json.toString()
}
def retrieveAuthorizationCode = {
def CLIENT_ID_= CLIENT_ID
def REDIRECT_URI_= REDIRECT_URI
def SCOPES_= SCOPES
// パラメータを組み立てる
StringBuilder b = new StringBuilder()
b.with{
it << "response_type=code"
it << "&client_id=${URLEncoder.encode(CLIENT_ID_, 'utf-8')}"
it << "&redirect_uri=${URLEncoder.encode(REDIRECT_URI_, 'utf-8')}"
it << "&scope=${URLEncoder.encode(SCOPES_, 'utf-8')}"
it << "&state=dummy"
}
HttpURLConnection.setFollowRedirects(false)
// GET メソッドでリクエストする
HttpURLConnection c = (HttpURLConnection) new URL(ENDPOINT + "/auth?" + b.toString()).openConnection()
println "下記URLを開いて、アクセス承認後に表示された文字列を入力してください。"
println c.getHeaderField("Location") // Locationヘッダに、承認用URLが設定される
// ブラウザに表示されたauthorization codeを標準入力から入力させる。
//// 返却されたHTMLのタイトルにもauthorization codeが設定されているので、自動的に取得することもできる。
//// <title>Success state=dummy&ampcode=XXXXXXX</title>
//BufferedReader reader = new BufferedReader(new InputStreamReader(
// System.in))
//return reader.readLine()
java.awt.Desktop.getDesktop().browse(new URI(c.getHeaderField("Location")))
def authorizationCode
/*
//only groovy command . not running groovy Console
System.in.withReader {
authorizationCode = it.readLine()
}
*/
//see http://d.hatena.ne.jp/waman/20101209/1291846107
def pane = new groovy.swing.SwingBuilder().optionPane(
message:'Here is a authorizationCode.',
messageType:javax.swing.JOptionPane.INFORMATION_MESSAGE,
optionType:javax.swing.JOptionPane.OK_CANCEL_OPTION,
wantsInput:true,
initialSelectionValue:'')
def dialog = pane.createDialog(null, 'authorizationCode input message')
dialog.show()
authorizationCode = pane.inputValue
authorizationCode
}
// autherization codeを取得するためのURLを組み立てる
String authorizationCode = retrieveAuthorizationCode()
// autherization codeを使ってaccess tokenとrefresh tokenを取得する
String tokens = retrieveTokens authorizationCode
println tokens
int start = tokens.indexOf("\"access_token\" : \"") + "\"access_token\" : \"".length()
int end = tokens.indexOf("\"", start)
String accessToken = tokens.substring(start, end)
// user info APIを使ってみる。
HttpURLConnection c = (HttpURLConnection) new URL(
"https://www.googleapis.com/oauth2/v2/userinfo")
.openConnection()
// access tokenを Authorization Headerに指定するだけ!
c.setRequestProperty("Authorization", "OAuth $accessToken")
/*
BufferedReader reader = new BufferedReader(new InputStreamReader(c.getInputStream()))
String line = null
while ((line = reader.readLine()) != null) {
println(line)
}
*/
c.getInputStream().withReader{
it.eachLine{ println it }
}
@soundTricker
Copy link

👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment