Search in sources :

Example 1 with TokenResponse

use of com.microsoft.identity.common.internal.providers.oauth2.TokenResponse in project dockstore by dockstore.

the class Hoverfly method getFakeTokenResponse.

private static TokenResponse getFakeTokenResponse(String suffix) {
    TokenResponse fakeTokenResponse = new TokenResponse();
    fakeTokenResponse.setAccessToken(getFakeAccessToken(suffix));
    fakeTokenResponse.setExpiresInSeconds(9001L);
    fakeTokenResponse.setRefreshToken("fakeRefreshToken" + suffix);
    return fakeTokenResponse;
}
Also used : TokenResponse(com.google.api.client.auth.oauth2.TokenResponse)

Example 2 with TokenResponse

use of com.microsoft.identity.common.internal.providers.oauth2.TokenResponse in project dockstore by dockstore.

the class TokenResource method addGitlabToken.

@GET
@Timed
@UnitOfWork
@Path("/gitlab.com")
@JsonView(TokenViews.User.class)
@Operation(operationId = "addGitlabToken", description = "Add a new gitlab.com token.", security = @SecurityRequirement(name = OPENAPI_JWT_SECURITY_DEFINITION_NAME))
@ApiOperation(value = "Add a new gitlab.com token.", authorizations = { @Authorization(value = JWT_SECURITY_DEFINITION_NAME) }, notes = "This is used as part of the OAuth 2 web flow. Once a user has approved permissions for CollaboratoryTheir browser will load the redirect URI which should resolve here", response = Token.class)
public Token addGitlabToken(@ApiParam(hidden = true) @Parameter(hidden = true, name = "user") @Auth User user, @QueryParam("code") String code) {
    final AuthorizationCodeFlow flow = new AuthorizationCodeFlow.Builder(BearerToken.authorizationHeaderAccessMethod(), HTTP_TRANSPORT, JSON_FACTORY, new GenericUrl(GITLAB_URL + "oauth/token"), new ClientParametersAuthentication(gitlabClientID, gitlabClientSecret), gitlabClientID, GITLAB_URL + "oauth/authorize").build();
    LOG.info("About to try and grab access token");
    String accessToken;
    try {
        TokenResponse tokenResponse = flow.newTokenRequest(code).setRequestInitializer(request -> request.getHeaders().setAccept("application/json")).setGrantType("authorization_code").setRedirectUri(gitlabRedirectUri).execute();
        accessToken = tokenResponse.getAccessToken();
    } catch (IOException e) {
        LOG.error("Retrieving accessToken was unsuccessful");
        throw new CustomWebApplicationException("Could not retrieve gitlab.com token based on code", HttpStatus.SC_BAD_REQUEST);
    }
    String url = GITLAB_URL + "api/v3/user";
    Optional<String> asString = ResourceUtilities.asString(url, accessToken, client);
    String username = getUserName(url, asString);
    if (user != null) {
        Token token = new Token();
        token.setTokenSource(TokenType.GITLAB_COM);
        token.setContent(accessToken);
        token.setUserId(user.getId());
        if (username != null) {
            token.setUsername(username);
        } else {
            LOG.info("Gitlab.com tokenusername is null, did not create token");
            throw new CustomWebApplicationException("Username not found from resource call " + url, HttpStatus.SC_CONFLICT);
        }
        checkIfAccountHasBeenLinked(token, TokenType.GITLAB_COM);
        long create = tokenDAO.create(token);
        LOG.info("Gitlab token created for {}", user.getUsername());
        return tokenDAO.findById(create);
    } else {
        LOG.info("Could not find user");
        throw new CustomWebApplicationException("User not found", HttpStatus.SC_CONFLICT);
    }
}
Also used : JsonObject(com.google.gson.JsonObject) JsonView(com.fasterxml.jackson.annotation.JsonView) Produces(javax.ws.rs.Produces) URL(java.net.URL) Date(java.util.Date) Path(javax.ws.rs.Path) LoggerFactory(org.slf4j.LoggerFactory) CustomWebApplicationException(io.dockstore.webservice.CustomWebApplicationException) ApiParam(io.swagger.annotations.ApiParam) HttpStatus(org.apache.http.HttpStatus) DockstoreWebserviceConfiguration(io.dockstore.webservice.DockstoreWebserviceConfiguration) GitHubBuilder(org.kohsuke.github.GitHubBuilder) SecureRandom(java.security.SecureRandom) SourceCodeRepoFactory(io.dockstore.webservice.helpers.SourceCodeRepoFactory) ApiOperation(io.swagger.annotations.ApiOperation) MediaType(javax.ws.rs.core.MediaType) QueryParam(javax.ws.rs.QueryParam) TokenScope(io.dockstore.webservice.core.TokenScope) Gson(com.google.gson.Gson) Map(java.util.Map) GenericUrl(com.google.api.client.http.GenericUrl) TokenType(io.dockstore.webservice.core.TokenType) OPENAPI_JWT_SECURITY_DEFINITION_NAME(io.dockstore.webservice.resources.ResourceConstants.OPENAPI_JWT_SECURITY_DEFINITION_NAME) User(io.dockstore.webservice.core.User) GitHub(org.kohsuke.github.GitHub) DELETE(javax.ws.rs.DELETE) SecurityRequirement(io.swagger.v3.oas.annotations.security.SecurityRequirement) TokenViews(io.dockstore.webservice.core.TokenViews) GitHubHelper(io.dockstore.webservice.helpers.GitHubHelper) HttpTransport(com.google.api.client.http.HttpTransport) Instant(java.time.Instant) Userinfoplus(com.google.api.services.oauth2.model.Userinfoplus) GoogleHelper(io.dockstore.webservice.helpers.GoogleHelper) Parameter(io.swagger.v3.oas.annotations.Parameter) Timed(com.codahale.metrics.annotation.Timed) List(java.util.List) Response(javax.ws.rs.core.Response) ClientParametersAuthentication(com.google.api.client.auth.oauth2.ClientParametersAuthentication) UnitOfWork(io.dropwizard.hibernate.UnitOfWork) Tag(io.swagger.v3.oas.annotations.tags.Tag) Optional(java.util.Optional) TOSVersion(io.dockstore.webservice.core.TOSVersion) PathParam(javax.ws.rs.PathParam) CachingAuthenticator(io.dropwizard.auth.CachingAuthenticator) GET(javax.ws.rs.GET) Auth(io.dropwizard.auth.Auth) HashMap(java.util.HashMap) Hashing(com.google.common.hash.Hashing) JWT_SECURITY_DEFINITION_NAME(io.dockstore.webservice.Constants.JWT_SECURITY_DEFINITION_NAME) ApiResponses(io.swagger.annotations.ApiResponses) MessageFormat(java.text.MessageFormat) JsonElement(com.google.gson.JsonElement) JacksonFactory(com.google.api.client.json.jackson.JacksonFactory) Operation(io.swagger.v3.oas.annotations.Operation) HttpClient(org.apache.http.client.HttpClient) AuthorizationCodeFlow(com.google.api.client.auth.oauth2.AuthorizationCodeFlow) TokenResponse(com.google.api.client.auth.oauth2.TokenResponse) Api(io.swagger.annotations.Api) Token(io.dockstore.webservice.core.Token) UserDAO(io.dockstore.webservice.jdbi.UserDAO) NetHttpTransport(com.google.api.client.http.javanet.NetHttpTransport) Charsets(com.google.common.base.Charsets) POST(javax.ws.rs.POST) Logger(org.slf4j.Logger) DeletedUserHelper(io.dockstore.webservice.helpers.DeletedUserHelper) MalformedURLException(java.net.MalformedURLException) BaseEncoding(com.google.common.io.BaseEncoding) BearerToken(com.google.api.client.auth.oauth2.BearerToken) DeletedUsernameDAO(io.dockstore.webservice.jdbi.DeletedUsernameDAO) IOException(java.io.IOException) PrivacyPolicyVersion(io.dockstore.webservice.core.PrivacyPolicyVersion) JsonFactory(com.google.api.client.json.JsonFactory) ApiResponse(io.swagger.annotations.ApiResponse) GitHubSourceCodeRepo(io.dockstore.webservice.helpers.GitHubSourceCodeRepo) TokenDAO(io.dockstore.webservice.jdbi.TokenDAO) Collections(java.util.Collections) Authorization(io.swagger.annotations.Authorization) ClientParametersAuthentication(com.google.api.client.auth.oauth2.ClientParametersAuthentication) TokenResponse(com.google.api.client.auth.oauth2.TokenResponse) CustomWebApplicationException(io.dockstore.webservice.CustomWebApplicationException) Token(io.dockstore.webservice.core.Token) BearerToken(com.google.api.client.auth.oauth2.BearerToken) GenericUrl(com.google.api.client.http.GenericUrl) IOException(java.io.IOException) AuthorizationCodeFlow(com.google.api.client.auth.oauth2.AuthorizationCodeFlow) Path(javax.ws.rs.Path) UnitOfWork(io.dropwizard.hibernate.UnitOfWork) Timed(com.codahale.metrics.annotation.Timed) GET(javax.ws.rs.GET) ApiOperation(io.swagger.annotations.ApiOperation) JsonView(com.fasterxml.jackson.annotation.JsonView) ApiOperation(io.swagger.annotations.ApiOperation) Operation(io.swagger.v3.oas.annotations.Operation)

