use of com.google.api.client.auth.oauth2.AuthorizationCodeResponseUrl in project che by eclipse.
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 = getUser(newDto(OAuthToken.class).withToken(tokenResponse.getAccessToken())).getId();
}
flow.createAndStoreCredential(tokenResponse, userId);
return userId;
} catch (IOException ioe) {
throw new OAuthAuthenticationException(ioe.getMessage());
}
}
use of com.google.api.client.auth.oauth2.AuthorizationCodeResponseUrl in project OpenRefine by OpenRefine.
the class GoogleAPIExtension method getTokenFromCode.
public static String getTokenFromCode(ButterflyModule module, HttpServletRequest request) throws IOException {
String redirectUrl = makeRedirectUrl(module, request);
StringBuffer fullUrlBuf = request.getRequestURL();
if (request.getQueryString() != null) {
fullUrlBuf.append('?').append(request.getQueryString());
}
AuthorizationCodeResponseUrl authResponse = new AuthorizationCodeResponseUrl(fullUrlBuf.toString());
// check for user-denied error
if (authResponse.getError() != null) {
// authorization denied...
} else {
// request access token using authResponse.getCode()...
String code = authResponse.getCode();
GoogleTokenResponse response = new GoogleAuthorizationCodeTokenRequest(HTTP_TRANSPORT, JSON_FACTORY, CLIENT_ID, CLIENT_SECRET, code, redirectUrl).execute();
String tokenAndExpiresInSeconds = response.getAccessToken() + "," + response.getExpiresInSeconds();
return tokenAndExpiresInSeconds;
}
return null;
}
use of com.google.api.client.auth.oauth2.AuthorizationCodeResponseUrl in project OpenRefine by OpenRefine.
the class GDataExtension method getTokenFromCode.
public static String getTokenFromCode(ButterflyModule module, HttpServletRequest request) throws MalformedURLException {
String redirectUrl = makeRedirectUrl(module, request);
StringBuffer fullUrlBuf = request.getRequestURL();
if (request.getQueryString() != null) {
fullUrlBuf.append('?').append(request.getQueryString());
}
AuthorizationCodeResponseUrl authResponse = new AuthorizationCodeResponseUrl(fullUrlBuf.toString());
// check for user-denied error
if (authResponse.getError() != null) {
// authorization denied...
} else {
// request access token using authResponse.getCode()...
String code = authResponse.getCode();
try {
GoogleTokenResponse response = new GoogleAuthorizationCodeTokenRequest(HTTP_TRANSPORT, JSON_FACTORY, CLIENT_ID, CLIENT_SECRET, code, redirectUrl).execute();
String token = response.getAccessToken();
return token;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return null;
}
use of com.google.api.client.auth.oauth2.AuthorizationCodeResponseUrl in project data-transfer-project by google.
the class Oauth2CallbackHandler method handleExchange.
private String handleExchange(HttpExchange exchange) throws IOException {
String redirect = "/error";
try {
Headers requestHeaders = exchange.getRequestHeaders();
String requestURL = ReferenceApiUtils.createURL(requestHeaders.getFirst(HttpHeaders.HOST), exchange.getRequestURI().toString(), IS_LOCAL);
AuthorizationCodeResponseUrl authResponse = new AuthorizationCodeResponseUrl(requestURL);
// check for user-denied error
if (authResponse.getError() != null) {
logger.warn("Authorization DENIED: {} Redirecting to /error", authResponse.getError());
return redirect;
}
// retrieve cookie from exchange
Map<String, HttpCookie> httpCookies = ReferenceApiUtils.getCookies(requestHeaders);
HttpCookie encodedIdCookie = httpCookies.get(JsonKeys.ID_COOKIE_KEY);
Preconditions.checkArgument(encodedIdCookie != null && !Strings.isNullOrEmpty(encodedIdCookie.getValue()), "Encoded Id cookie required");
UUID jobId = ReferenceApiUtils.decodeJobId(encodedIdCookie.getValue());
logger.debug("State token: {}", authResponse.getState());
// TODO(#258): Check job ID in state token, was broken during local demo
// UUID jobIdFromState = ReferenceApiUtils.decodeJobId(authResponse.getState());
// // TODO: Remove sanity check
// Preconditions.checkState(
// jobIdFromState.equals(jobId),
// "Job id in cookie [%s] and request [%s] should match",
// jobId,
// jobIdFromState);
PortabilityJob job = store.findJob(jobId);
Preconditions.checkNotNull(job, "existing job not found for jobId: %s", jobId);
// TODO: Determine service from job or from authUrl path?
AuthMode authMode = ReferenceApiUtils.getAuthMode(exchange.getRequestHeaders());
String service = (authMode == AuthMode.EXPORT) ? job.exportService() : job.importService();
Preconditions.checkState(!Strings.isNullOrEmpty(service), "service not found, service: %s authMode: %s, jobId: %s", service, authMode, jobId.toString());
AuthDataGenerator generator = registry.getAuthDataGenerator(service, job.transferDataType(), authMode);
Preconditions.checkNotNull(generator, "Generator not found for type: %s, service: %s", job.transferDataType(), service);
// Obtain the session key for this job
String encodedSessionKey = job.jobAuthorization().sessionSecretKey();
SecretKey key = symmetricKeyGenerator.parse(BaseEncoding.base64Url().decode(encodedSessionKey));
// Retrieve initial auth data, if it existed
AuthData initialAuthData = null;
String encryptedInitialAuthData = (authMode == AuthMode.EXPORT) ? job.jobAuthorization().encryptedInitialExportAuthData() : job.jobAuthorization().encryptedInitialImportAuthData();
if (encryptedInitialAuthData != null) {
// Retrieve and parse the session key from the job
// Decrypt and deserialize the object
String serialized = DecrypterFactory.create(key).decrypt(encryptedInitialAuthData);
initialAuthData = objectMapper.readValue(serialized, AuthData.class);
}
// TODO: Use UUID instead of UUID.toString()
// Generate auth data
AuthData authData = generator.generateAuthData(baseApiUrl, authResponse.getCode(), jobId.toString(), initialAuthData, null);
Preconditions.checkNotNull(authData, "Auth data should not be null");
// Serialize and encrypt the auth data
String serialized = objectMapper.writeValueAsString(authData);
String encryptedAuthData = EncrypterFactory.create(key).encrypt(serialized);
// Set new cookie
ReferenceApiUtils.setCookie(exchange.getResponseHeaders(), encryptedAuthData, authMode);
redirect = baseUrl + ((authMode == AuthMode.EXPORT) ? FrontendConstantUrls.URL_NEXT_PAGE : FrontendConstantUrls.URL_COPY_PAGE);
} catch (Exception e) {
logger.error("Error handling request: {}", e);
throw e;
}
return redirect;
}
Aggregations