use of com.tremolosecurity.proxy.auth.oauth2.AccessTokenResponse in project openhab-addons by openhab.
the class HydrawiseGraphQLClient method sendGraphQLRequest.
private String sendGraphQLRequest(String content) throws HydrawiseConnectionException, HydrawiseAuthenticationException {
logger.trace("Sending Request: {}", content);
ContentResponse response;
final AtomicInteger responseCode = new AtomicInteger(0);
final StringBuilder responseMessage = new StringBuilder();
try {
AccessTokenResponse token = oAuthService.getAccessTokenResponse();
if (token == null) {
throw new HydrawiseAuthenticationException("Login required");
}
response = httpClient.newRequest(GRAPH_URL).method(HttpMethod.POST).content(new StringContentProvider(content), "application/json").header("Authorization", token.getTokenType() + " " + token.getAccessToken()).onResponseFailure(new Response.FailureListener() {
@Override
public void onFailure(@Nullable Response response, @Nullable Throwable failure) {
int status = response != null ? response.getStatus() : -1;
String reason = response != null ? response.getReason() : "Null response";
logger.trace("onFailure code: {} message: {}", status, reason);
responseCode.set(status);
responseMessage.append(reason);
}
}).send();
String stringResponse = response.getContentAsString();
logger.trace("Received Response: {}", stringResponse);
return stringResponse;
} catch (InterruptedException | TimeoutException | OAuthException | IOException e) {
logger.debug("Could not send request", e);
throw new HydrawiseConnectionException(e);
} catch (OAuthResponseException e) {
throw new HydrawiseAuthenticationException(e.getMessage());
} catch (ExecutionException e) {
// this allows us to catch this in a callback and handle accordingly
switch(responseCode.get()) {
case 401:
case 403:
throw new HydrawiseAuthenticationException(responseMessage.toString());
default:
throw new HydrawiseConnectionException(e);
}
}
}
use of com.tremolosecurity.proxy.auth.oauth2.AccessTokenResponse in project openhab-addons by openhab.
the class SmartherBridgeHandler method isAuthorized.
@Override
public boolean isAuthorized() {
try {
final AccessTokenResponse tokenResponse = getAccessTokenResponse();
onAccessTokenResponse(tokenResponse);
return (tokenResponse != null && tokenResponse.getAccessToken() != null && tokenResponse.getRefreshToken() != null);
} catch (SmartherAuthorizationException e) {
return false;
}
}
use of com.tremolosecurity.proxy.auth.oauth2.AccessTokenResponse in project openhab-addons by openhab.
the class OpenHabOAuthTokenRefresherTest method whenTokenIsRefreshedAndNoAccessTokenIsProvidedThenTheListenerIsNotNotified.
@Test
public void whenTokenIsRefreshedAndNoAccessTokenIsProvidedThenTheListenerIsNotNotified() throws org.openhab.core.auth.client.oauth2.OAuthException, IOException, OAuthResponseException {
// given:
AccessTokenResponse accessTokenResponse = new AccessTokenResponse();
OAuthClientService oauthClientService = mock(OAuthClientService.class);
OAuthFactory oauthFactory = mock(OAuthFactory.class);
when(oauthFactory.getOAuthClientService(MieleCloudBindingTestConstants.SERVICE_HANDLE)).thenReturn(oauthClientService);
OpenHabOAuthTokenRefresher refresher = new OpenHabOAuthTokenRefresher(oauthFactory);
when(oauthClientService.refreshToken()).thenAnswer(new Answer<@Nullable AccessTokenResponse>() {
@Override
@Nullable
public AccessTokenResponse answer(@Nullable InvocationOnMock invocation) throws Throwable {
getAccessTokenRefreshListenerByServiceHandle(refresher, MieleCloudBindingTestConstants.SERVICE_HANDLE).onAccessTokenResponse(accessTokenResponse);
return accessTokenResponse;
}
});
OAuthTokenRefreshListener listener = mock(OAuthTokenRefreshListener.class);
refresher.setRefreshListener(listener, MieleCloudBindingTestConstants.SERVICE_HANDLE);
// when:
assertThrows(OAuthException.class, () -> {
try {
refresher.refreshToken(MieleCloudBindingTestConstants.SERVICE_HANDLE);
} catch (OAuthException e) {
verifyNoInteractions(listener);
throw e;
}
});
}
use of com.tremolosecurity.proxy.auth.oauth2.AccessTokenResponse in project openhab-addons by openhab.
the class MieleHandlerFactoryTest method setUp.
@BeforeEach
public void setUp() throws Exception {
registerVolatileStorageService();
thingRegistry = getService(ThingRegistry.class, ThingRegistry.class);
assertNotNull(thingRegistry, "Thing registry is missing");
// Ensure the MieleWebservice is not initialized.
MieleHandlerFactory factory = getService(ThingHandlerFactory.class, MieleHandlerFactory.class);
assertNotNull(factory);
// Assume an access token has already been stored
AccessTokenResponse accessTokenResponse = new AccessTokenResponse();
accessTokenResponse.setAccessToken(ACCESS_TOKEN);
OAuthClientService oAuthClientService = mock(OAuthClientService.class);
when(oAuthClientService.getAccessTokenResponse()).thenReturn(accessTokenResponse);
OAuthFactory oAuthFactory = mock(OAuthFactory.class);
when(oAuthFactory.getOAuthClientService(MieleCloudBindingIntegrationTestConstants.EMAIL)).thenReturn(oAuthClientService);
OpenHabOAuthTokenRefresher tokenRefresher = getService(OAuthTokenRefresher.class, OpenHabOAuthTokenRefresher.class);
assertNotNull(tokenRefresher);
setPrivate(Objects.requireNonNull(tokenRefresher), "oauthFactory", oAuthFactory);
}
use of com.tremolosecurity.proxy.auth.oauth2.AccessTokenResponse in project openhab-addons by openhab.
the class MyQAccountHandler method login.
/**
* This attempts to navigate the MyQ oAuth login flow in order to obtain a @AccessTokenResponse
*
* @return AccessTokenResponse token
* @throws InterruptedException
* @throws MyQCommunicationException
* @throws MyQAuthenticationException
*/
private AccessTokenResponse login() throws InterruptedException, MyQCommunicationException, MyQAuthenticationException {
try {
// make sure we have a fresh session
URI authUri = new URI(LOGIN_BASE_URL);
CookieStore store = httpClient.getCookieStore();
store.get(authUri).forEach(cookie -> {
store.remove(authUri, cookie);
});
String codeVerifier = generateCodeVerifier();
ContentResponse loginPageResponse = getLoginPage(codeVerifier);
// load the login page to get cookies and form parameters
Document loginPage = Jsoup.parse(loginPageResponse.getContentAsString());
Element form = loginPage.select("form").first();
Element requestToken = loginPage.select("input[name=__RequestVerificationToken]").first();
Element returnURL = loginPage.select("input[name=ReturnUrl]").first();
if (form == null || requestToken == null) {
throw new MyQCommunicationException("Could not load login page");
}
// url that the form will submit to
String action = LOGIN_BASE_URL + form.attr("action");
// post our user name and password along with elements from the scraped form
String location = postLogin(action, requestToken.attr("value"), returnURL.attr("value"));
if (location == null) {
throw new MyQAuthenticationException("Could not login with credentials");
}
// finally complete the oAuth flow and retrieve a JSON oAuth token response
ContentResponse tokenResponse = getLoginToken(location, codeVerifier);
String loginToken = tokenResponse.getContentAsString();
AccessTokenResponse accessTokenResponse = gsonLowerCase.fromJson(loginToken, AccessTokenResponse.class);
if (accessTokenResponse == null) {
throw new MyQAuthenticationException("Could not parse token response");
}
getOAuthService().importAccessTokenResponse(accessTokenResponse);
return accessTokenResponse;
} catch (IOException | ExecutionException | TimeoutException | OAuthException | URISyntaxException e) {
throw new MyQCommunicationException(e.getMessage());
}
}
Aggregations