Search in sources :

Example 1 with AuthorizationCodeResponseUrl

use of com.google.api.client.auth.oauth2.AuthorizationCodeResponseUrl in project che by eclipse.

the class OAuthAuthenticator method callback.

/**
     * Process callback request.
     *
     * @param requestUrl
     *         request URI. URI should contain authorization code generated by authorization server
     * @param scopes
     *         specify exactly what type of access needed. This list must be exactly the same as list passed to the method
     *         {@link #getAuthenticateUrl(URL, java.util.List)}
     * @return id of authenticated user
     * @throws OAuthAuthenticationException
     *         if authentication failed or <code>requestUrl</code> does not contain required parameters, e.g. 'code'
     */
public String callback(URL requestUrl, List<String> scopes) throws OAuthAuthenticationException {
    if (!isConfigured()) {
        throw new OAuthAuthenticationException("Authenticator is not configured");
    }
    AuthorizationCodeResponseUrl authorizationCodeResponseUrl = new AuthorizationCodeResponseUrl(requestUrl.toString());
    final String error = authorizationCodeResponseUrl.getError();
    if (error != null) {
        throw new OAuthAuthenticationException("Authentication failed: " + error);
    }
    final String code = authorizationCodeResponseUrl.getCode();
    if (code == null) {
        throw new OAuthAuthenticationException("Missing authorization code. ");
    }
    try {
        TokenResponse tokenResponse = flow.newTokenRequest(code).setRequestInitializer(request -> {
            if (request.getParser() == null) {
                request.setParser(flow.getJsonFactory().createJsonObjectParser());
            }
            request.getHeaders().setAccept(MediaType.APPLICATION_JSON);
        }).setRedirectUri(findRedirectUrl(requestUrl)).setScopes(scopes).execute();
        String userId = getUserFromUrl(authorizationCodeResponseUrl);
        if (userId == null) {
            userId = getUser(newDto(OAuthToken.class).withToken(tokenResponse.getAccessToken())).getId();
        }
        flow.createAndStoreCredential(tokenResponse, userId);
        return userId;
    } catch (IOException ioe) {
        throw new OAuthAuthenticationException(ioe.getMessage());
    }
}
Also used : HttpURLConnection(java.net.HttpURLConnection) Arrays(java.util.Arrays) URLDecoder(java.net.URLDecoder) URL(java.net.URL) LoggerFactory(org.slf4j.LoggerFactory) HashMap(java.util.HashMap) MediaType(javax.ws.rs.core.MediaType) AuthorizationCodeFlow(com.google.api.client.auth.oauth2.AuthorizationCodeFlow) TokenResponse(com.google.api.client.auth.oauth2.TokenResponse) JsonParseException(org.eclipse.che.commons.json.JsonParseException) Map(java.util.Map) GenericUrl(com.google.api.client.http.GenericUrl) JsonHelper(org.eclipse.che.commons.json.JsonHelper) Credential(com.google.api.client.auth.oauth2.Credential) URI(java.net.URI) AuthorizationCodeRequestUrl(com.google.api.client.auth.oauth2.AuthorizationCodeRequestUrl) NetHttpTransport(com.google.api.client.http.javanet.NetHttpTransport) Logger(org.slf4j.Logger) User(org.eclipse.che.security.oauth.shared.User) JacksonFactory(com.google.api.client.json.jackson2.JacksonFactory) BearerToken(com.google.api.client.auth.oauth2.BearerToken) OAuthToken(org.eclipse.che.api.auth.shared.dto.OAuthToken) DtoFactory.newDto(org.eclipse.che.dto.server.DtoFactory.newDto) IOException(java.io.IOException) List(java.util.List) AuthorizationCodeResponseUrl(com.google.api.client.auth.oauth2.AuthorizationCodeResponseUrl) ClientParametersAuthentication(com.google.api.client.auth.oauth2.ClientParametersAuthentication) MemoryDataStoreFactory(com.google.api.client.util.store.MemoryDataStoreFactory) Pattern(java.util.regex.Pattern) Collections(java.util.Collections) InputStream(java.io.InputStream) TokenResponse(com.google.api.client.auth.oauth2.TokenResponse) AuthorizationCodeResponseUrl(com.google.api.client.auth.oauth2.AuthorizationCodeResponseUrl) IOException(java.io.IOException)

Example 2 with AuthorizationCodeResponseUrl

use of com.google.api.client.auth.oauth2.AuthorizationCodeResponseUrl in project OpenRefine by OpenRefine.

the class GoogleAPIExtension method getTokenFromCode.

