use of com.microsoft.identity.common.internal.providers.oauth2.TokenResponse in project cyberduck by iterate-ch.
the class FreenetAuthenticatedUrlProvider method toUrl.
@Override
public DescriptiveUrl toUrl(final Host bookmark) {
try {
// Run password flow
final TokenResponse response;
try {
final Host target = new Host(new DAVSSLProtocol(), "oauth.freenet.de");
final X509TrustManager trust = new KeychainX509TrustManager(new DisabledCertificateTrustCallback(), new DefaultTrustManagerHostnameCallback(target), CertificateStoreFactory.get());
final X509KeyManager key = new KeychainX509KeyManager(new DisabledCertificateIdentityCallback(), target, CertificateStoreFactory.get());
final CloseableHttpClient client = new HttpConnectionPoolBuilder(target, new ThreadLocalHostnameDelegatingTrustManager(trust, target.getHostname()), key, ProxyFactory.get()).build(ProxyFactory.get().find(new ProxyHostUrlProvider().get(target)), new DisabledTranscriptListener(), new DisabledLoginCallback()).setUserAgent(new FreenetUserAgentProvider().get()).build();
final String username = bookmark.getCredentials().getUsername();
final String password;
if (StringUtils.isBlank(bookmark.getCredentials().getPassword())) {
password = PasswordStoreFactory.get().findLoginPassword(bookmark);
} else {
password = bookmark.getCredentials().getPassword();
}
response = new PasswordTokenRequest(new ApacheHttpTransport(client), new GsonFactory(), new GenericUrl("https://oauth.freenet.de/oauth/token"), username, password).setClientAuthentication(new BasicAuthentication("desktop_client", "6LIGIHuOSkznLomu5xw0EPPBJOXb2jLp")).setRequestInitializer(new UserAgentHttpRequestInitializer(new FreenetUserAgentProvider())).set("world", new HostPreferences(bookmark).getProperty("world")).set("webLogin", Boolean.TRUE).execute();
final FreenetTemporaryLoginResponse login = this.getLoginSession(client, response.getAccessToken());
return new DescriptiveUrl(URI.create(login.urls.login), DescriptiveUrl.Type.authenticated);
} catch (IOException e) {
throw new HttpExceptionMappingService().map(e);
}
} catch (BackgroundException e) {
log.warn(String.format("Failure %s retrieving authenticated URL for %s", e, bookmark));
return DescriptiveUrl.EMPTY;
}
}
use of com.microsoft.identity.common.internal.providers.oauth2.TokenResponse in project cyberduck by iterate-ch.
the class OAuth2AuthorizationService method refresh.
public OAuthTokens refresh(final OAuthTokens tokens) throws BackgroundException {
if (StringUtils.isBlank(tokens.getRefreshToken())) {
log.warn("Missing refresh token");
return tokens;
}
if (log.isDebugEnabled()) {
log.debug(String.format("Refresh expired tokens %s", tokens));
}
try {
final TokenResponse response = new RefreshTokenRequest(transport, json, new GenericUrl(tokenServerUrl), tokens.getRefreshToken()).setRequestInitializer(new UserAgentHttpRequestInitializer(new PreferencesUseragentProvider())).setClientAuthentication(new ClientParametersAuthentication(clientid, clientsecret)).executeUnparsed().parseAs(PermissiveTokenResponse.class).toTokenResponse();
final long expiryInMilliseconds = System.currentTimeMillis() + response.getExpiresInSeconds() * 1000;
if (StringUtils.isBlank(response.getRefreshToken())) {
return new OAuthTokens(response.getAccessToken(), tokens.getRefreshToken(), expiryInMilliseconds);
}
return new OAuthTokens(response.getAccessToken(), response.getRefreshToken(), expiryInMilliseconds);
} catch (TokenResponseException e) {
throw new OAuthExceptionMappingService().map(e);
} catch (HttpResponseException e) {
throw new DefaultHttpResponseExceptionMappingService().map(new org.apache.http.client.HttpResponseException(e.getStatusCode(), e.getStatusMessage()));
} catch (IOException e) {
throw new DefaultIOExceptionMappingService().map(e);
}
}
use of com.microsoft.identity.common.internal.providers.oauth2.TokenResponse in project devspaces-images by redhat-developer.
the class OAuthAuthenticator method callback.
/**
* Process callback request.
*
* @param requestUrl request URI. URI should contain authorization code generated by authorization
* server
* @param scopes specify exactly what type of access needed. This list must be exactly the same as
* list passed to the method {@link #getAuthenticateUrl(URL, java.util.List)}
* @return id of authenticated user
* @throws OAuthAuthenticationException if authentication failed or <code>requestUrl</code> does
* not contain required parameters, e.g. 'code'
*/
public String callback(URL requestUrl, List<String> scopes) throws OAuthAuthenticationException {
if (!isConfigured()) {
throw new OAuthAuthenticationException(AUTHENTICATOR_IS_NOT_CONFIGURED);
}
AuthorizationCodeResponseUrl authorizationCodeResponseUrl = new AuthorizationCodeResponseUrl(requestUrl.toString());
final String error = authorizationCodeResponseUrl.getError();
if (error != null) {
throw new OAuthAuthenticationException("Authentication failed: " + error);
}
final String code = authorizationCodeResponseUrl.getCode();
if (code == null) {
throw new OAuthAuthenticationException("Missing authorization code. ");
}
try {
TokenResponse tokenResponse = flow.newTokenRequest(code).setRequestInitializer(request -> {
if (request.getParser() == null) {
request.setParser(flow.getJsonFactory().createJsonObjectParser());
}
request.getHeaders().setAccept(MediaType.APPLICATION_JSON);
}).setRedirectUri(findRedirectUrl(requestUrl)).setScopes(scopes).execute();
String userId = getUserFromUrl(authorizationCodeResponseUrl);
if (userId == null) {
userId = EnvironmentContext.getCurrent().getSubject().getUserId();
}
flow.createAndStoreCredential(tokenResponse, userId);
return userId;
} catch (IOException ioe) {
throw new OAuthAuthenticationException(ioe.getMessage());
}
}
use of com.microsoft.identity.common.internal.providers.oauth2.TokenResponse in project sigstore-maven-plugin by sigstore.
the class Sign method getIDToken.
/**
* Obtains an OpenID Connect Identity Token from the OIDC provider specified in <code>oidcAuthURL</code>
*
* @param expectedEmailAddress The email address we expected to see in the identity token
* @return the ID token String (in JWS format)
* @throws MojoExecutionException If any exception happened during the OIDC authentication flow
*/
public String getIDToken(String expectedEmailAddress) throws MojoExecutionException {
try {
JsonFactory jsonFactory = new GsonFactory();
HttpTransport httpTransport = getHttpTransport();
DataStoreFactory memStoreFactory = new MemoryDataStoreFactory();
final String idTokenKey = "id_token";
if (!oidcDeviceCodeFlow) {
AuthorizationCodeFlow.Builder flowBuilder = new AuthorizationCodeFlow.Builder(BearerToken.authorizationHeaderAccessMethod(), httpTransport, jsonFactory, new GenericUrl(oidcTokenURL.toString()), new ClientParametersAuthentication(oidcClientID, null), oidcClientID, oidcAuthURL.toString()).enablePKCE().setScopes(List.of("openid", "email")).setCredentialCreatedListener(new AuthorizationCodeFlow.CredentialCreatedListener() {
@Override
public void onCredentialCreated(Credential credential, TokenResponse tokenResponse) throws IOException {
memStoreFactory.getDataStore("user").set(idTokenKey, tokenResponse.get(idTokenKey).toString());
}
});
AuthorizationCodeInstalledApp app = new AuthorizationCodeInstalledApp(flowBuilder.build(), new LocalServerReceiver());
app.authorize("user");
}
// TODO: add device code flow support
String idTokenString = (String) memStoreFactory.getDataStore("user").get(idTokenKey);
IdTokenVerifier idTokenVerifier = new IdTokenVerifier();
IdToken parsedIdToken = IdToken.parse(jsonFactory, idTokenString);
if (!idTokenVerifier.verify(parsedIdToken)) {
throw new InvalidObjectException("id token could not be verified");
}
String emailFromIDToken = (String) parsedIdToken.getPayload().get("email");
Boolean emailVerified = (Boolean) parsedIdToken.getPayload().get("email_verified");
if (expectedEmailAddress != null && !emailFromIDToken.equals(expectedEmailAddress)) {
throw new InvalidObjectException(String.format("email in ID token '%s' does not match address specified to plugin '%s'", emailFromIDToken, emailAddress));
} else if (Boolean.FALSE.equals(emailVerified)) {
throw new InvalidObjectException(String.format("identity provider '%s' reports email address '%s' has not been verified", parsedIdToken.getPayload().getIssuer(), emailAddress));
}
this.emailAddress = emailFromIDToken;
return idTokenString;
} catch (Exception e) {
throw new MojoExecutionException("Error signing email address:", e);
}
}
use of com.microsoft.identity.common.internal.providers.oauth2.TokenResponse in project urlaubsverwaltung by synyx.
the class GoogleCalendarSyncProvider method getOrCreateGoogleCalendarClient.
/**
* Build and return an authorized google calendar client.
*
* @return an authorized calendar client service
*/
private com.google.api.services.calendar.Calendar getOrCreateGoogleCalendarClient() {
String refreshToken = settingsService.getSettings().getCalendarSettings().getGoogleCalendarSettings().getRefreshToken();
if (googleCalendarClient != null && refreshToken != null && refreshTokenHashCode == refreshToken.hashCode()) {
LOG.debug("use cached googleCalendarClient");
return googleCalendarClient;
}
try {
LOG.info("create new googleCalendarClient");
if (refreshToken != null) {
refreshTokenHashCode = refreshToken.hashCode();
}
NetHttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
TokenResponse tokenResponse = new TokenResponse();
tokenResponse.setRefreshToken(refreshToken);
Credential credential = createCredentialWithRefreshToken(httpTransport, JSON_FACTORY, tokenResponse);
return new com.google.api.services.calendar.Calendar.Builder(httpTransport, JSON_FACTORY, credential).setApplicationName(APPLICATION_NAME).build();
} catch (GeneralSecurityException | IOException e) {
LOG.error("Something went wrong!", e);
}
return null;
}
Aggregations