Search in sources :

Example 36 with AccessTokenResponse

use of com.tremolosecurity.proxy.auth.oauth2.AccessTokenResponse in project openhab-addons by openhab.

the class OpenHabOAuthTokenRefresherTest method whenTokenIsRefreshedThenTheListenerIsCalledWithTheNewAccessToken.

@Test
public void whenTokenIsRefreshedThenTheListenerIsCalledWithTheNewAccessToken() throws org.openhab.core.auth.client.oauth2.OAuthException, IOException, OAuthResponseException {
    // given:
    AccessTokenResponse accessTokenResponse = new AccessTokenResponse();
    accessTokenResponse.setAccessToken(ACCESS_TOKEN);
    OAuthClientService oauthClientService = mock(OAuthClientService.class);
    OAuthFactory oauthFactory = mock(OAuthFactory.class);
    when(oauthFactory.getOAuthClientService(MieleCloudBindingTestConstants.SERVICE_HANDLE)).thenReturn(oauthClientService);
    OpenHabOAuthTokenRefresher refresher = new OpenHabOAuthTokenRefresher(oauthFactory);
    when(oauthClientService.refreshToken()).thenAnswer(new Answer<@Nullable AccessTokenResponse>() {

        @Override
        @Nullable
        public AccessTokenResponse answer(@Nullable InvocationOnMock invocation) throws Throwable {
            getAccessTokenRefreshListenerByServiceHandle(refresher, MieleCloudBindingTestConstants.SERVICE_HANDLE).onAccessTokenResponse(accessTokenResponse);
            return accessTokenResponse;
        }
    });
    OAuthTokenRefreshListener listener = mock(OAuthTokenRefreshListener.class);
    refresher.setRefreshListener(listener, MieleCloudBindingTestConstants.SERVICE_HANDLE);
    // when:
    refresher.refreshToken(MieleCloudBindingTestConstants.SERVICE_HANDLE);
    // then:
    verify(listener).onNewAccessToken(ACCESS_TOKEN);
}
Also used : OAuthClientService(org.openhab.core.auth.client.oauth2.OAuthClientService) InvocationOnMock(org.mockito.invocation.InvocationOnMock) OAuthFactory(org.openhab.core.auth.client.oauth2.OAuthFactory) AccessTokenResponse(org.openhab.core.auth.client.oauth2.AccessTokenResponse) Nullable(org.eclipse.jdt.annotation.Nullable) Test(org.junit.jupiter.api.Test)

Example 37 with AccessTokenResponse

use of com.tremolosecurity.proxy.auth.oauth2.AccessTokenResponse in project openhab-addons by openhab.

the class OpenHabOAuthTokenRefresher method refreshAccessToken.

private void refreshAccessToken(OAuthClientService clientService) {
    try {
        final AccessTokenResponse accessTokenResponse = clientService.refreshToken();
        final String accessToken = accessTokenResponse.getAccessToken();
        if (accessToken == null) {
            throw new OAuthException("Access token is not available.");
        }
    } catch (org.openhab.core.auth.client.oauth2.OAuthException e) {
        throw new OAuthException("An error occured during token refresh: " + e.getMessage(), e);
    } catch (IOException e) {
        throw new OAuthException("A network error occured during token refresh: " + e.getMessage(), e);
    } catch (OAuthResponseException e) {
        throw new OAuthException("Miele cloud service returned an illegal response: " + e.getMessage(), e);
    }
}
Also used : OAuthResponseException(org.openhab.core.auth.client.oauth2.OAuthResponseException) IOException(java.io.IOException) AccessTokenResponse(org.openhab.core.auth.client.oauth2.AccessTokenResponse)

Example 38 with AccessTokenResponse

use of com.tremolosecurity.proxy.auth.oauth2.AccessTokenResponse in project openhab-addons by openhab.

the class SpotifyApi method request.

