Skip to content

Instantly share code, notes, and snippets.

@yincrash
Created April 22, 2012 17:22
Show Gist options
  • Star 35 You must be signed in to star a gist
  • Fork 9 You must be signed in to fork a gist
  • Save yincrash/2465453 to your computer and use it in GitHub Desktop.
Save yincrash/2465453 to your computer and use it in GitHub Desktop.
Google OAuth2.0 for scribe-java
package org.scribe.builder.api;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.scribe.exceptions.OAuthException;
import org.scribe.extractors.AccessTokenExtractor;
import org.scribe.model.OAuthConfig;
import org.scribe.model.OAuthConstants;
import org.scribe.model.OAuthRequest;
import org.scribe.model.Response;
import org.scribe.model.Token;
import org.scribe.model.Verb;
import org.scribe.model.Verifier;
import org.scribe.oauth.OAuth20ServiceImpl;
import org.scribe.oauth.OAuthService;
import org.scribe.utils.OAuthEncoder;
import org.scribe.utils.Preconditions;
/**
* Google OAuth2.0
* Released under the same license as scribe (MIT License)
* @author yincrash
*
*/
public class Google2Api extends DefaultApi20 {
private static final String AUTHORIZE_URL = "https://accounts.google.com/o/oauth2/auth?response_type=code&client_id=%s&redirect_uri=%s";
private static final String SCOPED_AUTHORIZE_URL = AUTHORIZE_URL + "&scope=%s";
@Override
public String getAccessTokenEndpoint() {
return "https://accounts.google.com/o/oauth2/token";
}
@Override
public AccessTokenExtractor getAccessTokenExtractor() {
return new AccessTokenExtractor() {
@Override
public Token extract(String response) {
Preconditions.checkEmptyString(response, "Response body is incorrect. Can't extract a token from an empty string");
Matcher matcher = Pattern.compile("\"access_token\" : \"([^&\"]+)\"").matcher(response);
if (matcher.find())
{
String token = OAuthEncoder.decode(matcher.group(1));
return new Token(token, "", response);
}
else
{
throw new OAuthException("Response body is incorrect. Can't extract a token from this: '" + response + "'", null);
}
}
};
}
@Override
public String getAuthorizationUrl(OAuthConfig config) {
// Append scope if present
if (config.hasScope()) {
return String.format(SCOPED_AUTHORIZE_URL, config.getApiKey(),
OAuthEncoder.encode(config.getCallback()),
OAuthEncoder.encode(config.getScope()));
} else {
return String.format(AUTHORIZE_URL, config.getApiKey(),
OAuthEncoder.encode(config.getCallback()));
}
}
@Override
public Verb getAccessTokenVerb() {
return Verb.POST;
}
@Override
public OAuthService createService(OAuthConfig config) {
return new GoogleOAuth2Service(this, config);
}
private class GoogleOAuth2Service extends OAuth20ServiceImpl {
private static final String GRANT_TYPE_AUTHORIZATION_CODE = "authorization_code";
private static final String GRANT_TYPE = "grant_type";
private DefaultApi20 api;
private OAuthConfig config;
public GoogleOAuth2Service(DefaultApi20 api, OAuthConfig config) {
super(api, config);
this.api = api;
this.config = config;
}
@Override
public Token getAccessToken(Token requestToken, Verifier verifier) {
OAuthRequest request = new OAuthRequest(api.getAccessTokenVerb(), api.getAccessTokenEndpoint());
switch (api.getAccessTokenVerb()) {
case POST:
request.addBodyParameter(OAuthConstants.CLIENT_ID, config.getApiKey());
request.addBodyParameter(OAuthConstants.CLIENT_SECRET, config.getApiSecret());
request.addBodyParameter(OAuthConstants.CODE, verifier.getValue());
request.addBodyParameter(OAuthConstants.REDIRECT_URI, config.getCallback());
request.addBodyParameter(GRANT_TYPE, GRANT_TYPE_AUTHORIZATION_CODE);
break;
case GET:
default:
request.addQuerystringParameter(OAuthConstants.CLIENT_ID, config.getApiKey());
request.addQuerystringParameter(OAuthConstants.CLIENT_SECRET, config.getApiSecret());
request.addQuerystringParameter(OAuthConstants.CODE, verifier.getValue());
request.addQuerystringParameter(OAuthConstants.REDIRECT_URI, config.getCallback());
if(config.hasScope()) request.addQuerystringParameter(OAuthConstants.SCOPE, config.getScope());
}
Response response = request.send();
return api.getAccessTokenExtractor().extract(response.getBody());
}
}
}
@eranation
Copy link