public static String getTokenFromCode(ButterflyModule module, HttpServletRequest request) throws IOException {
    String redirectUrl = makeRedirectUrl(module, request);
    StringBuffer fullUrlBuf = request.getRequestURL();
    if (request.getQueryString() != null) {
        fullUrlBuf.append('?').append(request.getQueryString());
    }
    AuthorizationCodeResponseUrl authResponse = new AuthorizationCodeResponseUrl(fullUrlBuf.toString());
    // check for user-denied error
    if (authResponse.getError() != null) {
    // authorization denied...
    } else {
        // request access token using authResponse.getCode()...
        String code = authResponse.getCode();
        GoogleTokenResponse response = new GoogleAuthorizationCodeTokenRequest(HTTP_TRANSPORT, JSON_FACTORY, CLIENT_ID, CLIENT_SECRET, code, redirectUrl).execute();
        String tokenAndExpiresInSeconds = response.getAccessToken() + "," + response.getExpiresInSeconds();
        return tokenAndExpiresInSeconds;
    }
    return null;
}
Also used : GoogleAuthorizationCodeTokenRequest(com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeTokenRequest) AuthorizationCodeResponseUrl(com.google.api.client.auth.oauth2.AuthorizationCodeResponseUrl) GoogleTokenResponse(com.google.api.client.googleapis.auth.oauth2.GoogleTokenResponse)

Example 3 with AuthorizationCodeResponseUrl

use of com.google.api.client.auth.oauth2.AuthorizationCodeResponseUrl in project OpenRefine by OpenRefine.

the class GDataExtension method getTokenFromCode.

