Search in sources :

Example 6 with TokenResponse

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

the class FreenetAuthenticatedUrlProvider method toUrl.

@Override
public DescriptiveUrl toUrl(final Host bookmark) {
    try {
        // Run password flow
        final TokenResponse response;
        try {
            final Host target = new Host(new DAVSSLProtocol(), "oauth.freenet.de");
            final X509TrustManager trust = new KeychainX509TrustManager(new DisabledCertificateTrustCallback(), new DefaultTrustManagerHostnameCallback(target), CertificateStoreFactory.get());
            final X509KeyManager key = new KeychainX509KeyManager(new DisabledCertificateIdentityCallback(), target, CertificateStoreFactory.get());
            final CloseableHttpClient client = new HttpConnectionPoolBuilder(target, new ThreadLocalHostnameDelegatingTrustManager(trust, target.getHostname()), key, ProxyFactory.get()).build(ProxyFactory.get().find(new ProxyHostUrlProvider().get(target)), new DisabledTranscriptListener(), new DisabledLoginCallback()).setUserAgent(new FreenetUserAgentProvider().get()).build();
            final String username = bookmark.getCredentials().getUsername();
            final String password;
            if (StringUtils.isBlank(bookmark.getCredentials().getPassword())) {
                password = PasswordStoreFactory.get().findLoginPassword(bookmark);
            } else {
                password = bookmark.getCredentials().getPassword();
            }
            response = new PasswordTokenRequest(new ApacheHttpTransport(client), new GsonFactory(), new GenericUrl("https://oauth.freenet.de/oauth/token"), username, password).setClientAuthentication(new BasicAuthentication("desktop_client", "6LIGIHuOSkznLomu5xw0EPPBJOXb2jLp")).setRequestInitializer(new UserAgentHttpRequestInitializer(new FreenetUserAgentProvider())).set("world", new HostPreferences(bookmark).getProperty("world")).set("webLogin", Boolean.TRUE).execute();
            final FreenetTemporaryLoginResponse login = this.getLoginSession(client, response.getAccessToken());
            return new DescriptiveUrl(URI.create(login.urls.login), DescriptiveUrl.Type.authenticated);
        } catch (IOException e) {
            throw new HttpExceptionMappingService().map(e);
        }
    } catch (BackgroundException e) {
        log.warn(String.format("Failure %s retrieving authenticated URL for %s", e, bookmark));
        return DescriptiveUrl.EMPTY;
    }
}
Also used : UserAgentHttpRequestInitializer(ch.cyberduck.core.http.UserAgentHttpRequestInitializer) KeychainX509KeyManager(ch.cyberduck.core.ssl.KeychainX509KeyManager) DisabledCertificateIdentityCallback(ch.cyberduck.core.DisabledCertificateIdentityCallback) ProxyHostUrlProvider(ch.cyberduck.core.proxy.ProxyHostUrlProvider) GenericUrl(com.google.api.client.http.GenericUrl) DAVSSLProtocol(ch.cyberduck.core.dav.DAVSSLProtocol) KeychainX509TrustManager(ch.cyberduck.core.ssl.KeychainX509TrustManager) HttpExceptionMappingService(ch.cyberduck.core.http.HttpExceptionMappingService) HttpConnectionPoolBuilder(ch.cyberduck.core.http.HttpConnectionPoolBuilder) KeychainX509KeyManager(ch.cyberduck.core.ssl.KeychainX509KeyManager) X509KeyManager(ch.cyberduck.core.ssl.X509KeyManager) DisabledCertificateTrustCallback(ch.cyberduck.core.DisabledCertificateTrustCallback) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) GsonFactory(com.google.api.client.json.gson.GsonFactory) Host(ch.cyberduck.core.Host) IOException(java.io.IOException) DisabledTranscriptListener(ch.cyberduck.core.DisabledTranscriptListener) HostPreferences(ch.cyberduck.core.preferences.HostPreferences) DescriptiveUrl(ch.cyberduck.core.DescriptiveUrl) TokenResponse(com.google.api.client.auth.oauth2.TokenResponse) X509TrustManager(ch.cyberduck.core.ssl.X509TrustManager) KeychainX509TrustManager(ch.cyberduck.core.ssl.KeychainX509TrustManager) DisabledLoginCallback(ch.cyberduck.core.DisabledLoginCallback) ThreadLocalHostnameDelegatingTrustManager(ch.cyberduck.core.ssl.ThreadLocalHostnameDelegatingTrustManager) DefaultTrustManagerHostnameCallback(ch.cyberduck.core.ssl.DefaultTrustManagerHostnameCallback) BasicAuthentication(com.google.api.client.http.BasicAuthentication) PasswordTokenRequest(com.google.api.client.auth.oauth2.PasswordTokenRequest) ApacheHttpTransport(com.google.api.client.http.apache.v2.ApacheHttpTransport) BackgroundException(ch.cyberduck.core.exception.BackgroundException)

