Search in sources :

Example 1 with UrlEncodedContent

use of com.google.api.client.http.UrlEncodedContent in project google-auth-library-java by google.

the class UserAuthorizer method getCredentialsFromCode.

/**
 * Returns a UserCredentials instance by exchanging an OAuth2 authorization code for tokens.
 *
 * @param code Code returned from OAuth2 consent prompt.
 * @param baseUri The URI to resolve the OAuth2 callback URI relative to.
 * @return the UserCredentials instance created from the authorization code.
 * @throws IOException An error from the server API call to get the tokens.
 */
public UserCredentials getCredentialsFromCode(String code, URI baseUri) throws IOException {
    Preconditions.checkNotNull(code);
    URI resolvedCallbackUri = getCallbackUri(baseUri);
    GenericData tokenData = new GenericData();
    tokenData.put("code", code);
    tokenData.put("client_id", clientId.getClientId());
    tokenData.put("client_secret", clientId.getClientSecret());
    tokenData.put("redirect_uri", resolvedCallbackUri);
    tokenData.put("grant_type", "authorization_code");
    UrlEncodedContent tokenContent = new UrlEncodedContent(tokenData);
    HttpRequestFactory requestFactory = transportFactory.create().createRequestFactory();
    HttpRequest tokenRequest = requestFactory.buildPostRequest(new GenericUrl(tokenServerUri), tokenContent);
    tokenRequest.setParser(new JsonObjectParser(OAuth2Utils.JSON_FACTORY));
    HttpResponse tokenResponse = tokenRequest.execute();
    GenericJson parsedTokens = tokenResponse.parseAs(GenericJson.class);
    String accessTokenValue = OAuth2Utils.validateString(parsedTokens, "access_token", FETCH_TOKEN_ERROR);
    int expiresInSecs = OAuth2Utils.validateInt32(parsedTokens, "expires_in", FETCH_TOKEN_ERROR);
    Date expirationTime = new Date(new Date().getTime() + expiresInSecs * 1000);
    AccessToken accessToken = new AccessToken(accessTokenValue, expirationTime);
    String refreshToken = OAuth2Utils.validateOptionalString(parsedTokens, "refresh_token", FETCH_TOKEN_ERROR);
    return UserCredentials.newBuilder().setClientId(clientId.getClientId()).setClientSecret(clientId.getClientSecret()).setRefreshToken(refreshToken).setAccessToken(accessToken).setHttpTransportFactory(transportFactory).setTokenServerUri(tokenServerUri).build();
}
Also used : HttpRequest(com.google.api.client.http.HttpRequest) HttpRequestFactory(com.google.api.client.http.HttpRequestFactory) UrlEncodedContent(com.google.api.client.http.UrlEncodedContent) HttpResponse(com.google.api.client.http.HttpResponse) GenericUrl(com.google.api.client.http.GenericUrl) URI(java.net.URI) GenericData(com.google.api.client.util.GenericData) Date(java.util.Date) GenericJson(com.google.api.client.json.GenericJson) JsonObjectParser(com.google.api.client.json.JsonObjectParser)

Example 2 with UrlEncodedContent

use of com.google.api.client.http.UrlEncodedContent in project google-api-java-client by google.

the class MethodOverride method intercept.

public void intercept(HttpRequest request) throws IOException {
    if (overrideThisMethod(request)) {
        String requestMethod = request.getRequestMethod();
        request.setRequestMethod(HttpMethods.POST);
        request.getHeaders().set(HEADER, requestMethod);
        if (requestMethod.equals(HttpMethods.GET)) {
            // take the URI query part and put it into the HTTP body
            request.setContent(new UrlEncodedContent(request.getUrl().clone()));
            // remove query parameters from URI
            request.getUrl().clear();
        } else if (request.getContent() == null) {
            // Google servers will fail to process a POST unless the Content-Length header is specified
            request.setContent(new EmptyContent());
        }
    }
}
Also used : UrlEncodedContent(com.google.api.client.http.UrlEncodedContent) EmptyContent(com.google.api.client.http.EmptyContent)

Example 3 with UrlEncodedContent

use of com.google.api.client.http.UrlEncodedContent in project openhab1-addons by openhab.

the class GCalGoogleOAuth method getCredential.

/**
     * <p>
     * Perform OAuth2 authorization with Google server based on provided client_id and client_secret and
     * stores credential in local persistent store.
     * </p>
     *
     * @param newCredential If true try to obtain new credential (user interaction required)
     * @return Authorization credential object.
     */