public static String getTokenFromCode(ButterflyModule module, HttpServletRequest request) throws MalformedURLException {
    String redirectUrl = makeRedirectUrl(module, request);
    StringBuffer fullUrlBuf = request.getRequestURL();
    if (request.getQueryString() != null) {
        fullUrlBuf.append('?').append(request.getQueryString());
    }
    AuthorizationCodeResponseUrl authResponse = new AuthorizationCodeResponseUrl(fullUrlBuf.toString());
    // check for user-denied error
    if (authResponse.getError() != null) {
    // authorization denied...
    } else {
        // request access token using authResponse.getCode()...
        String code = authResponse.getCode();
        try {
            GoogleTokenResponse response = new GoogleAuthorizationCodeTokenRequest(HTTP_TRANSPORT, JSON_FACTORY, CLIENT_ID, CLIENT_SECRET, code, redirectUrl).execute();
            String token = response.getAccessToken();
            return token;
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    return null;
}
Also used : GoogleAuthorizationCodeTokenRequest(com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeTokenRequest) AuthorizationCodeResponseUrl(com.google.api.client.auth.oauth2.AuthorizationCodeResponseUrl) GoogleTokenResponse(com.google.api.client.googleapis.auth.oauth2.GoogleTokenResponse) IOException(java.io.IOException)

Example 4 with AuthorizationCodeResponseUrl

use of com.google.api.client.auth.oauth2.AuthorizationCodeResponseUrl in project data-transfer-project by google.

the class Oauth2CallbackHandler method handleExchange.

private String handleExchange(HttpExchange exchange) throws IOException {
    String redirect = "/error";
    try {
        Headers requestHeaders = exchange.getRequestHeaders();
        String requestURL = ReferenceApiUtils.createURL(requestHeaders.getFirst(HttpHeaders.HOST), exchange.getRequestURI().toString(), IS_LOCAL);
        AuthorizationCodeResponseUrl authResponse = new AuthorizationCodeResponseUrl(requestURL);
        // check for user-denied error
        if (authResponse.getError() != null) {
            logger.warn("Authorization DENIED: {} Redirecting to /error", authResponse.getError());
            return redirect;
        }
        // retrieve cookie from exchange
        Map<String, HttpCookie> httpCookies = ReferenceApiUtils.getCookies(requestHeaders);
        HttpCookie encodedIdCookie = httpCookies.get(JsonKeys.ID_COOKIE_KEY);
        Preconditions.checkArgument(encodedIdCookie != null && !Strings.isNullOrEmpty(encodedIdCookie.getValue()), "Encoded Id cookie required");
        UUID jobId = ReferenceApiUtils.decodeJobId(encodedIdCookie.getValue());
        logger.debug("State token: {}", authResponse.getState());
        // TODO(#258): Check job ID in state token, was broken during local demo
        // UUID jobIdFromState = ReferenceApiUtils.decodeJobId(authResponse.getState());
        // // TODO: Remove sanity check
        // Preconditions.checkState(
        // jobIdFromState.equals(jobId),
        // "Job id in cookie [%s] and request [%s] should match",
        // jobId,
        // jobIdFromState);
        PortabilityJob job = store.findJob(jobId);
        Preconditions.checkNotNull(job, "existing job not found for jobId: %s", jobId);
        // TODO: Determine service from job or from authUrl path?
        AuthMode authMode = ReferenceApiUtils.getAuthMode(exchange.getRequestHeaders());
        String service = (authMode == AuthMode.EXPORT) ? job.exportService() : job.importService();
        Preconditions.checkState(!Strings.isNullOrEmpty(service), "service not found, service: %s authMode: %s, jobId: %s", service, authMode, jobId.toString());
        AuthDataGenerator generator = registry.getAuthDataGenerator(service, job.transferDataType(), authMode);
        Preconditions.checkNotNull(generator, "Generator not found for type: %s, service: %s", job.transferDataType(), service);
        // Obtain the session key for this job
        String encodedSessionKey = job.jobAuthorization().sessionSecretKey();
        SecretKey key = symmetricKeyGenerator.parse(BaseEncoding.base64Url().decode(encodedSessionKey));
        // Retrieve initial auth data, if it existed
        AuthData initialAuthData = null;
        String encryptedInitialAuthData = (authMode == AuthMode.EXPORT) ? job.jobAuthorization().encryptedInitialExportAuthData() : job.jobAuthorization().encryptedInitialImportAuthData();
        if (encryptedInitialAuthData != null) {
            // Retrieve and parse the session key from the job
            // Decrypt and deserialize the object
            String serialized = DecrypterFactory.create(key).decrypt(encryptedInitialAuthData);
            initialAuthData = objectMapper.readValue(serialized, AuthData.class);
        }
        // TODO: Use UUID instead of UUID.toString()
        // Generate auth data
        AuthData authData = generator.generateAuthData(baseApiUrl, authResponse.getCode(), jobId.toString(), initialAuthData, null);
        Preconditions.checkNotNull(authData, "Auth data should not be null");
        // Serialize and encrypt the auth data
        String serialized = objectMapper.writeValueAsString(authData);
        String encryptedAuthData = EncrypterFactory.create(key).encrypt(serialized);
        // Set new cookie
        ReferenceApiUtils.setCookie(exchange.getResponseHeaders(), encryptedAuthData, authMode);
        redirect = baseUrl + ((authMode == AuthMode.EXPORT) ? FrontendConstantUrls.URL_NEXT_PAGE : FrontendConstantUrls.URL_COPY_PAGE);
    } catch (Exception e) {
        logger.error("Error handling request: {}", e);
        throw e;
    }
    return redirect;
}
Also used : PortabilityJob(org.dataportabilityproject.spi.cloud.types.PortabilityJob) AuthDataGenerator(org.dataportabilityproject.spi.gateway.auth.AuthDataGenerator) SecretKey(javax.crypto.SecretKey) AuthData(org.dataportabilityproject.types.transfer.auth.AuthData) HttpHeaders(com.google.common.net.HttpHeaders) Headers(com.sun.net.httpserver.Headers) AuthorizationCodeResponseUrl(com.google.api.client.auth.oauth2.AuthorizationCodeResponseUrl) UUID(java.util.UUID) HttpCookie(java.net.HttpCookie) AuthMode(org.dataportabilityproject.spi.gateway.auth.AuthServiceProviderRegistry.AuthMode) IOException(java.io.IOException)

Aggregations

AuthorizationCodeResponseUrl (com.google.api.client.auth.oauth2.AuthorizationCodeResponseUrl)4 IOException (java.io.IOException)3 GoogleAuthorizationCodeTokenRequest (com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeTokenRequest)2 GoogleTokenResponse (com.google.api.client.googleapis.auth.oauth2.GoogleTokenResponse)2 AuthorizationCodeFlow (com.google.api.client.auth.oauth2.AuthorizationCodeFlow)1 AuthorizationCodeRequestUrl (com.google.api.client.auth.oauth2.AuthorizationCodeRequestUrl)1 BearerToken (com.google.api.client.auth.oauth2.BearerToken)1 ClientParametersAuthentication (com.google.api.client.auth.oauth2.ClientParametersAuthentication)1 Credential (com.google.api.client.auth.oauth2.Credential)1 TokenResponse (com.google.api.client.auth.oauth2.TokenResponse)1 GenericUrl (com.google.api.client.http.GenericUrl)1 NetHttpTransport (com.google.api.client.http.javanet.NetHttpTransport)1 JacksonFactory (com.google.api.client.json.jackson2.JacksonFactory)1 MemoryDataStoreFactory (com.google.api.client.util.store.MemoryDataStoreFactory)1 HttpHeaders (com.google.common.net.HttpHeaders)1 Headers (com.sun.net.httpserver.Headers)1 InputStream (java.io.InputStream)1 HttpCookie (java.net.HttpCookie)1 HttpURLConnection (java.net.HttpURLConnection)1 URI (java.net.URI)1