Java tutorial
/* * Copyright (c) 2011 Google Inc. * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package me.emily.oauth2; import java.io.IOException; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.api.client.auth.oauth2.Credential; import com.google.api.client.auth.oauth2.CredentialStore; import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow; import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets; import com.google.api.client.googleapis.auth.oauth2.GoogleOAuthConstants; import com.google.api.client.googleapis.auth.oauth2.GoogleTokenResponse; import com.google.api.client.http.HttpTransport; import com.google.api.client.json.JsonFactory; import com.google.common.collect.Iterables; import com.google.inject.Inject; public class OAuth2Native { private static final Logger log = LoggerFactory.getLogger(OAuth2Native.class); @Inject private GoogleClientSecrets clientSecrets; @Inject private CredentialStore credentialStore; @Inject private JsonFactory jsonFactory; @Inject private HttpTransport transport; public OAuth2Native() { super(); } public Credential authorize(String code, Iterable<String> scopes) throws IOException { GoogleAuthorizationCodeFlow flow = startFlow(scopes); GoogleTokenResponse response = flow.newTokenRequest(code) .setRedirectUri(GoogleOAuthConstants.OOB_REDIRECT_URI).execute(); log.info("/------------ Response "); log.info("| Id: {}", response.getIdToken()); log.info("| Token: {}", response.getAccessToken()); log.info("| Refresh token: {}", response.getRefreshToken()); log.info("| Expiry: {}", response.getExpiresInSeconds()); log.info("| Type: {}", response.getTokenType()); log.info("| Scope: {}", response.getScope()); for (Map.Entry<String, Object> entry : response.getUnknownKeys().entrySet()) { log.info("| {}: {}", entry.getKey(), entry.getValue()); } log.info("\\------------"); Credential creds = flow.createAndStoreCredential(response, null); return creds; } public String requestAccess(Iterable<String> scopes) { GoogleAuthorizationCodeFlow flow = startFlow(scopes); String build = flow.newAuthorizationUrl() .setRedirectUri(Iterables.getFirst(clientSecrets.getInstalled().getRedirectUris(), "")).build(); return build; } private GoogleAuthorizationCodeFlow startFlow(Iterable<String> scopes) { return new GoogleAuthorizationCodeFlow.Builder(transport, jsonFactory, clientSecrets, scopes) .setAccessType("offline").setApprovalPrompt("auto").build(); } }