Example 7 with TokenResponse

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

the class OAuth2AuthorizationService method refresh.

public OAuthTokens refresh(final OAuthTokens tokens) throws BackgroundException {
    if (StringUtils.isBlank(tokens.getRefreshToken())) {
        log.warn("Missing refresh token");
        return tokens;
    }
    if (log.isDebugEnabled()) {
        log.debug(String.format("Refresh expired tokens %s", tokens));
    }
    try {
        final TokenResponse response = new RefreshTokenRequest(transport, json, new GenericUrl(tokenServerUrl), tokens.getRefreshToken()).setRequestInitializer(new UserAgentHttpRequestInitializer(new PreferencesUseragentProvider())).setClientAuthentication(new ClientParametersAuthentication(clientid, clientsecret)).executeUnparsed().parseAs(PermissiveTokenResponse.class).toTokenResponse();
        final long expiryInMilliseconds = System.currentTimeMillis() + response.getExpiresInSeconds() * 1000;
        if (StringUtils.isBlank(response.getRefreshToken())) {
            return new OAuthTokens(response.getAccessToken(), tokens.getRefreshToken(), expiryInMilliseconds);
        }
        return new OAuthTokens(response.getAccessToken(), response.getRefreshToken(), expiryInMilliseconds);
    } catch (TokenResponseException e) {
        throw new OAuthExceptionMappingService().map(e);
    } catch (HttpResponseException e) {
        throw new DefaultHttpResponseExceptionMappingService().map(new org.apache.http.client.HttpResponseException(e.getStatusCode(), e.getStatusMessage()));
    } catch (IOException e) {
        throw new DefaultIOExceptionMappingService().map(e);
    }
}
Also used : DefaultHttpResponseExceptionMappingService(ch.cyberduck.core.http.DefaultHttpResponseExceptionMappingService) UserAgentHttpRequestInitializer(ch.cyberduck.core.http.UserAgentHttpRequestInitializer) OAuthTokens(ch.cyberduck.core.OAuthTokens) PreferencesUseragentProvider(ch.cyberduck.core.PreferencesUseragentProvider) HttpResponseException(com.google.api.client.http.HttpResponseException) GenericUrl(com.google.api.client.http.GenericUrl) IOException(java.io.IOException) RefreshTokenRequest(com.google.api.client.auth.oauth2.RefreshTokenRequest) ClientParametersAuthentication(com.google.api.client.auth.oauth2.ClientParametersAuthentication) TokenResponse(com.google.api.client.auth.oauth2.TokenResponse) DefaultIOExceptionMappingService(ch.cyberduck.core.DefaultIOExceptionMappingService) TokenResponseException(com.google.api.client.auth.oauth2.TokenResponseException)

Example 8 with TokenResponse

use of com.microsoft.identity.common.internal.providers.oauth2.TokenResponse in project devspaces-images by redhat-developer.

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 9 with TokenResponse

use of com.microsoft.identity.common.internal.providers.oauth2.TokenResponse in project sigstore-maven-plugin by sigstore.

the class Sign method getIDToken.

/**
 * Obtains an OpenID Connect Identity Token from the OIDC provider specified in <code>oidcAuthURL</code>
 *
 * @param  expectedEmailAddress The email address we expected to see in the identity token
 * @return      the ID token String (in JWS format)
 * @throws MojoExecutionException If any exception happened during the OIDC authentication flow
 */