Example 3 with TokenResponse

use of com.microsoft.identity.common.internal.providers.oauth2.TokenResponse in project dockstore by dockstore.

the class TokenResource method addBitbucketToken.

@GET
@Timed
@UnitOfWork
@Path("/bitbucket.org")
@JsonView(TokenViews.User.class)
@Operation(operationId = "addBitbucketToken", description = "Add a new bitbucket.org token, used by quay.io redirect.", security = @SecurityRequirement(name = OPENAPI_JWT_SECURITY_DEFINITION_NAME))
@ApiOperation(value = "Add a new bitbucket.org token, used by quay.io redirect.", authorizations = { @Authorization(value = JWT_SECURITY_DEFINITION_NAME) }, notes = "This is used as part of the OAuth 2 web flow. " + "Once a user has approved permissions for Collaboratory" + "Their browser will load the redirect URI which should resolve here", response = Token.class)
public Token addBitbucketToken(@ApiParam(hidden = true) @Parameter(hidden = true, name = "user") @Auth User user, @QueryParam("code") String code) {
    if (code.isEmpty()) {
        throw new CustomWebApplicationException("Please provide an access code", HttpStatus.SC_BAD_REQUEST);
    }
    final AuthorizationCodeFlow flow = new AuthorizationCodeFlow.Builder(BearerToken.authorizationHeaderAccessMethod(), HTTP_TRANSPORT, JSON_FACTORY, new GenericUrl(BITBUCKET_URL + "site/oauth2/access_token"), new ClientParametersAuthentication(bitbucketClientID, bitbucketClientSecret), bitbucketClientID, "https://bitbucket.org/site/oauth2/authorize").build();
    String accessToken;
    String refreshToken;
    try {
        TokenResponse tokenResponse = flow.newTokenRequest(code).setScopes(Collections.singletonList("user:email")).setRequestInitializer(request -> request.getHeaders().setAccept("application/json")).execute();
        accessToken = tokenResponse.getAccessToken();
        refreshToken = tokenResponse.getRefreshToken();
    } catch (IOException e) {
        LOG.error("Retrieving accessToken was unsuccessful");
        throw new CustomWebApplicationException("Could not retrieve bitbucket.org token based on code", HttpStatus.SC_BAD_REQUEST);
    }
    String url = BITBUCKET_URL + "api/2.0/user";
    Optional<String> asString2 = ResourceUtilities.asString(url, accessToken, client);
    String username = getUserName(url, asString2);
    if (user != null) {
        Token token = new Token();
        token.setTokenSource(TokenType.BITBUCKET_ORG);
        token.setContent(accessToken);
        token.setRefreshToken(refreshToken);
        token.setUserId(user.getId());
        if (username != null) {
            token.setUsername(username);
        } else {
            LOG.info("Bitbucket.org token username is null, did not create token");
            throw new CustomWebApplicationException("Username not found from resource call " + url, HttpStatus.SC_CONFLICT);
        }
        checkIfAccountHasBeenLinked(token, TokenType.BITBUCKET_ORG);
        long create = tokenDAO.create(token);
        LOG.info("Bitbucket token created for {}", user.getUsername());
        return tokenDAO.findById(create);
    } else {
        LOG.info("Could not find user");
        throw new CustomWebApplicationException("User not found", HttpStatus.SC_CONFLICT);
    }
}
Also used : JsonObject(com.google.gson.JsonObject) JsonView(com.fasterxml.jackson.annotation.JsonView) Produces(javax.ws.rs.Produces) URL(java.net.URL) Date(java.util.Date) Path(javax.ws.rs.Path) LoggerFactory(org.slf4j.LoggerFactory) CustomWebApplicationException(io.dockstore.webservice.CustomWebApplicationException) ApiParam(io.swagger.annotations.ApiParam) HttpStatus(org.apache.http.HttpStatus) DockstoreWebserviceConfiguration(io.dockstore.webservice.DockstoreWebserviceConfiguration) GitHubBuilder(org.kohsuke.github.GitHubBuilder) SecureRandom(java.security.SecureRandom) SourceCodeRepoFactory(io.dockstore.webservice.helpers.SourceCodeRepoFactory) ApiOperation(io.swagger.annotations.ApiOperation) MediaType(javax.ws.rs.core.MediaType) QueryParam(javax.ws.rs.QueryParam) TokenScope(io.dockstore.webservice.core.TokenScope) Gson(com.google.gson.Gson) Map(java.util.Map) GenericUrl(com.google.api.client.http.GenericUrl) TokenType(io.dockstore.webservice.core.TokenType) OPENAPI_JWT_SECURITY_DEFINITION_NAME(io.dockstore.webservice.resources.ResourceConstants.OPENAPI_JWT_SECURITY_DEFINITION_NAME) User(io.dockstore.webservice.core.User) GitHub(org.kohsuke.github.GitHub) DELETE(javax.ws.rs.DELETE) SecurityRequirement(io.swagger.v3.oas.annotations.security.SecurityRequirement) TokenViews(io.dockstore.webservice.core.TokenViews) GitHubHelper(io.dockstore.webservice.helpers.GitHubHelper) HttpTransport(com.google.api.client.http.HttpTransport) Instant(java.time.Instant) Userinfoplus(com.google.api.services.oauth2.model.Userinfoplus) GoogleHelper(io.dockstore.webservice.helpers.GoogleHelper) Parameter(io.swagger.v3.oas.annotations.Parameter) Timed(com.codahale.metrics.annotation.Timed) List(java.util.List) Response(javax.ws.rs.core.Response) ClientParametersAuthentication(com.google.api.client.auth.oauth2.ClientParametersAuthentication) UnitOfWork(io.dropwizard.hibernate.UnitOfWork) Tag(io.swagger.v3.oas.annotations.tags.Tag) Optional(java.util.Optional) TOSVersion(io.dockstore.webservice.core.TOSVersion) PathParam(javax.ws.rs.PathParam) CachingAuthenticator(io.dropwizard.auth.CachingAuthenticator) GET(javax.ws.rs.GET) Auth(io.dropwizard.auth.Auth) HashMap(java.util.HashMap) Hashing(com.google.common.hash.Hashing) JWT_SECURITY_DEFINITION_NAME(io.dockstore.webservice.Constants.JWT_SECURITY_DEFINITION_NAME) ApiResponses(io.swagger.annotations.ApiResponses) MessageFormat(java.text.MessageFormat) JsonElement(com.google.gson.JsonElement) JacksonFactory(com.google.api.client.json.jackson.JacksonFactory) Operation(io.swagger.v3.oas.annotations.Operation) HttpClient(org.apache.http.client.HttpClient) AuthorizationCodeFlow(com.google.api.client.auth.oauth2.AuthorizationCodeFlow) TokenResponse(com.google.api.client.auth.oauth2.TokenResponse) Api(io.swagger.annotations.Api) Token(io.dockstore.webservice.core.Token) UserDAO(io.dockstore.webservice.jdbi.UserDAO) NetHttpTransport(com.google.api.client.http.javanet.NetHttpTransport) Charsets(com.google.common.base.Charsets) POST(javax.ws.rs.POST) Logger(org.slf4j.Logger) DeletedUserHelper(io.dockstore.webservice.helpers.DeletedUserHelper) MalformedURLException(java.net.MalformedURLException) BaseEncoding(com.google.common.io.BaseEncoding) BearerToken(com.google.api.client.auth.oauth2.BearerToken) DeletedUsernameDAO(io.dockstore.webservice.jdbi.DeletedUsernameDAO) IOException(java.io.IOException) PrivacyPolicyVersion(io.dockstore.webservice.core.PrivacyPolicyVersion) JsonFactory(com.google.api.client.json.JsonFactory) ApiResponse(io.swagger.annotations.ApiResponse) GitHubSourceCodeRepo(io.dockstore.webservice.helpers.GitHubSourceCodeRepo) TokenDAO(io.dockstore.webservice.jdbi.TokenDAO) Collections(java.util.Collections) Authorization(io.swagger.annotations.Authorization) ClientParametersAuthentication(com.google.api.client.auth.oauth2.ClientParametersAuthentication) TokenResponse(com.google.api.client.auth.oauth2.TokenResponse) CustomWebApplicationException(io.dockstore.webservice.CustomWebApplicationException) Token(io.dockstore.webservice.core.Token) BearerToken(com.google.api.client.auth.oauth2.BearerToken) GenericUrl(com.google.api.client.http.GenericUrl) IOException(java.io.IOException) AuthorizationCodeFlow(com.google.api.client.auth.oauth2.AuthorizationCodeFlow) Path(javax.ws.rs.Path) UnitOfWork(io.dropwizard.hibernate.UnitOfWork) Timed(com.codahale.metrics.annotation.Timed) GET(javax.ws.rs.GET) ApiOperation(io.swagger.annotations.ApiOperation) JsonView(com.fasterxml.jackson.annotation.JsonView) ApiOperation(io.swagger.annotations.ApiOperation) Operation(io.swagger.v3.oas.annotations.Operation)

