Search in sources :

Example 11 with OAuthResponseException

use of org.openhab.core.auth.client.oauth2.OAuthResponseException in project openhab-addons by openhab.

the class OAuthAuthorizationHandlerImpl method completeAuthorization.

@Override
public synchronized void completeAuthorization(String redirectUrlWithParameters) {
    abortTimer();
    final OAuthClientService oauthClientService = this.oauthClientService;
    if (oauthClientService == null) {
        throw new NoOngoingAuthorizationException("There is no ongoing authorization.");
    }
    try {
        String authorizationCode = oauthClientService.extractAuthCodeFromAuthResponse(redirectUrlWithParameters);
        // Although this method is called "get" it actually fetches and stores the token response as a side effect.
        oauthClientService.getAccessTokenResponseByAuthorizationCode(authorizationCode, redirectUri);
    } catch (IOException e) {
        throw new OAuthException("Network error while retrieving token response: " + e.getMessage(), e);
    } catch (OAuthResponseException e) {
        throw new OAuthException("Failed to retrieve token response: " + e.getMessage(), e);
    } catch (org.openhab.core.auth.client.oauth2.OAuthException e) {
        throw new OAuthException("Error while processing Miele service response: " + e.getMessage(), e);
    } finally {
        this.oauthClientService = null;
        this.bridgeUid = null;
        this.email = null;
        this.redirectUri = null;
    }
}
Also used : OAuthResponseException(org.openhab.core.auth.client.oauth2.OAuthResponseException) OAuthClientService(org.openhab.core.auth.client.oauth2.OAuthClientService) OAuthException(org.openhab.binding.mielecloud.internal.auth.OAuthException) IOException(java.io.IOException) NoOngoingAuthorizationException(org.openhab.binding.mielecloud.internal.config.exception.NoOngoingAuthorizationException)

Example 12 with OAuthResponseException

use of org.openhab.core.auth.client.oauth2.OAuthResponseException in project openhab-addons by openhab.

the class GoogleCloudAPI method getAccessToken.

/**
 * Fetches the OAuth2 tokens from Google Cloud Platform if the auth-code is set in the configuration. If successful
 * the auth-code will be removed from the configuration.
 *
 * @throws AuthenticationException
 * @throws CommunicationException
 */
@SuppressWarnings("null")
private void getAccessToken() throws AuthenticationException, CommunicationException {
    String authcode = config.authcode;
    if (authcode != null && !authcode.isEmpty()) {
        logger.debug("Trying to get access and refresh tokens.");
        try {
            oAuthService.getAccessTokenResponseByAuthorizationCode(authcode, GCP_REDIRECT_URI);
        } catch (OAuthException | OAuthResponseException e) {
            logger.debug("Error fetching access token: {}", e.getMessage(), e);
            throw new AuthenticationException("Error fetching access token. Invalid authcode? Please generate a new one.");
        } catch (IOException e) {
            throw new CommunicationException(String.format("An unexpected IOException occurred: %s", e.getMessage()));
        }
        config.authcode = null;
        try {
            Configuration serviceConfig = configAdmin.getConfiguration(GoogleTTSService.SERVICE_PID);
            Dictionary<String, Object> configProperties = serviceConfig.getProperties();
            if (configProperties != null) {
                configProperties.put(GoogleTTSService.PARAM_AUTHCODE, "");
                serviceConfig.update(configProperties);
            }
        } catch (IOException e) {
            // should not happen
            logger.warn("Failed to update configuration for Google Cloud TTS service. Please clear the 'authcode' configuration parameter manualy.");
        }
    }
}
Also used : OAuthResponseException(org.openhab.core.auth.client.oauth2.OAuthResponseException) CommunicationException(org.openhab.core.i18n.CommunicationException) Configuration(org.osgi.service.cm.Configuration) AuthenticationException(org.openhab.core.auth.AuthenticationException) OAuthException(org.openhab.core.auth.client.oauth2.OAuthException) IOException(java.io.IOException)

Example 13 with OAuthResponseException

use of org.openhab.core.auth.client.oauth2.OAuthResponseException in project openhab-addons by openhab.

the class MyQAccountHandler method sendRequest.