public String getIDToken(String expectedEmailAddress) throws MojoExecutionException {
    try {
        JsonFactory jsonFactory = new GsonFactory();
        HttpTransport httpTransport = getHttpTransport();
        DataStoreFactory memStoreFactory = new MemoryDataStoreFactory();
        final String idTokenKey = "id_token";
        if (!oidcDeviceCodeFlow) {
            AuthorizationCodeFlow.Builder flowBuilder = new AuthorizationCodeFlow.Builder(BearerToken.authorizationHeaderAccessMethod(), httpTransport, jsonFactory, new GenericUrl(oidcTokenURL.toString()), new ClientParametersAuthentication(oidcClientID, null), oidcClientID, oidcAuthURL.toString()).enablePKCE().setScopes(List.of("openid", "email")).setCredentialCreatedListener(new AuthorizationCodeFlow.CredentialCreatedListener() {

                @Override
                public void onCredentialCreated(Credential credential, TokenResponse tokenResponse) throws IOException {
                    memStoreFactory.getDataStore("user").set(idTokenKey, tokenResponse.get(idTokenKey).toString());
                }
            });
            AuthorizationCodeInstalledApp app = new AuthorizationCodeInstalledApp(flowBuilder.build(), new LocalServerReceiver());
            app.authorize("user");
        }
        // TODO: add device code flow support
        String idTokenString = (String) memStoreFactory.getDataStore("user").get(idTokenKey);
        IdTokenVerifier idTokenVerifier = new IdTokenVerifier();
        IdToken parsedIdToken = IdToken.parse(jsonFactory, idTokenString);
        if (!idTokenVerifier.verify(parsedIdToken)) {
            throw new InvalidObjectException("id token could not be verified");
        }
        String emailFromIDToken = (String) parsedIdToken.getPayload().get("email");
        Boolean emailVerified = (Boolean) parsedIdToken.getPayload().get("email_verified");
        if (expectedEmailAddress != null && !emailFromIDToken.equals(expectedEmailAddress)) {
            throw new InvalidObjectException(String.format("email in ID token '%s' does not match address specified to plugin '%s'", emailFromIDToken, emailAddress));
        } else if (Boolean.FALSE.equals(emailVerified)) {
            throw new InvalidObjectException(String.format("identity provider '%s' reports email address '%s' has not been verified", parsedIdToken.getPayload().getIssuer(), emailAddress));
        }
        this.emailAddress = emailFromIDToken;
        return idTokenString;
    } catch (Exception e) {
        throw new MojoExecutionException("Error signing email address:", e);
    }
}
Also used : IdToken(com.google.api.client.auth.openidconnect.IdToken) Credential(com.google.api.client.auth.oauth2.Credential) GsonFactory(com.google.api.client.json.gson.GsonFactory) MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) JsonFactory(com.google.api.client.json.JsonFactory) AuthorizationCodeInstalledApp(com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp) GenericUrl(com.google.api.client.http.GenericUrl) IOException(java.io.IOException) LocalServerReceiver(com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver) InvalidObjectException(java.io.InvalidObjectException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) IOException(java.io.IOException) MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) AuthorizationCodeFlow(com.google.api.client.auth.oauth2.AuthorizationCodeFlow) HttpTransport(com.google.api.client.http.HttpTransport) ApacheHttpTransport(com.google.api.client.http.apache.v2.ApacheHttpTransport) ClientParametersAuthentication(com.google.api.client.auth.oauth2.ClientParametersAuthentication) MemoryDataStoreFactory(com.google.api.client.util.store.MemoryDataStoreFactory) TokenResponse(com.google.api.client.auth.oauth2.TokenResponse) InvalidObjectException(java.io.InvalidObjectException) MemoryDataStoreFactory(com.google.api.client.util.store.MemoryDataStoreFactory) DataStoreFactory(com.google.api.client.util.store.DataStoreFactory) IdTokenVerifier(com.google.api.client.auth.openidconnect.IdTokenVerifier)

Example 10 with TokenResponse

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

the class GoogleCalendarSyncProvider method getOrCreateGoogleCalendarClient.

/**
 * Build and return an authorized google calendar client.
 *
 * @return an authorized calendar client service
 */
private com.google.api.services.calendar.Calendar getOrCreateGoogleCalendarClient() {
    String refreshToken = settingsService.getSettings().getCalendarSettings().getGoogleCalendarSettings().getRefreshToken();
    if (googleCalendarClient != null && refreshToken != null && refreshTokenHashCode == refreshToken.hashCode()) {
        LOG.debug("use cached googleCalendarClient");
        return googleCalendarClient;
    }
    try {
        LOG.info("create new googleCalendarClient");
        if (refreshToken != null) {
            refreshTokenHashCode = refreshToken.hashCode();
        }
        NetHttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
        TokenResponse tokenResponse = new TokenResponse();
        tokenResponse.setRefreshToken(refreshToken);
        Credential credential = createCredentialWithRefreshToken(httpTransport, JSON_FACTORY, tokenResponse);
        return new com.google.api.services.calendar.Calendar.Builder(httpTransport, JSON_FACTORY, credential).setApplicationName(APPLICATION_NAME).build();
    } catch (GeneralSecurityException | IOException e) {
        LOG.error("Something went wrong!", e);
    }
    return null;
}
Also used : Credential(com.google.api.client.auth.oauth2.Credential) TokenResponse(com.google.api.client.auth.oauth2.TokenResponse) NetHttpTransport(com.google.api.client.http.javanet.NetHttpTransport) GoogleNetHttpTransport(com.google.api.client.googleapis.javanet.GoogleNetHttpTransport) GeneralSecurityException(java.security.GeneralSecurityException) IOException(java.io.IOException)

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