Search in sources :

Example 31 with OAuthResponseException

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

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.debug("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.openhab.core.auth.client.oauth2.OAuthResponseException) ContentResponse(org.eclipse.jetty.client.api.ContentResponse) PrivilegedActionException(java.security.PrivilegedActionException) OAuthException(org.openhab.core.auth.client.oauth2.OAuthException) Request(org.eclipse.jetty.client.api.Request) IOException(java.io.IOException) OAuthException(org.openhab.core.auth.client.oauth2.OAuthException) TimeoutException(java.util.concurrent.TimeoutException) PrivilegedActionException(java.security.PrivilegedActionException) OAuthResponseException(org.openhab.core.auth.client.oauth2.OAuthResponseException) JsonSyntaxException(com.google.gson.JsonSyntaxException) IOException(java.io.IOException) InvocationTargetException(java.lang.reflect.InvocationTargetException) ExecutionException(java.util.concurrent.ExecutionException) JsonSyntaxException(com.google.gson.JsonSyntaxException) ExecutionException(java.util.concurrent.ExecutionException) AccessTokenResponse(org.openhab.core.auth.client.oauth2.AccessTokenResponse) TimeoutException(java.util.concurrent.TimeoutException)

Example 32 with OAuthResponseException

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

the class AbstractTestAgent method testRefreshToken.

@Override
public AccessTokenResponse testRefreshToken() throws OAuthException, IOException, OAuthResponseException {
    logger.debug("test RefreshToken");
    AccessTokenResponse newRefreshedToken = oauthClientService.refreshToken();
    return newRefreshedToken;
}
Also used : AccessTokenResponse(org.openhab.core.auth.client.oauth2.AccessTokenResponse)

Example 33 with OAuthResponseException

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

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.openhab.core.auth.client.oauth2.OAuthResponseException) OAuthClientService(org.openhab.core.auth.client.oauth2.OAuthClientService) AbstractTestAgent(org.openhab.core.auth.oauth2client.test.internal.AbstractTestAgent) 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