Search in sources :

Example 1 with AccessTokenResponse

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

the class InnogyBridgeHandler method createWebSocket.

InnogyWebSocket createWebSocket() throws IOException, AuthenticationException {
    final AccessTokenResponse accessTokenResponse = client.getAccessTokenResponse();
    final String webSocketUrl = WEBSOCKET_API_URL_EVENTS.replace("{token}", accessTokenResponse.getAccessToken());
    logger.debug("WebSocket URL: {}...{}", webSocketUrl.substring(0, 70), webSocketUrl.substring(webSocketUrl.length() - 10));
    return new InnogyWebSocket(this, URI.create(webSocketUrl), bridgeConfiguration.websocketidletimeout * 1000);
}
Also used : InnogyWebSocket(org.openhab.binding.innogysmarthome.internal.InnogyWebSocket) AccessTokenResponse(org.openhab.core.auth.client.oauth2.AccessTokenResponse)

Example 2 with AccessTokenResponse

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

the class InnogyClientTest method before.

@BeforeEach
public void before() throws Exception {
    AccessTokenResponse accessTokenResponse = new AccessTokenResponse();
    accessTokenResponse.setAccessToken("accessToken");
    when(oAuthClient.getAccessTokenResponse()).thenReturn(accessTokenResponse);
    client = new InnogyClient(oAuthClient, httpClient);
}
Also used : AccessTokenResponse(org.openhab.core.auth.client.oauth2.AccessTokenResponse) BeforeEach(org.junit.jupiter.api.BeforeEach)

Example 3 with AccessTokenResponse

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

the class HomeConnectServlet method getBridgeAuthenticationPage.

private void getBridgeAuthenticationPage(HttpServletRequest request, HttpServletResponse response, String code, String state) throws IOException {
    // callback handling from authorization server
    logger.debug("[oAuth] redirect from authorization server (code={}, state={}).", code, state);
    Optional<HomeConnectBridgeHandler> bridgeHandler = getBridgeHandler(state);
    if (bridgeHandler.isPresent()) {
        try {
            AccessTokenResponse accessTokenResponse = bridgeHandler.get().getOAuthClientService().getAccessTokenResponseByAuthorizationCode(code, null);
            logger.debug("access token response: {}", accessTokenResponse);
            // inform bridge
            bridgeHandler.get().reinitialize();
            WebContext context = new WebContext(request, response, request.getServletContext());
            context.setVariable("action", bridgeHandler.get().getThing().getUID().getAsString() + ACTION_AUTHORIZE);
            context.setVariable("bridgeHandlers", bridgeHandlers);
            templateEngine.process("bridges", context, response.getWriter());
        } catch (OAuthException | OAuthResponseException e) {
            logger.error("Could not fetch token!", e);
            response.sendError(HttpStatus.INTERNAL_SERVER_ERROR_500, "Could not fetch token!");
        }
    } else {
        response.sendError(HttpStatus.BAD_REQUEST_400, "Unknown bridge");
    }
}
Also used : OAuthResponseException(org.openhab.core.auth.client.oauth2.OAuthResponseException) WebContext(org.thymeleaf.context.WebContext) OAuthException(org.openhab.core.auth.client.oauth2.OAuthException) HomeConnectBridgeHandler(org.openhab.binding.homeconnect.internal.handler.HomeConnectBridgeHandler) AccessTokenResponse(org.openhab.core.auth.client.oauth2.AccessTokenResponse)

Example 4 with AccessTokenResponse

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

the class HttpHelper method getAuthorizationHeader.

