Search in sources :

Example 11 with AccessTokenResponse

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

the class MyQAccountHandler method sendRequest.

private synchronized ContentResponse sendRequest(String url, HttpMethod method, @Nullable ContentProvider content, @Nullable String contentType) throws InterruptedException, MyQCommunicationException, MyQAuthenticationException {
    AccessTokenResponse tokenResponse = null;
    // if we don't need to force a login, attempt to use the token we have
    if (!needsLogin) {
        try {
            tokenResponse = getOAuthService().getAccessTokenResponse();
        } catch (OAuthException | IOException | OAuthResponseException e) {
            // ignore error, will try to login below
            logger.debug("Error accessing token, will attempt to login again", e);
        }
    }
    // if no token, or we need to login, do so now
    if (tokenResponse == null) {
        tokenResponse = login();
        needsLogin = false;
    }
    Request request = httpClient.newRequest(url).method(method).agent(userAgent).timeout(10, TimeUnit.SECONDS).header("Authorization", authTokenHeader(tokenResponse));
    if (content != null & contentType != null) {
        request = request.content(content, contentType);
    }
    // use asyc jetty as the API service will response with a 401 error when credentials are wrong,
    // but not a WWW-Authenticate header which causes Jetty to throw a generic execution exception which
    // prevents us from knowing the response code
    logger.trace("Sending {} to {}", request.getMethod(), request.getURI());
    final CompletableFuture<ContentResponse> futureResult = new CompletableFuture<>();
    request.send(new BufferingResponseListener() {

        @NonNullByDefault({})
        @Override
        public void onComplete(Result result) {
            Response response = result.getResponse();
            futureResult.complete(new HttpContentResponse(response, getContent(), getMediaType(), getEncoding()));
        }
    });
    try {
        ContentResponse result = futureResult.get();
        logger.trace("Account Response - status: {} content: {}", result.getStatus(), result.getContentAsString());
        return result;
    } catch (ExecutionException e) {
        throw new MyQCommunicationException(e.getMessage());
    }
}
Also used : OAuthResponseException(org.openhab.core.auth.client.oauth2.OAuthResponseException) NonNullByDefault(org.eclipse.jdt.annotation.NonNullByDefault) HttpContentResponse(org.eclipse.jetty.client.HttpContentResponse) ContentResponse(org.eclipse.jetty.client.api.ContentResponse) OAuthException(org.openhab.core.auth.client.oauth2.OAuthException) Request(org.eclipse.jetty.client.api.Request) IOException(java.io.IOException) Result(org.eclipse.jetty.client.api.Result) HttpContentResponse(org.eclipse.jetty.client.HttpContentResponse) ContentResponse(org.eclipse.jetty.client.api.ContentResponse) Response(org.eclipse.jetty.client.api.Response) AccessTokenResponse(org.openhab.core.auth.client.oauth2.AccessTokenResponse) CompletableFuture(java.util.concurrent.CompletableFuture) ExecutionException(java.util.concurrent.ExecutionException) AccessTokenResponse(org.openhab.core.auth.client.oauth2.AccessTokenResponse) HttpContentResponse(org.eclipse.jetty.client.HttpContentResponse) BufferingResponseListener(org.eclipse.jetty.client.util.BufferingResponseListener)

Example 12 with AccessTokenResponse

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

the class SpotifyBridgeHandler method authorize.

@Override
public String authorize(String redirectUri, String reqCode) {
    try {
        logger.debug("Make call to Spotify to get access token.");
        final AccessTokenResponse credentials = oAuthService.getAccessTokenResponseByAuthorizationCode(reqCode, redirectUri);
        final String user = updateProperties(credentials);
        logger.debug("Authorized for user: {}", user);
        startPolling();
        return user;
    } catch (RuntimeException | OAuthException | IOException e) {
        updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, e.getMessage());
        throw new SpotifyException(e.getMessage(), e);
    } catch (final OAuthResponseException e) {
        throw new SpotifyAuthorizationException(e.getMessage(), e);
    }
}
Also used : SpotifyException(org.openhab.binding.spotify.internal.api.exception.SpotifyException) 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) SpotifyAuthorizationException(org.openhab.binding.spotify.internal.api.exception.SpotifyAuthorizationException)

Example 13 with AccessTokenResponse

use of com.tremolosecurity.proxy.auth.oauth2.AccessTokenResponse in project OpenUnison by TremoloSecurity.

the class LastMileJSON method doFilter.

@Override
public void doFilter(HttpFilterRequest request, HttpFilterResponse response, HttpFilterChain chain) throws Exception {
    chain.setNoProxy(true);
    ConfigManager cfgMgr = (ConfigManager) request.getAttribute(ProxyConstants.TREMOLO_CFG_OBJ);
    PrintWriter out = response.getWriter();
    out.println("<html><head>");
    out.println("<script type=\"text/javascript\">");
    out.println("     function onBodyLoad() {");
    out.println("          var element = document.getElementById(\"json\");");
    // out.println("          alert(element.innerHTML);");
    out.println("          window.javascriptAccessor.setJSON(element.innerHTML);");
    out.println("     }");
    out.println("</script></head><body onload=\"onBodyLoad()\">");
    out.print("<div id=\"json\">");
    DateTime notBefore = new DateTime().minusSeconds(secondsScew);
    DateTime notAfter = new DateTime().plusSeconds(secondsToLive);
    AuthController actl = (AuthController) request.getSession().getAttribute(ProxyConstants.AUTH_CTL);
    com.tremolosecurity.lastmile.LastMile lmreq = new com.tremolosecurity.lastmile.LastMile(request.getRequestURI(), notBefore, notAfter, 1, "chainName");
    lmreq.getAttributes().add(new Attribute("dn", actl.getAuthInfo().getUserDN()));
    AccessTokenResponse resp = new AccessTokenResponse();
    resp.setAccess_token(lmreq.generateLastMileToken(cfgMgr.getSecretKey(encKeyAlias)));
    resp.setToken_type("bearer");
    resp.setExpires_in(this.secondsToLive);
    Gson gson = new Gson();
    out.print(gson.toJson(resp));
    out.print("</div></body></html>");
}
Also used : Attribute(com.tremolosecurity.saml.Attribute) Gson(com.google.gson.Gson) AuthController(com.tremolosecurity.proxy.auth.AuthController) AccessTokenResponse(com.tremolosecurity.proxy.auth.oauth2.AccessTokenResponse) ConfigManager(com.tremolosecurity.config.util.ConfigManager) DateTime(org.joda.time.DateTime) PrintWriter(java.io.PrintWriter)

Example 14 with AccessTokenResponse

use of com.tremolosecurity.proxy.auth.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 15 with AccessTokenResponse

use of com.tremolosecurity.proxy.auth.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)

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