/**
 * Calls the Spotify Web Api with the given method and given url as parameters of the call to Spotify.
 *
 * @param method Http method to perform
 * @param url url path to call to Spotify
 * @param requestData data to pass along with the call as content
 * @param clazz data type of return data, if null no data is expected to be returned.
 * @return the response give by Spotify
 */
@Nullable
private <T> T request(HttpMethod method, String url, String requestData, Class<T> clazz) {
    logger.debug("Request: ({}) {} - {}", method, url, requestData);
    final Function<HttpClient, Request> call = httpClient -> httpClient.newRequest(url).method(method).header("Accept", CONTENT_TYPE).content(new StringContentProvider(requestData), CONTENT_TYPE);
    try {
        final AccessTokenResponse accessTokenResponse = oAuthClientService.getAccessTokenResponse();
        final String accessToken = accessTokenResponse == null ? null : accessTokenResponse.getAccessToken();
        if (accessToken == null || accessToken.isEmpty()) {
            throw new SpotifyAuthorizationException("No Spotify accesstoken. Did you authorize Spotify via /connectspotify ?");
        } else {
            final String response = requestWithRetry(call, accessToken).getContentAsString();
            return clazz == String.class ? (@Nullable T) response : fromJson(response, clazz);
        }
    } catch (final IOException e) {
        throw new SpotifyException(e.getMessage(), e);
    } catch (OAuthException | OAuthResponseException e) {
        throw new SpotifyAuthorizationException(e.getMessage(), e);
    }
}
Also used : Arrays(java.util.Arrays) GET(org.eclipse.jetty.http.HttpMethod.GET) Devices(org.openhab.binding.spotify.internal.api.model.Devices) OAuthException(org.openhab.core.auth.client.oauth2.OAuthException) LoggerFactory(org.slf4j.LoggerFactory) OnOffType(org.openhab.core.library.types.OnOffType) Request(org.eclipse.jetty.client.api.Request) StringContentProvider(org.eclipse.jetty.client.util.StringContentProvider) Function(java.util.function.Function) SPOTIFY_API_PLAYER_URL(org.openhab.binding.spotify.internal.SpotifyBindingConstants.SPOTIFY_API_PLAYER_URL) HttpClient(org.eclipse.jetty.client.HttpClient) ContentResponse(org.eclipse.jetty.client.api.ContentResponse) Playlist(org.openhab.binding.spotify.internal.api.model.Playlist) Nullable(org.eclipse.jdt.annotation.Nullable) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) PUT(org.eclipse.jetty.http.HttpMethod.PUT) CurrentlyPlayingContext(org.openhab.binding.spotify.internal.api.model.CurrentlyPlayingContext) NonNullByDefault(org.eclipse.jdt.annotation.NonNullByDefault) SpotifyAuthorizationException(org.openhab.binding.spotify.internal.api.exception.SpotifyAuthorizationException) Logger(org.slf4j.Logger) POST(org.eclipse.jetty.http.HttpMethod.POST) OAuthResponseException(org.openhab.core.auth.client.oauth2.OAuthResponseException) JsonSyntaxException(com.google.gson.JsonSyntaxException) IOException(java.io.IOException) Collectors(java.util.stream.Collectors) ModelUtil(org.openhab.binding.spotify.internal.api.model.ModelUtil) Objects(java.util.Objects) Device(org.openhab.binding.spotify.internal.api.model.Device) SPOTIFY_API_URL(org.openhab.binding.spotify.internal.SpotifyBindingConstants.SPOTIFY_API_URL) List(java.util.List) HttpMethod(org.eclipse.jetty.http.HttpMethod) SpotifyTokenExpiredException(org.openhab.binding.spotify.internal.api.exception.SpotifyTokenExpiredException) AccessTokenResponse(org.openhab.core.auth.client.oauth2.AccessTokenResponse) Playlists(org.openhab.binding.spotify.internal.api.model.Playlists) OAuthClientService(org.openhab.core.auth.client.oauth2.OAuthClientService) SpotifyException(org.openhab.binding.spotify.internal.api.exception.SpotifyException) Collections(java.util.Collections) Me(org.openhab.binding.spotify.internal.api.model.Me) OAuthResponseException(org.openhab.core.auth.client.oauth2.OAuthResponseException) StringContentProvider(org.eclipse.jetty.client.util.StringContentProvider) OAuthException(org.openhab.core.auth.client.oauth2.OAuthException) Request(org.eclipse.jetty.client.api.Request) IOException(java.io.IOException) SpotifyException(org.openhab.binding.spotify.internal.api.exception.SpotifyException) HttpClient(org.eclipse.jetty.client.HttpClient) AccessTokenResponse(org.openhab.core.auth.client.oauth2.AccessTokenResponse) SpotifyAuthorizationException(org.openhab.binding.spotify.internal.api.exception.SpotifyAuthorizationException) Nullable(org.eclipse.jdt.annotation.Nullable) Nullable(org.eclipse.jdt.annotation.Nullable)