public static Credential getCredential(boolean newCredential) {
    Credential credential = null;
    try {
        File tokenPath = null;
        String userdata = System.getProperty("smarthome.userdata");
        if (StringUtils.isEmpty(userdata)) {
            tokenPath = new File("etc");
        } else {
            tokenPath = new File(userdata);
        }
        File tokenFile = new File(tokenPath, TOKEN_PATH);
        FileDataStoreFactory fileDataStoreFactory = new FileDataStoreFactory(tokenFile);
        DataStore<StoredCredential> datastore = fileDataStoreFactory.getDataStore("gcal_oauth2_token");
        credential = loadCredential("openhab", datastore);
        if (credential == null && newCredential) {
            if (StringUtils.isBlank(client_id) || StringUtils.isBlank(client_secret)) {
                logger.warn("OAuth2 credentials are not provided");
                return null;
            }
            GenericUrl genericUrl = new GenericUrl("https://accounts.google.com/o/oauth2/device/code");
            Map<String, String> mapData = new HashMap<String, String>();
            mapData.put("client_id", client_id);
            mapData.put("scope", CalendarScopes.CALENDAR);
            UrlEncodedContent content = new UrlEncodedContent(mapData);
            HttpRequestFactory requestFactory = HTTP_TRANSPORT.createRequestFactory(new HttpRequestInitializer() {

                @Override
                public void initialize(HttpRequest request) {
                    request.setParser(new JsonObjectParser(JSON_FACTORY));
                }
            });
            HttpRequest postRequest = requestFactory.buildPostRequest(genericUrl, content);
            Device device = postRequest.execute().parseAs(Device.class);
            // no access token/secret specified so display the authorisation URL in the log
            logger.info("################################################################################################");
            logger.info("# Google-Integration: U S E R   I N T E R A C T I O N   R E Q U I R E D !!");
            logger.info("# 1. Open URL '{}'", device.verification_url);
            logger.info("# 2. Type provided code {} ", device.user_code);
            logger.info("# 3. Grant openHAB access to your Google calendar");
            logger.info("# 4. openHAB will automatically detect the permiossions and complete the authentication process");
            logger.info("# NOTE: You will only have {} mins before openHAB gives up waiting for the access!!!", device.expires_in);
            logger.info("################################################################################################");
            if (logger.isDebugEnabled()) {
                logger.debug("Got access code");
                logger.debug("user code : {}", device.user_code);
                logger.debug("device code : {}", device.device_code);
                logger.debug("expires in: {}", device.expires_in);
                logger.debug("interval : {}", device.interval);
                logger.debug("verification_url : {}", device.verification_url);
            }
            mapData = new HashMap<String, String>();
            mapData.put("client_id", client_id);
            mapData.put("client_secret", client_secret);
            mapData.put("code", device.device_code);
            mapData.put("grant_type", "http://oauth.net/grant_type/device/1.0");
            content = new UrlEncodedContent(mapData);
            postRequest = requestFactory.buildPostRequest(new GenericUrl("https://accounts.google.com/o/oauth2/token"), content);
            DeviceToken deviceToken;
            do {
                deviceToken = postRequest.execute().parseAs(DeviceToken.class);
                if (deviceToken.access_token != null) {
                    if (logger.isDebugEnabled()) {
                        logger.debug("Got access token");
                        logger.debug("device access token: {}", deviceToken.access_token);
                        logger.debug("device token_type: {}", deviceToken.token_type);
                        logger.debug("device refresh_token: {}", deviceToken.refresh_token);
                        logger.debug("device expires_in: {}", deviceToken.expires_in);
                    }
                    break;
                }
                logger.debug("waiting for {} seconds", device.interval);
                Thread.sleep(device.interval * 1000);
            } while (true);
            StoredCredential dataCredential = new StoredCredential();
            dataCredential.setAccessToken(deviceToken.access_token);
            dataCredential.setRefreshToken(deviceToken.refresh_token);
            dataCredential.setExpirationTimeMilliseconds((long) deviceToken.expires_in * 1000);
            datastore.set(TOKEN_STORE_USER_ID, dataCredential);
            credential = loadCredential(TOKEN_STORE_USER_ID, datastore);
        }
    } catch (Exception e) {
        logger.warn("getCredential got exception: {}", e.getMessage());
    }
    return credential;
}
Also used : HttpRequest(com.google.api.client.http.HttpRequest) Credential(com.google.api.client.auth.oauth2.Credential) StoredCredential(com.google.api.client.auth.oauth2.StoredCredential) HashMap(java.util.HashMap) HttpRequestFactory(com.google.api.client.http.HttpRequestFactory) StoredCredential(com.google.api.client.auth.oauth2.StoredCredential) UrlEncodedContent(com.google.api.client.http.UrlEncodedContent) GenericUrl(com.google.api.client.http.GenericUrl) IOException(java.io.IOException) FileDataStoreFactory(com.google.api.client.util.store.FileDataStoreFactory) JsonObjectParser(com.google.api.client.json.JsonObjectParser) HttpRequestInitializer(com.google.api.client.http.HttpRequestInitializer) File(java.io.File)

Example 4 with UrlEncodedContent