public static String getAuthorizationHeader(OAuthClientService oAuthClientService) throws AuthorizationException, CommunicationException {
    synchronized (AUTHORIZATION_HEADER_MONITOR) {
        try {
            AccessTokenResponse accessTokenResponse = oAuthClientService.getAccessTokenResponse();
            // refresh the token if it's about to expire
            if (accessTokenResponse != null && accessTokenResponse.isExpired(LocalDateTime.now(), OAUTH_EXPIRE_BUFFER)) {
                LoggerFactory.getLogger(HttpHelper.class).debug("Requesting a refresh of the access token.");
                accessTokenResponse = oAuthClientService.refreshToken();
            }
            if (accessTokenResponse != null) {
                String lastToken = lastAccessToken;
                if (lastToken == null) {
                    LoggerFactory.getLogger(HttpHelper.class).debug("The used access token was created at {}", accessTokenResponse.getCreatedOn().format(DateTimeFormatter.ISO_LOCAL_DATE_TIME));
                } else if (!lastToken.equals(accessTokenResponse.getAccessToken())) {
                    LoggerFactory.getLogger(HttpHelper.class).debug("The access token changed. New one created at {}", accessTokenResponse.getCreatedOn().format(DateTimeFormatter.ISO_LOCAL_DATE_TIME));
                }
                lastAccessToken = accessTokenResponse.getAccessToken();
                LoggerFactory.getLogger(HttpHelper.class).debug("Current access token: {}", accessTokenResponse.getAccessToken());
                return BEARER + accessTokenResponse.getAccessToken();
            } else {
                LoggerFactory.getLogger(HttpHelper.class).error("No access token available! Fatal error.");
                throw new AuthorizationException("No access token available!");
            }
        } catch (IOException e) {
            String errorMessage = e.getMessage();
            throw new CommunicationException(errorMessage != null ? errorMessage : "IOException", e);
        } catch (OAuthException | OAuthResponseException e) {
            String errorMessage = e.getMessage();
            throw new AuthorizationException(errorMessage != null ? errorMessage : "oAuth exception", e);
        }
    }
}
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) AccessTokenResponse(org.openhab.core.auth.client.oauth2.AccessTokenResponse)

Example 5 with AccessTokenResponse

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

the class EcobeeApi method isAuthorized.

/**
 * Check to see if the Ecobee authorization process is complete. This will be determined
 * by requesting an AccessTokenResponse from the OHC OAuth service. If we get a valid
 * response, then assume that the Ecobee authorization process is complete. Otherwise,
 * start the Ecobee authorization process.
 */
private boolean isAuthorized() {
    boolean isAuthorized = false;
    try {
        AccessTokenResponse localAccessTokenResponse = oAuthClientService.getAccessTokenResponse();
        if (localAccessTokenResponse != null) {
            logger.trace("API: Got AccessTokenResponse from OAuth service: {}", localAccessTokenResponse);
            if (localAccessTokenResponse.isExpired(LocalDateTime.now(), TOKEN_EXPIRES_IN_BUFFER_SECONDS)) {
                logger.debug("API: Token is expiring soon. Refresh it now");
                localAccessTokenResponse = oAuthClientService.refreshToken();
            }
            ecobeeAuth.setState(EcobeeAuthState.COMPLETE);
            isAuthorized = true;
        } else {
            logger.debug("API: Didn't get an AccessTokenResponse from OAuth service - doEcobeeAuthorization!!!");
            if (ecobeeAuth.isComplete()) {
                ecobeeAuth.setState(EcobeeAuthState.NEED_PIN);
            }
        }
        accessTokenResponse = localAccessTokenResponse;
        ecobeeAuth.doAuthorization();
    } catch (OAuthException | IOException | RuntimeException e) {
        if (logger.isDebugEnabled()) {
            logger.warn("API: Got exception trying to get access token from OAuth service", e);
        } else {
            logger.warn("API: Got {} trying to get access token from OAuth service: {}", e.getClass().getSimpleName(), e.getMessage());
        }
    } catch (EcobeeAuthException e) {
        if (logger.isDebugEnabled()) {
            logger.warn("API: The Ecobee authorization process threw an exception", e);
        } else {
            logger.warn("API: The Ecobee authorization process threw an exception: {}", e.getMessage());
        }
        ecobeeAuth.setState(EcobeeAuthState.NEED_PIN);
    } catch (OAuthResponseException e) {
        handleOAuthException(e);
    }
    return isAuthorized;
}
Also used : 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)

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