Example 39 with AccessTokenResponse

use of com.tremolosecurity.proxy.auth.oauth2.AccessTokenResponse in project openhab-addons by openhab.

the class HomeConnectBridgeHandler method initialize.

@Override
public void initialize() {
    // let the bridge configuration servlet know about this handler
    homeConnectServlet.addBridgeHandler(this);
    // create oAuth service
    ApiBridgeConfiguration config = getConfiguration();
    String tokenUrl = (config.isSimulator() ? API_SIMULATOR_BASE_URL : API_BASE_URL) + OAUTH_TOKEN_PATH;
    String authorizeUrl = (config.isSimulator() ? API_SIMULATOR_BASE_URL : API_BASE_URL) + OAUTH_AUTHORIZE_PATH;
    String oAuthServiceHandleId = thing.getUID().getAsString() + (config.isSimulator() ? "simulator" : "");
    oAuthClientService = oAuthFactory.createOAuthClientService(oAuthServiceHandleId, tokenUrl, authorizeUrl, config.getClientId(), config.getClientSecret(), OAUTH_SCOPE, true);
    this.oAuthServiceHandleId = oAuthServiceHandleId;
    logger.debug("Initialize oAuth client service. tokenUrl={}, authorizeUrl={}, oAuthServiceHandleId={}, scope={}, oAuthClientService={}", tokenUrl, authorizeUrl, oAuthServiceHandleId, OAUTH_SCOPE, oAuthClientService);
    // create api client
    apiClient = new HomeConnectApiClient(httpClient, oAuthClientService, config.isSimulator(), apiRequestHistory, config);
    eventSourceClient = new HomeConnectEventSourceClient(clientBuilder, eventSourceFactory, oAuthClientService, config.isSimulator(), scheduler, eventHistory);
    updateStatus(ThingStatus.UNKNOWN);
    scheduler.submit(() -> {
        try {
            @Nullable AccessTokenResponse accessTokenResponse = oAuthClientService.getAccessTokenResponse();
            if (accessTokenResponse == null) {
                updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_PENDING, "Please authenticate your account at http(s)://[YOUROPENHAB]:[YOURPORT]/homeconnect (e.g. http://192.168.178.100:8080/homeconnect).");
            } else {
                apiClient.getHomeAppliances();
                updateStatus(ThingStatus.ONLINE);
            }
        } catch (OAuthException | IOException | OAuthResponseException | CommunicationException | AuthorizationException e) {
            ZonedDateTime nextReinitializeDateTime = ZonedDateTime.now().plusSeconds(REINITIALIZATION_DELAY_SEC);
            String offlineMessage = String.format("Home Connect service is not reachable or a problem occurred! Retrying at %s (%s). bridge=%s", nextReinitializeDateTime.format(DateTimeFormatter.RFC_1123_DATE_TIME), e.getMessage(), getThing().getLabel());
            updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, offlineMessage);
            scheduleReinitialize();
        }
    });
}
Also used : OAuthResponseException(org.openhab.core.auth.client.oauth2.OAuthResponseException) CommunicationException(org.openhab.binding.homeconnect.internal.client.exception.CommunicationException) AuthorizationException(org.openhab.binding.homeconnect.internal.client.exception.AuthorizationException) OAuthException(org.openhab.core.auth.client.oauth2.OAuthException) IOException(java.io.IOException) HomeConnectApiClient(org.openhab.binding.homeconnect.internal.client.HomeConnectApiClient) HomeConnectEventSourceClient(org.openhab.binding.homeconnect.internal.client.HomeConnectEventSourceClient) ApiBridgeConfiguration(org.openhab.binding.homeconnect.internal.configuration.ApiBridgeConfiguration) ZonedDateTime(java.time.ZonedDateTime) AccessTokenResponse(org.openhab.core.auth.client.oauth2.AccessTokenResponse) Nullable(org.eclipse.jdt.annotation.Nullable)