use of com.google.api.client.http.UrlEncodedContent in project java-docs-samples by GoogleCloudPlatform.

the class BuildIapRequest method getGoogleIdToken.

private static String getGoogleIdToken(String jwt) throws Exception {
    final GenericData tokenRequest = new GenericData().set("grant_type", JWT_BEARER_TOKEN_GRANT_TYPE).set("assertion", jwt);
    final UrlEncodedContent content = new UrlEncodedContent(tokenRequest);
    final HttpRequestFactory requestFactory = httpTransport.createRequestFactory();
    final HttpRequest request = requestFactory.buildPostRequest(new GenericUrl(OAUTH_TOKEN_URI), content).setParser(new JsonObjectParser(JacksonFactory.getDefaultInstance()));
    HttpResponse response;
    String idToken = null;
    response = request.execute();
    GenericData responseData = response.parseAs(GenericData.class);
    idToken = (String) responseData.get("id_token");
    return idToken;
}
Also used : HttpRequest(com.google.api.client.http.HttpRequest) HttpRequestFactory(com.google.api.client.http.HttpRequestFactory) JsonObjectParser(com.google.api.client.json.JsonObjectParser) UrlEncodedContent(com.google.api.client.http.UrlEncodedContent) HttpResponse(com.google.api.client.http.HttpResponse) GenericUrl(com.google.api.client.http.GenericUrl) GenericData(com.google.api.client.util.GenericData)

Example 5 with UrlEncodedContent

use of com.google.api.client.http.UrlEncodedContent in project google-api-java-client by google.

the class ClientLogin method authenticate.

/**
 * Authenticates based on the provided field values.
 *
 * @throws ClientLoginResponseException if the authentication response has an error code, such as
 *         for a CAPTCHA challenge.
 */
public Response authenticate() throws IOException {
    GenericUrl url = serverUrl.clone();
    url.appendRawPath("/accounts/ClientLogin");
    HttpRequest request = transport.createRequestFactory().buildPostRequest(url, new UrlEncodedContent(this));
    request.setParser(AuthKeyValueParser.INSTANCE);
    request.setContentLoggingLimit(0);
    request.setThrowExceptionOnExecuteError(false);
    HttpResponse response = request.execute();
    // check for an HTTP success response (2xx)
    if (response.isSuccessStatusCode()) {
        return response.parseAs(Response.class);
    }
    HttpResponseException.Builder builder = new HttpResponseException.Builder(response.getStatusCode(), response.getStatusMessage(), response.getHeaders());
    // On error, throw a ClientLoginResponseException with the parsed error details
    ErrorInfo details = response.parseAs(ErrorInfo.class);
    String detailString = details.toString();
    StringBuilder message = HttpResponseException.computeMessageBuffer(response);
    if (!Strings.isNullOrEmpty(detailString)) {
        message.append(StringUtils.LINE_SEPARATOR).append(detailString);
        builder.setContent(detailString);
    }
    builder.setMessage(message.toString());
    throw new ClientLoginResponseException(builder, details);
}
Also used : HttpRequest(com.google.api.client.http.HttpRequest) UrlEncodedContent(com.google.api.client.http.UrlEncodedContent) HttpResponse(com.google.api.client.http.HttpResponse) HttpResponseException(com.google.api.client.http.HttpResponseException) GenericUrl(com.google.api.client.http.GenericUrl)

Aggregations

UrlEncodedContent (com.google.api.client.http.UrlEncodedContent)8 GenericUrl (com.google.api.client.http.GenericUrl)7 HttpRequest (com.google.api.client.http.HttpRequest)7 HttpRequestFactory (com.google.api.client.http.HttpRequestFactory)5 HttpResponse (com.google.api.client.http.HttpResponse)5 JsonObjectParser (com.google.api.client.json.JsonObjectParser)5 GenericData (com.google.api.client.util.GenericData)4 IOException (java.io.IOException)2 Date (java.util.Date)2 Credential (com.google.api.client.auth.oauth2.Credential)1 StoredCredential (com.google.api.client.auth.oauth2.StoredCredential)1 EmptyContent (com.google.api.client.http.EmptyContent)1 HttpBackOffIOExceptionHandler (com.google.api.client.http.HttpBackOffIOExceptionHandler)1 HttpBackOffUnsuccessfulResponseHandler (com.google.api.client.http.HttpBackOffUnsuccessfulResponseHandler)1 BackOffRequired (com.google.api.client.http.HttpBackOffUnsuccessfulResponseHandler.BackOffRequired)1 HttpRequestInitializer (com.google.api.client.http.HttpRequestInitializer)1 HttpResponseException (com.google.api.client.http.HttpResponseException)1 HttpTransport (com.google.api.client.http.HttpTransport)1 GenericJson (com.google.api.client.json.GenericJson)1 JsonFactory (com.google.api.client.json.JsonFactory)1