Example 4 with TokenResponse

use of com.microsoft.identity.common.internal.providers.oauth2.TokenResponse in project che-server by eclipse-che.

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 = EnvironmentContext.getCurrent().getSubject().getUserId();
        }
        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) EnvironmentContext(org.eclipse.che.commons.env.EnvironmentContext) AuthorizationCodeFlow(com.google.api.client.auth.oauth2.AuthorizationCodeFlow) TokenResponse(com.google.api.client.auth.oauth2.TokenResponse) Map(java.util.Map) JsonParseException(org.eclipse.che.commons.json.JsonParseException) 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) OAuthTokenProvider(org.eclipse.che.security.oauth.shared.OAuthTokenProvider) 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) MediaType(jakarta.ws.rs.core.MediaType) 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 5 with TokenResponse

use of com.microsoft.identity.common.internal.providers.oauth2.TokenResponse in project cyberduck by iterate-ch.

the class SDSSession method connect.

@Override
protected SDSApiClient connect(final Proxy proxy, final HostKeyCallback key, final LoginCallback prompt, final CancelCallback cancel) throws BackgroundException {
    final HttpClientBuilder configuration = builder.build(proxy, this, prompt);
    if (preferences.getBoolean("sds.oauth.migrate.enable")) {
        if (host.getProtocol().isDeprecated()) {
            final Credentials credentials = host.getCredentials();
            if (!host.getCredentials().validate(host.getProtocol(), new LoginOptions(host.getProtocol()))) {
                log.warn(String.format("Skip migration with missing credentials for %s", host));
            } else {
                if (log.isDebugEnabled()) {
                    log.debug(String.format("Attempt migration to OAuth flow for %s", host));
                }
                try {
                    // Search for installed connection profile using OAuth authorization method
                    for (Protocol oauth : ProtocolFactory.get().find(new OAuthFinderPredicate(host.getProtocol().getIdentifier()))) {
                        // Run password flow to attempt to migrate to OAuth
                        final TokenResponse response = new PasswordTokenRequest(new ApacheHttpTransport(builder.build(proxy, this, prompt).build()), new GsonFactory(), new GenericUrl(Scheme.isURL(oauth.getOAuthTokenUrl()) ? oauth.getOAuthTokenUrl() : new HostUrlProvider().withUsername(false).withPath(true).get(oauth.getScheme(), host.getPort(), null, host.getHostname(), oauth.getOAuthTokenUrl())), host.getCredentials().getUsername(), host.getCredentials().getPassword()).setClientAuthentication(new BasicAuthentication(oauth.getOAuthClientId(), oauth.getOAuthClientSecret())).setRequestInitializer(new UserAgentHttpRequestInitializer(new PreferencesUseragentProvider())).execute();
                        final long expiryInMilliseconds = System.currentTimeMillis() + response.getExpiresInSeconds() * 1000;
                        credentials.setOauth(new OAuthTokens(response.getAccessToken(), response.getRefreshToken(), expiryInMilliseconds));
                        credentials.setSaved(true);
                        log.warn(String.format("Switch bookmark %s to protocol %s", host, oauth));
                        host.setProtocol(oauth);
                        break;
                    }
                } catch (IOException e) {
                    log.warn(String.format("Failure %s running password flow to migrate to OAuth", e));
                }
            }
        }
    }
    switch(SDSProtocol.Authorization.valueOf(host.getProtocol().getAuthorization())) {
        case oauth:
        case password:
            authorizationService = new OAuth2RequestInterceptor(builder.build(proxy, this, prompt).addInterceptorLast(new HttpRequestInterceptor() {

                @Override
                public void process(final HttpRequest request, final HttpContext context) {
                    if (request instanceof HttpRequestWrapper) {
                        final HttpRequestWrapper wrapper = (HttpRequestWrapper) request;
                        if (null != wrapper.getTarget()) {
                            if (StringUtils.equals(wrapper.getTarget().getHostName(), host.getHostname())) {
                                request.addHeader(HttpHeaders.AUTHORIZATION, String.format("Basic %s", Base64.encodeToString(String.format("%s:%s", host.getProtocol().getOAuthClientId(), host.getProtocol().getOAuthClientSecret()).getBytes(StandardCharsets.UTF_8), false)));
                            }
                        }
                    }
                }
            }).build(), host) {

                @Override
                public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException {
                    if (request instanceof HttpRequestWrapper) {
                        final HttpRequestWrapper wrapper = (HttpRequestWrapper) request;
                        if (null != wrapper.getTarget()) {
                            if (StringUtils.equals(wrapper.getTarget().getHostName(), host.getHostname())) {
                                super.process(request, context);
                            }
                        }
                    }
                }
            }.withRedirectUri(CYBERDUCK_REDIRECT_URI.equals(host.getProtocol().getOAuthRedirectUrl()) ? host.getProtocol().getOAuthRedirectUrl() : Scheme.isURL(host.getProtocol().getOAuthRedirectUrl()) ? host.getProtocol().getOAuthRedirectUrl() : new HostUrlProvider().withUsername(false).withPath(true).get(host.getProtocol().getScheme(), host.getPort(), null, host.getHostname(), host.getProtocol().getOAuthRedirectUrl()));
            try {
                authorizationService.withParameter("user_agent_info", Base64.encodeToString(InetAddress.getLocalHost().getHostName().getBytes(StandardCharsets.UTF_8), false));
            } catch (UnknownHostException e) {
                throw new DefaultIOExceptionMappingService().map(e);
            }
            configuration.setServiceUnavailableRetryStrategy(new OAuth2ErrorResponseInterceptor(host, authorizationService, prompt));
            configuration.addInterceptorLast(authorizationService);
            configuration.addInterceptorLast(new HttpRequestInterceptor() {

                @Override
                public void process(final HttpRequest request, final HttpContext context) {
                    request.removeHeaders(SDSSession.SDS_AUTH_TOKEN_HEADER);
                }
            });
            break;
        default:
            retryHandler = new SDSErrorResponseInterceptor(this, nodeid);
            configuration.setServiceUnavailableRetryStrategy(retryHandler);
            configuration.addInterceptorLast(retryHandler);
            break;
    }
    final CloseableHttpClient apache = configuration.build();
    final SDSApiClient client = new SDSApiClient(apache);
    client.setBasePath(new HostUrlProvider().withUsername(false).withPath(true).get(host.getProtocol().getScheme(), host.getPort(), null, host.getHostname(), host.getProtocol().getContext()));
    client.setHttpClient(ClientBuilder.newClient(new ClientConfig().register(new InputStreamProvider()).register(MultiPartFeature.class).register(new JSON()).register(JacksonFeature.class).connectorProvider(new HttpComponentsProvider(apache))));
    final int timeout = preferences.getInteger("connection.timeout.seconds") * 1000;
    client.setConnectTimeout(timeout);
    client.setReadTimeout(timeout);
    client.setUserAgent(new PreferencesUseragentProvider().get());
    return client;
}
Also used : UserAgentHttpRequestInitializer(ch.cyberduck.core.http.UserAgentHttpRequestInitializer) JSON(ch.cyberduck.core.sds.io.swagger.client.JSON) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) GenericUrl(com.google.api.client.http.GenericUrl) JacksonFeature(org.glassfish.jersey.jackson.JacksonFeature) OAuth2RequestInterceptor(ch.cyberduck.core.oauth.OAuth2RequestInterceptor) HttpRequestWrapper(org.apache.http.client.methods.HttpRequestWrapper) ClientConfig(org.glassfish.jersey.client.ClientConfig) HttpRequest(org.apache.http.HttpRequest) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) GsonFactory(com.google.api.client.json.gson.GsonFactory) UnknownHostException(java.net.UnknownHostException) InputStreamProvider(org.glassfish.jersey.message.internal.InputStreamProvider) HttpContext(org.apache.http.protocol.HttpContext) OAuth2ErrorResponseInterceptor(ch.cyberduck.core.oauth.OAuth2ErrorResponseInterceptor) IOException(java.io.IOException) TokenResponse(com.google.api.client.auth.oauth2.TokenResponse) MultiPartFeature(org.glassfish.jersey.media.multipart.MultiPartFeature) HttpRequestInterceptor(org.apache.http.HttpRequestInterceptor) BasicAuthentication(com.google.api.client.http.BasicAuthentication) PasswordTokenRequest(com.google.api.client.auth.oauth2.PasswordTokenRequest) ApacheHttpTransport(com.google.api.client.http.apache.v2.ApacheHttpTransport) HttpComponentsProvider(ch.cyberduck.core.jersey.HttpComponentsProvider)

