Search in sources :

Example 1 with OAuthResponseException

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

the class OAuthConnector method doRequest.

private AccessTokenResponse doRequest(final String grantType, HttpClient httpClient, final Request request, Fields fields) throws OAuthResponseException, OAuthException, IOException {
    int statusCode = 0;
    String content = "";
    try {
        final FormContentProvider entity = new FormContentProvider(fields);
        final ContentResponse response = AccessController.doPrivileged((PrivilegedExceptionAction<ContentResponse>) () -> {
            Request requestWithContent = request.content(entity);
            return requestWithContent.send();
        });
        statusCode = response.getStatus();
        content = response.getContentAsString();
        if (statusCode == HttpStatus.OK_200) {
            AccessTokenResponse jsonResponse = gson.fromJson(content, AccessTokenResponse.class);
            // this is not supplied by the response
            jsonResponse.setCreatedOn(LocalDateTime.now());
            logger.info("grant type {} to URL {} success", grantType, request.getURI());
            return jsonResponse;
        } else if (statusCode == HttpStatus.BAD_REQUEST_400) {
            OAuthResponseException errorResponse = gson.fromJson(content, OAuthResponseException.class);
            logger.error("grant type {} to URL {} failed with error code {}, description {}", grantType, request.getURI(), errorResponse.getError(), errorResponse.getErrorDescription());
            throw errorResponse;
        } else {
            logger.error("grant type {} to URL {} failed with HTTP response code {}", grantType, request.getURI(), statusCode);
            throw new OAuthException("Bad http response, http code " + statusCode);
        }
    } catch (PrivilegedActionException pae) {
        Exception underlyingException = pae.getException();
        if (underlyingException instanceof InterruptedException || underlyingException instanceof TimeoutException || underlyingException instanceof ExecutionException) {
            throw new IOException("Exception in oauth communication, grant type " + grantType, underlyingException);
        }
        // Dont know what exception it is, wrap it up and throw it out
        throw new OAuthException("Exception in oauth communication, grant type " + grantType, underlyingException);
    } catch (JsonSyntaxException e) {
        throw new OAuthException(String.format("Unable to deserialize json into AccessTokenResponse/ OAuthResponseException. httpCode: %i json: %s", statusCode, content), e);
    }
}
Also used : FormContentProvider(org.eclipse.jetty.client.util.FormContentProvider) OAuthResponseException(org.eclipse.smarthome.core.auth.client.oauth2.OAuthResponseException) ContentResponse(org.eclipse.jetty.client.api.ContentResponse) PrivilegedActionException(java.security.PrivilegedActionException) OAuthException(org.eclipse.smarthome.core.auth.client.oauth2.OAuthException) Request(org.eclipse.jetty.client.api.Request) IOException(java.io.IOException) OAuthResponseException(org.eclipse.smarthome.core.auth.client.oauth2.OAuthResponseException) TimeoutException(java.util.concurrent.TimeoutException) PrivilegedActionException(java.security.PrivilegedActionException) JsonSyntaxException(com.google.gson.JsonSyntaxException) IOException(java.io.IOException) OAuthException(org.eclipse.smarthome.core.auth.client.oauth2.OAuthException) ExecutionException(java.util.concurrent.ExecutionException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) JsonSyntaxException(com.google.gson.JsonSyntaxException) ExecutionException(java.util.concurrent.ExecutionException) AccessTokenResponse(org.eclipse.smarthome.core.auth.client.oauth2.AccessTokenResponse) TimeoutException(java.util.concurrent.TimeoutException)

Example 2 with OAuthResponseException

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

the class ConsoleOAuthCommandExtension method execute.

@Override
public void execute(String[] args, Console console) {
    this.console = console;
    if (args.length < 2) {
        console.println("Argument expected.  Please check usage.");
        return;
    }
    AbstractTestAgent agent = getTestAgent(args[0]);
    if (agent == null) {
        console.println("Unexpected test agent:" + args[0]);
        return;
    }
    AccessTokenResponse response;
    try {
        switch(args[1]) {
            case "create":
                OAuthClientService newService = agent.testCreateClient();
                console.println("handle: " + agent.handle + ", service: " + newService);
                break;
            case "getAccessTokenByResourceOwnerPassword":
                response = agent.testGetAccessTokenByResourceOwnerPasswordCredentials();
                consolePrintAccessToken(response);
                break;
            case "getClient":
                OAuthClientService service = agent.testGetClient(args[2]);
                console.println("OAuthClientService: " + service);
                break;
            case "refresh":
                response = agent.testRefreshToken();
                consolePrintAccessToken(response);
                break;
            case "getAccessTokenByCode":
                console.println("using authorization code: " + args[2]);
                response = agent.testGetAccessTokenByAuthorizationCode(args[2]);
                consolePrintAccessToken(response);
                break;
            case "getAuthorizationUrl":
                String authURL;
                if (args.length >= 3) {
                    authURL = agent.testGetAuthorizationUrl(args[2]);
                    console.println("Authorization URL: " + authURL + " state: " + args[2]);
                } else {
                    authURL = agent.testGetAuthorizationUrl(null);
                    console.println("Authorization URL: " + authURL + " state: null");
                }
                break;
            case "getCachedAccessToken":
                response = agent.testGetCachedAccessToken();
                consolePrintAccessToken(response);
                break;
            case "close":
                console.println("Closing test agent client service...");
                agent.close();
                break;
            case "delete":
                console.println("Delete by handle: " + args[2]);
                agent.delete(args[2]);
                break;
            default:
                console.println("Commands are case-sensitive.  Unknown command: " + args[1]);
                break;
        }
    } catch (OAuthException | IOException | OAuthResponseException e) {
        console.print(String.format("%s %s, cause %s", e.getClass(), e.getMessage(), e.getCause()));
    }
}
Also used : OAuthResponseException(org.eclipse.smarthome.core.auth.client.oauth2.OAuthResponseException) OAuthClientService(org.eclipse.smarthome.core.auth.client.oauth2.OAuthClientService) AbstractTestAgent(org.eclipse.smarthome.auth.oauth2client.test.internal.AbstractTestAgent) OAuthException(org.eclipse.smarthome.core.auth.client.oauth2.OAuthException) IOException(java.io.IOException) AccessTokenResponse(org.eclipse.smarthome.core.auth.client.oauth2.AccessTokenResponse)

Example 3 with OAuthResponseException

use of org.openhab.core.auth.client.oauth2.OAuthResponseException 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 OAuthResponseException

use of org.openhab.core.auth.client.oauth2.OAuthResponseException 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 OAuthResponseException

use of org.openhab.core.auth.client.oauth2.OAuthResponseException 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)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