Example 40 with AccessTokenResponse

use of com.tremolosecurity.proxy.auth.oauth2.AccessTokenResponse in project openhab-addons by openhab.

the class SmartherApi method request.

/**
 * Calls the API gateway with the given http method, request url and actual data.
 *
 * @param method
 *            the http method to make the call with
 * @param url
 *            the API operation url to call
 * @param requestData
 *            the actual data to send in the request body, may be {@code null}
 *
 * @return the response received from the API gateway
 *
 * @throws {@link SmartherGatewayException}
 *             in case of communication issues with the API gateway
 */
private ContentResponse request(HttpMethod method, String url, @Nullable String requestData) throws SmartherGatewayException {
    logger.debug("Request: ({}) {} - {}", method, url, StringUtil.defaultString(requestData));
    Function<HttpClient, Request> call = httpClient -> httpClient.newRequest(url).method(method).header(HEADER_ACCEPT, CONTENT_TYPE).content(new StringContentProvider(StringUtil.defaultString(requestData)), CONTENT_TYPE);
    try {
        final AccessTokenResponse accessTokenResponse = oAuthClientService.getAccessTokenResponse();
        final String accessToken = (accessTokenResponse == null) ? null : accessTokenResponse.getAccessToken();
        if (accessToken == null || accessToken.isEmpty()) {
            throw new SmartherAuthorizationException(String.format("No gateway accesstoken. Did you authorize smarther via %s ?", AUTH_SERVLET_ALIAS));
        } else {
            return requestWithRetry(call, accessToken);
        }
    } catch (SmartherGatewayException e) {
        throw e;
    } catch (OAuthException | OAuthResponseException e) {
        throw new SmartherAuthorizationException(e.getMessage(), e);
    } catch (IOException e) {
        throw new SmartherGatewayException(e.getMessage(), e);
    }
}
Also used : SIUnits(org.openhab.core.library.unit.SIUnits) SmartherTokenExpiredException(org.openhab.binding.bticinosmarther.internal.api.exception.SmartherTokenExpiredException) Plants(org.openhab.binding.bticinosmarther.internal.api.dto.Plants) TypeToken(com.google.gson.reflect.TypeToken) Chronothermostat(org.openhab.binding.bticinosmarther.internal.api.dto.Chronothermostat) ModelUtil(org.openhab.binding.bticinosmarther.internal.util.ModelUtil) OAuthException(org.openhab.core.auth.client.oauth2.OAuthException) SmartherGatewayException(org.openhab.binding.bticinosmarther.internal.api.exception.SmartherGatewayException) LoggerFactory(org.slf4j.LoggerFactory) Request(org.eclipse.jetty.client.api.Request) StringContentProvider(org.eclipse.jetty.client.util.StringContentProvider) Function(java.util.function.Function) Plant(org.openhab.binding.bticinosmarther.internal.api.dto.Plant) Program(org.openhab.binding.bticinosmarther.internal.api.dto.Program) StringUtil(org.openhab.binding.bticinosmarther.internal.util.StringUtil) ArrayList(java.util.ArrayList) HttpClient(org.eclipse.jetty.client.HttpClient) ContentResponse(org.eclipse.jetty.client.api.ContentResponse) Temperature(javax.measure.quantity.Temperature) Nullable(org.eclipse.jdt.annotation.Nullable) Map(java.util.Map) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) Subscription(org.openhab.binding.bticinosmarther.internal.api.dto.Subscription) ModuleSettings(org.openhab.binding.bticinosmarther.internal.model.ModuleSettings) HttpStatus(org.eclipse.jetty.http.HttpStatus) MeasureUnit(org.openhab.binding.bticinosmarther.internal.api.dto.Enums.MeasureUnit) QuantityType(org.openhab.core.library.types.QuantityType) IdentityHashMap(java.util.IdentityHashMap) NonNullByDefault(org.eclipse.jdt.annotation.NonNullByDefault) Logger(org.slf4j.Logger) SmartherBindingConstants(org.openhab.binding.bticinosmarther.internal.SmartherBindingConstants) ModuleStatus(org.openhab.binding.bticinosmarther.internal.api.dto.ModuleStatus) OAuthResponseException(org.openhab.core.auth.client.oauth2.OAuthResponseException) JsonSyntaxException(com.google.gson.JsonSyntaxException) IOException(java.io.IOException) Objects(java.util.Objects) HttpMethod(org.eclipse.jetty.http.HttpMethod) List(java.util.List) Topology(org.openhab.binding.bticinosmarther.internal.api.dto.Topology) SmartherAuthorizationException(org.openhab.binding.bticinosmarther.internal.api.exception.SmartherAuthorizationException) AccessTokenResponse(org.openhab.core.auth.client.oauth2.AccessTokenResponse) OAuthClientService(org.openhab.core.auth.client.oauth2.OAuthClientService) Module(org.openhab.binding.bticinosmarther.internal.api.dto.Module) Collections(java.util.Collections) OAuthResponseException(org.openhab.core.auth.client.oauth2.OAuthResponseException) StringContentProvider(org.eclipse.jetty.client.util.StringContentProvider) OAuthException(org.openhab.core.auth.client.oauth2.OAuthException) Request(org.eclipse.jetty.client.api.Request) IOException(java.io.IOException) SmartherAuthorizationException(org.openhab.binding.bticinosmarther.internal.api.exception.SmartherAuthorizationException) SmartherGatewayException(org.openhab.binding.bticinosmarther.internal.api.exception.SmartherGatewayException) HttpClient(org.eclipse.jetty.client.HttpClient) AccessTokenResponse(org.openhab.core.auth.client.oauth2.AccessTokenResponse)

