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());
}
}
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);
}
}
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>");
}
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);
}
}
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;
}
Aggregations