Aggregations

TokenResponse (com.google.api.client.auth.oauth2.TokenResponse)48 IOException (java.io.IOException)23 GenericUrl (com.google.api.client.http.GenericUrl)22 Credential (com.google.api.client.auth.oauth2.Credential)20 ClientParametersAuthentication (com.google.api.client.auth.oauth2.ClientParametersAuthentication)16 AuthorizationCodeFlow (com.google.api.client.auth.oauth2.AuthorizationCodeFlow)15 Map (java.util.Map)13 NetHttpTransport (com.google.api.client.http.javanet.NetHttpTransport)12 TokenResponse (com.microsoft.identity.common.internal.providers.oauth2.TokenResponse)11 BearerToken (com.google.api.client.auth.oauth2.BearerToken)9 TokenResult (com.microsoft.identity.common.internal.providers.oauth2.TokenResult)8 Logger (org.slf4j.Logger)8 LoggerFactory (org.slf4j.LoggerFactory)8 Test (org.junit.Test)7 URL (java.net.URL)6 HashMap (java.util.HashMap)6 List (java.util.List)6 Timed (com.codahale.metrics.annotation.Timed)5 AuthorizationCodeRequestUrl (com.google.api.client.auth.oauth2.AuthorizationCodeRequestUrl)5 Collections (java.util.Collections)5