Aggregations

AccessTokenResponse (org.openhab.core.auth.client.oauth2.AccessTokenResponse)36 OAuthException (org.openhab.core.auth.client.oauth2.OAuthException)17 IOException (java.io.IOException)15 AccessTokenResponse (org.eclipse.smarthome.core.auth.client.oauth2.AccessTokenResponse)12 OAuthResponseException (org.openhab.core.auth.client.oauth2.OAuthResponseException)12 ContentResponse (org.eclipse.jetty.client.api.ContentResponse)8 OAuthClientService (org.openhab.core.auth.client.oauth2.OAuthClientService)8 Nullable (org.eclipse.jdt.annotation.Nullable)7 ExecutionException (java.util.concurrent.ExecutionException)6 OAuthException (org.eclipse.smarthome.core.auth.client.oauth2.OAuthException)6 TimeoutException (java.util.concurrent.TimeoutException)5 Request (org.eclipse.jetty.client.api.Request)5 OAuthFactory (org.openhab.core.auth.client.oauth2.OAuthFactory)5 JsonSyntaxException (com.google.gson.JsonSyntaxException)4 GeneralSecurityException (java.security.GeneralSecurityException)4 NonNullByDefault (org.eclipse.jdt.annotation.NonNullByDefault)3 StringContentProvider (org.eclipse.jetty.client.util.StringContentProvider)3 Test (org.junit.jupiter.api.Test)3 PrivilegedActionException (java.security.PrivilegedActionException)2 Collections (java.util.Collections)2