Search in sources :

Example 6 with AccessTokenResponse

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

the class HydrawiseGraphQLClient method sendGraphQLRequest.

private String sendGraphQLRequest(String content) throws HydrawiseConnectionException, HydrawiseAuthenticationException {
    logger.trace("Sending Request: {}", content);
    ContentResponse response;
    final AtomicInteger responseCode = new AtomicInteger(0);
    final StringBuilder responseMessage = new StringBuilder();
    try {
        AccessTokenResponse token = oAuthService.getAccessTokenResponse();
        if (token == null) {
            throw new HydrawiseAuthenticationException("Login required");
        }
        response = httpClient.newRequest(GRAPH_URL).method(HttpMethod.POST).content(new StringContentProvider(content), "application/json").header("Authorization", token.getTokenType() + " " + token.getAccessToken()).onResponseFailure(new Response.FailureListener() {

            @Override
            public void onFailure(@Nullable Response response, @Nullable Throwable failure) {
                int status = response != null ? response.getStatus() : -1;
                String reason = response != null ? response.getReason() : "Null response";
                logger.trace("onFailure code: {} message: {}", status, reason);
                responseCode.set(status);
                responseMessage.append(reason);
            }
        }).send();
        String stringResponse = response.getContentAsString();
        logger.trace("Received Response: {}", stringResponse);
        return stringResponse;
    } catch (InterruptedException | TimeoutException | OAuthException | IOException e) {
        logger.debug("Could not send request", e);
        throw new HydrawiseConnectionException(e);
    } catch (OAuthResponseException e) {
        throw new HydrawiseAuthenticationException(e.getMessage());
    } catch (ExecutionException e) {
        // this allows us to catch this in a callback and handle accordingly
        switch(responseCode.get()) {
            case 401:
            case 403:
                throw new HydrawiseAuthenticationException(responseMessage.toString());
            default:
                throw new HydrawiseConnectionException(e);
        }
    }
}
Also used : OAuthResponseException(org.openhab.core.auth.client.oauth2.OAuthResponseException) ContentResponse(org.eclipse.jetty.client.api.ContentResponse) StringContentProvider(org.eclipse.jetty.client.util.StringContentProvider) OAuthException(org.openhab.core.auth.client.oauth2.OAuthException) IOException(java.io.IOException) MutationResponse(org.openhab.binding.hydrawise.internal.api.graphql.dto.MutationResponse) ContentResponse(org.eclipse.jetty.client.api.ContentResponse) Response(org.eclipse.jetty.client.api.Response) AccessTokenResponse(org.openhab.core.auth.client.oauth2.AccessTokenResponse) QueryResponse(org.openhab.binding.hydrawise.internal.api.graphql.dto.QueryResponse) HydrawiseConnectionException(org.openhab.binding.hydrawise.internal.api.HydrawiseConnectionException) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) HydrawiseAuthenticationException(org.openhab.binding.hydrawise.internal.api.HydrawiseAuthenticationException) ExecutionException(java.util.concurrent.ExecutionException) AccessTokenResponse(org.openhab.core.auth.client.oauth2.AccessTokenResponse) TimeoutException(java.util.concurrent.TimeoutException)

Example 7 with AccessTokenResponse

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

the class SmartherBridgeHandler method isAuthorized.

@Override
public boolean isAuthorized() {
    try {
        final AccessTokenResponse tokenResponse = getAccessTokenResponse();
        onAccessTokenResponse(tokenResponse);
        return (tokenResponse != null && tokenResponse.getAccessToken() != null && tokenResponse.getRefreshToken() != null);
    } catch (SmartherAuthorizationException e) {
        return false;
    }
}
Also used : AccessTokenResponse(org.openhab.core.auth.client.oauth2.AccessTokenResponse) SmartherAuthorizationException(org.openhab.binding.bticinosmarther.internal.api.exception.SmartherAuthorizationException)

Example 8 with AccessTokenResponse

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

the class OpenHabOAuthTokenRefresherTest method whenTokenIsRefreshedAndNoAccessTokenIsProvidedThenTheListenerIsNotNotified.

@Test
public void whenTokenIsRefreshedAndNoAccessTokenIsProvidedThenTheListenerIsNotNotified() throws org.openhab.core.auth.client.oauth2.OAuthException, IOException, OAuthResponseException {
    // given:
    AccessTokenResponse accessTokenResponse = new AccessTokenResponse();
    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:
    assertThrows(OAuthException.class, () -> {
        try {
            refresher.refreshToken(MieleCloudBindingTestConstants.SERVICE_HANDLE);
        } catch (OAuthException e) {
            verifyNoInteractions(listener);
            throw e;
        }
    });
}
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 9 with AccessTokenResponse

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

the class MieleHandlerFactoryTest method setUp.