Thanks, it works like a charm (used the Facebook example to get a clue on how to use it)

@saurabh-agrawal83
Copy link

thanks, I was searching for this for more than 2hrs :-)..

@gabrielrubens
Copy link

Thank you.

It was pretty cool, could go in a pull request

Thank you!

@manishkbharti
Copy link

Thank you.
This works perfectly fine with grails oauth plugin also.
Thanks a lot.

@dgosset
Copy link

dgosset commented May 30, 2014

"Google has deprecated OpenID 2.0 and will shut it down after a migration period" (May 19, 2014.) Your code can help peoples with Scribe. You don't send a pull request on the origin project with this ? The current project has only "GoogleApi extends DefaultApi10a"

@davejordan
Copy link

Thank you.
Really great contribution. I was struggling with this for ages.

@azerafati
Copy link

anyone could guide me how to use this?
by calling ".getRequestToken()" it returns an exception,

@MarcosBermudez
Copy link

Usage exemple, is the adaption of the Facebook scribe exemple :
https://github.com/fernandezpablo85/scribe-java/blob/master/src/test/java/org/scribe/examples/FacebookExample.java

   private static final String PROTECTED_RESOURCE_URL = "https://www.googleapis.com/userinfo/v2/me";
   private static final String SCOPE = "openid email profile";

   public static void main(String[] args)  {

    // Replace these with your own api key and secret
    String apiKey = YourKeys.GOOGLE_API_KEY;
    String apiSecret = YourKeys.GOOGLE_API_SECRET;
    OAuthService service = new ServiceBuilder().provider(Google2Api.class).apiKey(apiKey).scope(SCOPE)
            .apiSecret(apiSecret).callback(YourKeys.CALLBACK).build();
    Scanner in = new Scanner(System.in);
    System.out.println("=== " + NETWORK_NAME + "'s OAuth Workflow ===");
    System.out.println();

    // Obtain the Authorization URL
    System.out.println("Fetching the Authorization URL...");
    String authorizationUrl = service.getAuthorizationUrl(EMPTY_TOKEN);
    System.out.println("Got the Authorization URL!");
    System.out.println("Now go and authorize Scribe here:");
    System.out.println(authorizationUrl);
    System.out.println("And paste the authorization code here");
    System.out.print(">>");
    Verifier verifier = new Verifier(in.nextLine());
    System.out.println();

    // Trade the Request Token and Verfier for the Access Token
    System.out.println("Trading the Request Token for an Access Token...");
    Token accessToken = service.getAccessToken(EMPTY_TOKEN, verifier);
    System.out.println("Got the Access Token!");
    System.out.println("(if your curious it looks like this: " + accessToken + " )");
    System.out.println();

    // Now let's go and ask for a protected resource!
    System.out.println("Now we're going to access a protected resource...");
    OAuthRequest request = new OAuthRequest(Verb.GET, PROTECTED_RESOURCE_URL);
    service.signRequest(accessToken, request);
    Response response = request.send();
    System.out.println("Got it! Lets see what we found...");
    System.out.println();
    System.out.println(response.getCode());
    System.out.println(response.getBody());

    System.out.println();
    System.out.println("Thats it man! Go and build something awesome with Scribe! :)");

}

@liqiang372
Copy link

for those who need a help on how to use this class, see this tutorial

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