private synchronized ContentResponse sendRequest(String url, HttpMethod method, @Nullable ContentProvider content, @Nullable String contentType) throws InterruptedException, MyQCommunicationException, MyQAuthenticationException {
    AccessTokenResponse tokenResponse = null;
    // if we don't need to force a login, attempt to use the token we have
    if (!needsLogin) {
        try {
            tokenResponse = getOAuthService().getAccessTokenResponse();
        } catch (OAuthException | IOException | OAuthResponseException e) {
            // ignore error, will try to login below
            logger.debug("Error accessing token, will attempt to login again", e);
        }
    }
    // if no token, or we need to login, do so now
    if (tokenResponse == null) {
        tokenResponse = login();
        needsLogin = false;
    }
    Request request = httpClient.newRequest(url).method(method).agent(userAgent).timeout(10, TimeUnit.SECONDS).header("Authorization", authTokenHeader(tokenResponse));
    if (content != null & contentType != null) {
        request = request.content(content, contentType);
    }
    // use asyc jetty as the API service will response with a 401 error when credentials are wrong,
    // but not a WWW-Authenticate header which causes Jetty to throw a generic execution exception which
    // prevents us from knowing the response code
    logger.trace("Sending {} to {}", request.getMethod(), request.getURI());
    final CompletableFuture<ContentResponse> futureResult = new CompletableFuture<>();
    request.send(new BufferingResponseListener() {

        @NonNullByDefault({})
        @Override
        public void onComplete(Result result) {
            Response response = result.getResponse();
            futureResult.complete(new HttpContentResponse(response, getContent(), getMediaType(), getEncoding()));
        }
    });
    try {
        ContentResponse result = futureResult.get();
        logger.trace("Account Response - status: {} content: {}", result.getStatus(), result.getContentAsString());
        return result;
    } catch (ExecutionException e) {
        throw new MyQCommunicationException(e.getMessage());
    }
}
Also used : OAuthResponseException(org.openhab.core.auth.client.oauth2.OAuthResponseException) NonNullByDefault(org.eclipse.jdt.annotation.NonNullByDefault) HttpContentResponse(org.eclipse.jetty.client.HttpContentResponse) ContentResponse(org.eclipse.jetty.client.api.ContentResponse) OAuthException(org.openhab.core.auth.client.oauth2.OAuthException) Request(org.eclipse.jetty.client.api.Request) IOException(java.io.IOException) Result(org.eclipse.jetty.client.api.Result) HttpContentResponse(org.eclipse.jetty.client.HttpContentResponse) ContentResponse(org.eclipse.jetty.client.api.ContentResponse) Response(org.eclipse.jetty.client.api.Response) AccessTokenResponse(org.openhab.core.auth.client.oauth2.AccessTokenResponse) CompletableFuture(java.util.concurrent.CompletableFuture) ExecutionException(java.util.concurrent.ExecutionException) AccessTokenResponse(org.openhab.core.auth.client.oauth2.AccessTokenResponse) HttpContentResponse(org.eclipse.jetty.client.HttpContentResponse) BufferingResponseListener(org.eclipse.jetty.client.util.BufferingResponseListener)

Example 14 with OAuthResponseException

use of org.openhab.core.auth.client.oauth2.OAuthResponseException in project openhab-addons by openhab.

the class SpotifyBridgeHandler method authorize.

@Override
public String authorize(String redirectUri, String reqCode) {
    try {
        logger.debug("Make call to Spotify to get access token.");
        final AccessTokenResponse credentials = oAuthService.getAccessTokenResponseByAuthorizationCode(reqCode, redirectUri);
        final String user = updateProperties(credentials);
        logger.debug("Authorized for user: {}", user);
        startPolling();
        return user;
    } catch (RuntimeException | OAuthException | IOException e) {
        updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, e.getMessage());
        throw new SpotifyException(e.getMessage(), e);
    } catch (final OAuthResponseException e) {
        throw new SpotifyAuthorizationException(e.getMessage(), e);
    }
}
Also used : SpotifyException(org.openhab.binding.spotify.internal.api.exception.SpotifyException) OAuthResponseException(org.openhab.core.auth.client.oauth2.OAuthResponseException) OAuthException(org.openhab.core.auth.client.oauth2.OAuthException) IOException(java.io.IOException) AccessTokenResponse(org.openhab.core.auth.client.oauth2.AccessTokenResponse) SpotifyAuthorizationException(org.openhab.binding.spotify.internal.api.exception.SpotifyAuthorizationException)

Example 15 with OAuthResponseException

use of org.openhab.core.auth.client.oauth2.OAuthResponseException in project openhab-core by openhab.

the class OAuthClientServiceImpl method getAccessTokenByResourceOwnerPasswordCredentials.

@Override
public AccessTokenResponse getAccessTokenByResourceOwnerPasswordCredentials(String username, String password, @Nullable String scope) throws OAuthException, IOException, OAuthResponseException {
    if (isClosed()) {
        throw new OAuthException(EXCEPTION_MESSAGE_CLOSED);
    }
    String tokenUrl = persistedParams.tokenUrl;
    if (tokenUrl == null) {
        throw new OAuthException("Missing token url");
    }
    OAuthConnector connector = new OAuthConnector(httpClientFactory, persistedParams.deserializerClassName);
    AccessTokenResponse accessTokenResponse = connector.grantTypePassword(tokenUrl, username, password, persistedParams.clientId, persistedParams.clientSecret, scope, Boolean.TRUE.equals(persistedParams.supportsBasicAuth));
    // store it
    storeHandler.saveAccessTokenResponse(handle, accessTokenResponse);
    return accessTokenResponse;
}
Also used : OAuthException(org.openhab.core.auth.client.oauth2.OAuthException) AccessTokenResponse(org.openhab.core.auth.client.oauth2.AccessTokenResponse)

Aggregations

AccessTokenResponse (org.openhab.core.auth.client.oauth2.AccessTokenResponse)21 IOException (java.io.IOException)19 OAuthException (org.openhab.core.auth.client.oauth2.OAuthException)19 OAuthResponseException (org.openhab.core.auth.client.oauth2.OAuthResponseException)19 OAuthClientService (org.openhab.core.auth.client.oauth2.OAuthClientService)11 Test (org.junit.jupiter.api.Test)7 ContentResponse (org.eclipse.jetty.client.api.ContentResponse)6 OAuthFactory (org.openhab.core.auth.client.oauth2.OAuthFactory)6 Nullable (org.eclipse.jdt.annotation.Nullable)5 Request (org.eclipse.jetty.client.api.Request)5 JsonSyntaxException (com.google.gson.JsonSyntaxException)4 ExecutionException (java.util.concurrent.ExecutionException)4 TimeoutException (java.util.concurrent.TimeoutException)3 NonNullByDefault (org.eclipse.jdt.annotation.NonNullByDefault)3 StringContentProvider (org.eclipse.jetty.client.util.StringContentProvider)3 PrivilegedActionException (java.security.PrivilegedActionException)2 Collections (java.util.Collections)2 List (java.util.List)2 Objects (java.util.Objects)2 ScheduledExecutorService (java.util.concurrent.ScheduledExecutorService)2