Google OAuth 2.0 Scribe Java Example

Google OAuthServiceConfig and OAuthServiceProvider Bean

<bean id="gdServiceConfig" class="com.example.oauth.OAuthServiceConfig">
		<constructor-arg value="xxx.apps.googleusercontent.com" />
		<constructor-arg value="xxx"/>
		<constructor-arg value="https://www.example.com/oauth/gd"/>
		<!-- <constructor-arg value="openid profile email https://www.googleapis.com/auth/drive.file"/> -->
		<constructor-arg value="com.example.oauth.GoogleDriveOauthApi"/>
	</bean>
	<bean id="gdServiceProvider" class="com.example.oauth.OAuthServiceProvider">
		<constructor-arg name="config" ref="gdServiceConfig" />
	</bean>
</bean>

Google OAuth Spring MVC Controller

package com.example.oauth.controller;

import static org.springframework.web.context.request.RequestAttributes.SCOPE_SESSION;

import java.util.Map;

import javax.servlet.http.HttpSession;

import org.scribe.model.Token;
import org.scribe.model.Verifier;
import org.scribe.oauth.OAuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.context.request.WebRequest;

import com.example.oauth.OAuthServiceProvider;

@Controller
@RequestMapping("/oauth/gd")
public class GoogleDriveController {

	@Autowired
	@Qualifier("gdServiceProvider")
	private OAuthServiceProvider gdServiceProvider;
	
	private static final Token EMPTY_TOKEN = null;
	
	@RequestMapping(value = "/login-gd", method = RequestMethod.GET)
	public String loginToGoogleDrive(Map<String, Object> map, WebRequest request) {
		OAuthService service = gdServiceProvider.getService();
		String auth = service.getAuthorizationUrl(EMPTY_TOKEN);
		System.out.println("RequestToken: " + auth);
		return "redirect:" + auth;
	}
	
	@RequestMapping(value={""}, method = RequestMethod.GET)
	public String callback(@RequestParam(value="oauth_token", required=false) String oauthToken,
			@RequestParam(value="code", required=false) String oauthVerifier, WebRequest request, Map<String, Object> map) {

		OAuthService service = gdServiceProvider.getService();

		// getting access token
		Verifier verifier = new Verifier(oauthVerifier);
		Token accessToken = service.getAccessToken(EMPTY_TOKEN, verifier);

		// store access token as a session attribute
		request.setAttribute("oauthAccessToken", accessToken, SCOPE_SESSION);

		ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
		HttpSession session = attr.getRequest().getSession(false); //create a new session
		session.setAttribute("accessToken",accessToken);

		return "settings";
	}
}

Google OAuth extends DefaultApi20

package com.example.oauth;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.scribe.builder.api.DefaultApi20;
import org.scribe.extractors.AccessTokenExtractor;
import org.scribe.model.OAuthConfig;
import org.scribe.model.Verb;
import org.scribe.exceptions.OAuthException;
import org.scribe.model.OAuthConstants;
import org.scribe.model.OAuthRequest;
import org.scribe.model.Response;
import org.scribe.model.Token;
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;

public class GoogleDriveOauthApi 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) {
            return String.format(SCOPED_AUTHORIZE_URL, config.getApiKey(),
                    OAuthEncoder.encode(config.getCallback()),
                    OAuthEncoder.encode("openid profile email https://www.googleapis.com/auth/drive.file"));
	    }
	    
	    @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, "openid profile email https://www.googleapis.com/auth/drive.file");
	            }
	            Response response = request.send();
	            return api.getAccessTokenExtractor().extract(response.getBody());
	        }
	    }
}

2 thoughts on “Google OAuth 2.0 Scribe Java Example

  1. Atlanta can be a non profit organization focused on assisting the low-income and displaced families while in the city area.

  2. They are ready to discover new as well as innovative solutions to increase the actual profit margin. This choosiness brings fruit for the faultless campaign is known to fetch the finest of results.
    As soon as you launch your own website or online business, you will need the right SEO Agency to help you in many activities.
    Due to a dearth of top SEO experts and growing demand, the business is able to command best profit margins.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s