@BeforeEach
public void setUp() throws Exception {
    registerVolatileStorageService();
    thingRegistry = getService(ThingRegistry.class, ThingRegistry.class);
    assertNotNull(thingRegistry, "Thing registry is missing");
    // Ensure the MieleWebservice is not initialized.
    MieleHandlerFactory factory = getService(ThingHandlerFactory.class, MieleHandlerFactory.class);
    assertNotNull(factory);
    // Assume an access token has already been stored
    AccessTokenResponse accessTokenResponse = new AccessTokenResponse();
    accessTokenResponse.setAccessToken(ACCESS_TOKEN);
    OAuthClientService oAuthClientService = mock(OAuthClientService.class);
    when(oAuthClientService.getAccessTokenResponse()).thenReturn(accessTokenResponse);
    OAuthFactory oAuthFactory = mock(OAuthFactory.class);
    when(oAuthFactory.getOAuthClientService(MieleCloudBindingIntegrationTestConstants.EMAIL)).thenReturn(oAuthClientService);
    OpenHabOAuthTokenRefresher tokenRefresher = getService(OAuthTokenRefresher.class, OpenHabOAuthTokenRefresher.class);
    assertNotNull(tokenRefresher);
    setPrivate(Objects.requireNonNull(tokenRefresher), "oauthFactory", oAuthFactory);
}
Also used : OAuthClientService(org.openhab.core.auth.client.oauth2.OAuthClientService) OAuthFactory(org.openhab.core.auth.client.oauth2.OAuthFactory) OpenHabOAuthTokenRefresher(org.openhab.binding.mielecloud.internal.auth.OpenHabOAuthTokenRefresher) AccessTokenResponse(org.openhab.core.auth.client.oauth2.AccessTokenResponse) ThingRegistry(org.openhab.core.thing.ThingRegistry) BeforeEach(org.junit.jupiter.api.BeforeEach)

Example 10 with AccessTokenResponse

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

the class MyQAccountHandler method login.

/**
 * This attempts to navigate the MyQ oAuth login flow in order to obtain a @AccessTokenResponse
 *
 * @return AccessTokenResponse token
 * @throws InterruptedException
 * @throws MyQCommunicationException
 * @throws MyQAuthenticationException
 */
private AccessTokenResponse login() throws InterruptedException, MyQCommunicationException, MyQAuthenticationException {
    try {
        // make sure we have a fresh session
        URI authUri = new URI(LOGIN_BASE_URL);
        CookieStore store = httpClient.getCookieStore();
        store.get(authUri).forEach(cookie -> {
            store.remove(authUri, cookie);
        });
        String codeVerifier = generateCodeVerifier();
        ContentResponse loginPageResponse = getLoginPage(codeVerifier);
        // load the login page to get cookies and form parameters
        Document loginPage = Jsoup.parse(loginPageResponse.getContentAsString());
        Element form = loginPage.select("form").first();
        Element requestToken = loginPage.select("input[name=__RequestVerificationToken]").first();
        Element returnURL = loginPage.select("input[name=ReturnUrl]").first();
        if (form == null || requestToken == null) {
            throw new MyQCommunicationException("Could not load login page");
        }
        // url that the form will submit to
        String action = LOGIN_BASE_URL + form.attr("action");
        // post our user name and password along with elements from the scraped form
        String location = postLogin(action, requestToken.attr("value"), returnURL.attr("value"));
        if (location == null) {
            throw new MyQAuthenticationException("Could not login with credentials");
        }
        // finally complete the oAuth flow and retrieve a JSON oAuth token response
        ContentResponse tokenResponse = getLoginToken(location, codeVerifier);
        String loginToken = tokenResponse.getContentAsString();
        AccessTokenResponse accessTokenResponse = gsonLowerCase.fromJson(loginToken, AccessTokenResponse.class);
        if (accessTokenResponse == null) {
            throw new MyQAuthenticationException("Could not parse token response");
        }
        getOAuthService().importAccessTokenResponse(accessTokenResponse);
        return accessTokenResponse;
    } catch (IOException | ExecutionException | TimeoutException | OAuthException | URISyntaxException e) {
        throw new MyQCommunicationException(e.getMessage());
    }
}
Also used : HttpContentResponse(org.eclipse.jetty.client.HttpContentResponse) ContentResponse(org.eclipse.jetty.client.api.ContentResponse) Element(org.jsoup.nodes.Element) OAuthException(org.openhab.core.auth.client.oauth2.OAuthException) IOException(java.io.IOException) URISyntaxException(java.net.URISyntaxException) Document(org.jsoup.nodes.Document) URI(java.net.URI) CookieStore(java.net.CookieStore) ExecutionException(java.util.concurrent.ExecutionException) AccessTokenResponse(org.openhab.core.auth.client.oauth2.AccessTokenResponse) TimeoutException(java.util.concurrent.TimeoutException)

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