Search in sources :

Example 1 with AccessTokenResponse

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

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

the class OAuthClientServiceImpl method getAccessTokenResponseByAuthorizationCode.

@Override
public AccessTokenResponse getAccessTokenResponseByAuthorizationCode(String authorizationCode, String redirectURI) throws OAuthException, IOException, OAuthResponseException {
    if (isClosed()) {
        throw new OAuthException(EXCEPTION_MESSAGE_CLOSED);
    }
    if (persistedParams.redirectUri != null && !persistedParams.redirectUri.equals(redirectURI)) {
        // check parameter redirectURI in #getAuthorizationUrl are the same as given
        throw new OAuthException(String.format("redirectURI should be the same from previous call #getAuthorizationUrl.  Expected: %s Found: %s", persistedParams.redirectUri, redirectURI));
    }
    String tokenUrl = persistedParams.tokenUrl;
    if (tokenUrl == null) {
        throw new OAuthException("Missing token url");
    }
    String clientId = persistedParams.clientId;
    if (clientId == null) {
        throw new OAuthException("Missing client ID");
    }
    OAuthConnector connector = new OAuthConnector(httpClientFactory);
    AccessTokenResponse accessTokenResponse = connector.grantTypeAuthorizationCode(tokenUrl, authorizationCode, clientId, persistedParams.clientSecret, redirectURI, Boolean.TRUE.equals(persistedParams.supportsBasicAuth));
    // store it
    storeHandler.saveAccessTokenResponse(handle, accessTokenResponse);
    return accessTokenResponse;
}
Also used : OAuthException(org.eclipse.smarthome.core.auth.client.oauth2.OAuthException) AccessTokenResponse(org.eclipse.smarthome.core.auth.client.oauth2.AccessTokenResponse)

Example 3 with AccessTokenResponse

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

the class OAuthClientServiceImpl method getAccessTokenByResourceOwnerPasswordCredentials.

@Override
public AccessTokenResponse getAccessTokenByResourceOwnerPasswordCredentials(String username, String password, @Nullable String scope) throws OAuthException, IOException, OAuthResponseException {
    if (isClosed()) {
        throw new OAuthException(EXCEPTION_MESSAGE_CLOSED);
    }
    String tokenUrl = persistedParams.tokenUrl;
    if (tokenUrl == null) {
        throw new OAuthException("Missing token url");
    }
    OAuthConnector connector = new OAuthConnector(httpClientFactory);
    AccessTokenResponse accessTokenResponse = connector.grantTypePassword(tokenUrl, username, password, persistedParams.clientId, persistedParams.clientSecret, scope, Boolean.TRUE.equals(persistedParams.supportsBasicAuth));
    // store it
    storeHandler.saveAccessTokenResponse(handle, accessTokenResponse);
    return accessTokenResponse;
}
Also used : OAuthException(org.eclipse.smarthome.core.auth.client.oauth2.OAuthException) AccessTokenResponse(org.eclipse.smarthome.core.auth.client.oauth2.AccessTokenResponse)

Example 4 with AccessTokenResponse

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

the class OAuthClientServiceImpl method getAccessTokenByClientCredentials.

@Override
public AccessTokenResponse getAccessTokenByClientCredentials(@Nullable String scope) throws OAuthException, IOException, OAuthResponseException {
    if (isClosed()) {
        throw new OAuthException(EXCEPTION_MESSAGE_CLOSED);
    }
    String tokenUrl = persistedParams.tokenUrl;
    if (tokenUrl == null) {
        throw new OAuthException("Missing token url");
    }
    String clientId = persistedParams.clientId;
    if (clientId == null) {
        throw new OAuthException("Missing client ID");
    }
    OAuthConnector connector = new OAuthConnector(httpClientFactory);
    // depending on usage, cannot guarantee every parameter is not null at the beginning
    AccessTokenResponse accessTokenResponse = connector.grantTypeClientCredentials(tokenUrl, clientId, persistedParams.clientSecret, scope, Boolean.TRUE.equals(persistedParams.supportsBasicAuth));
    // store it
    storeHandler.saveAccessTokenResponse(handle, accessTokenResponse);
    return accessTokenResponse;
}
Also used : OAuthException(org.eclipse.smarthome.core.auth.client.oauth2.OAuthException) AccessTokenResponse(org.eclipse.smarthome.core.auth.client.oauth2.AccessTokenResponse)

Example 5 with AccessTokenResponse

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

the class OAuthClientServiceImpl method refreshToken.

@Override
public AccessTokenResponse refreshToken() throws OAuthException, IOException, OAuthResponseException {
    if (isClosed()) {
        throw new OAuthException(EXCEPTION_MESSAGE_CLOSED);
    }
    AccessTokenResponse lastAccessToken;
    try {
        lastAccessToken = storeHandler.loadAccessTokenResponse(handle);
    } catch (GeneralSecurityException e) {
        throw new OAuthException("Cannot decrypt access token from store", e);
    }
    if (lastAccessToken == null) {
        throw new OAuthException("Cannot refresh token because last access token is not available from handle: " + handle);
    }
    if (lastAccessToken.getRefreshToken() == null) {
        throw new OAuthException("Cannot refresh token because last access token did not have a refresh token");
    }
    String tokenUrl = persistedParams.tokenUrl;
    if (tokenUrl == null) {
        throw new OAuthException("tokenUrl is required but null");
    }
    OAuthConnector connector = new OAuthConnector(httpClientFactory);
    AccessTokenResponse accessTokenResponse = connector.grantTypeRefreshToken(tokenUrl, lastAccessToken.getRefreshToken(), persistedParams.clientId, persistedParams.clientSecret, persistedParams.scope, Boolean.TRUE.equals(persistedParams.supportsBasicAuth));
    // The service may not return the refresh token so use the last refresh token otherwise it's not stored.
    if (StringUtil.isBlank(accessTokenResponse.getRefreshToken())) {
        accessTokenResponse.setRefreshToken(lastAccessToken.getRefreshToken());
    }
    // store it
    storeHandler.saveAccessTokenResponse(handle, accessTokenResponse);
    accessTokenRefreshListeners.forEach(l -> l.onAccessTokenResponse(accessTokenResponse));
    return accessTokenResponse;
}
Also used : OAuthException(org.eclipse.smarthome.core.auth.client.oauth2.OAuthException) GeneralSecurityException(java.security.GeneralSecurityException) AccessTokenResponse(org.eclipse.smarthome.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