use of com.microsoft.identity.common.internal.providers.oauth2.TokenResponse in project google-oauth-java-client by googleapis.
the class AbstractAuthorizationCodeCallbackServlet method doGet.
@Override
protected final void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
StringBuffer buf = req.getRequestURL();
if (req.getQueryString() != null) {
buf.append('?').append(req.getQueryString());
}
AuthorizationCodeResponseUrl responseUrl = new AuthorizationCodeResponseUrl(buf.toString());
String code = responseUrl.getCode();
if (responseUrl.getError() != null) {
onError(req, resp, responseUrl);
} else if (code == null) {
resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
resp.getWriter().print("Missing authorization code");
} else {
lock.lock();
try {
if (flow == null) {
flow = initializeFlow();
}
String redirectUri = getRedirectUri(req);
TokenResponse response = flow.newTokenRequest(code).setRedirectUri(redirectUri).execute();
String userId = getUserId(req);
Credential credential = flow.createAndStoreCredential(response, userId);
onSuccess(req, resp, credential);
} finally {
lock.unlock();
}
}
}
use of com.microsoft.identity.common.internal.providers.oauth2.TokenResponse in project getting-started-java by GoogleCloudPlatform.
the class Oauth2CallbackServlet method doGet.
@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
// sending us this connect request is the user that was supposed to.
if (req.getSession().getAttribute("state") == null || !req.getParameter("state").equals((String) req.getSession().getAttribute("state"))) {
resp.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
logger.log(Level.WARNING, "Invalid state parameter, expected " + (String) req.getSession().getAttribute("state") + " got " + req.getParameter("state"));
resp.sendRedirect("/books");
return;
}
// Remove one-time use state.
req.getSession().removeAttribute("state");
flow = new GoogleAuthorizationCodeFlow.Builder(HTTP_TRANSPORT, JSON_FACTORY, getServletContext().getInitParameter("bookshelf.clientID"), getServletContext().getInitParameter("bookshelf.clientSecret"), SCOPES).build();
final TokenResponse tokenResponse = flow.newTokenRequest(req.getParameter("code")).setRedirectUri(getServletContext().getInitParameter("bookshelf.callback")).execute();
// Keep track of the token.
req.getSession().setAttribute("token", tokenResponse.toString());
final Credential credential = flow.createAndStoreCredential(tokenResponse, null);
final HttpRequestFactory requestFactory = HTTP_TRANSPORT.createRequestFactory(credential);
// Make an authenticated request.
final GenericUrl url = new GenericUrl(USERINFO_ENDPOINT);
final HttpRequest request = requestFactory.buildGetRequest(url);
request.getHeaders().setContentType("application/json");
final String jsonIdentity = request.execute().parseAsString();
@SuppressWarnings("unchecked") HashMap<String, String> userIdResult = new ObjectMapper().readValue(jsonIdentity, HashMap.class);
// From this map, extract the relevant profile info and store it in the session.
req.getSession().setAttribute("userEmail", userIdResult.get("email"));
req.getSession().setAttribute("userId", userIdResult.get("sub"));
req.getSession().setAttribute("userImageUrl", userIdResult.get("picture"));
logger.log(Level.INFO, "Login successful, redirecting to " + (String) req.getSession().getAttribute("loginDestination"));
resp.sendRedirect((String) req.getSession().getAttribute("loginDestination"));
}
use of com.microsoft.identity.common.internal.providers.oauth2.TokenResponse in project data-transfer-project by google.
the class MicrosoftAuth method generateAuthData.
@Override
public AuthData generateAuthData(String callbackBaseUrl, String authCode, UUID jobId, AuthData initialAuthData, String extra) throws IOException {
Preconditions.checkArgument(Strings.isNullOrEmpty(extra), "Extra data not expected for MS oauth flow");
Preconditions.checkArgument(initialAuthData == null, "Earlier auth data not expected for MS oauth flow");
AuthorizationCodeFlow flow = createFlow();
TokenResponse response = flow.newTokenRequest(authCode).setRedirectUri(// TODO(chuy): Parameterize
callbackBaseUrl + CALLBACK_PATH).execute();
// Figure out storage
Credential credential = flow.createAndStoreCredential(response, jobId.toString());
// GoogleIdToken.Payload payload = ((GoogleTokenResponse) response).parseIdToken().getPayload();
return toAuthData(credential);
}
use of com.microsoft.identity.common.internal.providers.oauth2.TokenResponse in project data-transfer-project by google.
the class AuthorizationCodeInstalledAppSecureOverride method authorize.
/**
* Authorizes the installed application to access user's protected data.
*
* @param userId user ID or {@code null} if not using a persisted credential store
* @return credential
*/
public Credential authorize(String userId) throws Exception {
try {
System.out.println("loadCredential for: " + userId);
Credential credential = flow.loadCredential(userId);
if (credential != null && (credential.getRefreshToken() != null || credential.getExpiresInSeconds() > 60)) {
return credential;
}
// Ensure redirect http uri's are https
String redirectUri = receiver.getRedirectUri();
if (redirectUri.startsWith("http:")) {
redirectUri = redirectUri.replace("http:", "https:");
}
// open in browser
AuthorizationCodeRequestUrl authorizationUrl = flow.newAuthorizationUrl().setRedirectUri(redirectUri);
System.out.println("authorizationUrl: " + authorizationUrl);
onAuthorization(authorizationUrl);
// receive authorization code and exchange it for an access token
System.out.println("receiver.waitForCode()");
String code = receiver.waitForCode();
System.out.println("Code received from receiver: " + code);
TokenResponse response = flow.newTokenRequest(code).setRedirectUri(redirectUri).execute();
System.out.println("TokenResponse: " + response);
// store credential and return it
return flow.createAndStoreCredential(response, userId);
} finally {
receiver.stop();
}
}
use of com.microsoft.identity.common.internal.providers.oauth2.TokenResponse in project workbench by all-of-us.
the class RasLinkService method linkRasLoginGovAccount.
/**
* Links RAS login.gov account with AoU account.
*/
public DbUser linkRasLoginGovAccount(String authCode, String redirectUrl) {
OpenIdConnectClient rasOidcClient = rasOidcClientProvider.get();
JsonNode userInfoResponse;
try {
// Oauth dance to get id token and access token.
TokenResponse tokenResponse = rasOidcClient.codeExchange(authCode, decodeUrl(redirectUrl), RAS_AUTH_CODE_SCOPES);
// Validate IAL status.
String acrClaim = decodedJwt(tokenResponse.get(Id_TOKEN_FIELD_NAME).toString()).getClaim(ACR_CLAIM).asString();
if (!isIal2(acrClaim)) {
log.warning(String.format("User does not have IAL2 enabled, acrClaim: %s", acrClaim));
throw new ForbiddenException(String.format("User does not have IAL2 enabled, acrClaim: %s", acrClaim));
}
// Fetch user info.
userInfoResponse = rasOidcClient.fetchUserInfo(tokenResponse.getAccessToken());
} catch (IOException e) {
log.log(Level.WARNING, "Failed to link RAS account", e);
throw new ServerErrorException("Failed to link RAS account", e);
}
// If eRA is not already linked, check response from RAS see if RAS contains eRA Linking
// information.
DbUser user = userService.updateRasLinkLoginGovStatus(getLoginGovUsername(userInfoResponse));
Optional<AccessModuleStatus> eRAModuleStatus = accessModuleService.getAccessModuleStatus(user).stream().filter(a -> a.getModuleName() == AccessModule.ERA_COMMONS).findFirst();
if (eRAModuleStatus.isPresent() && (eRAModuleStatus.get().getCompletionEpochMillis() != null || eRAModuleStatus.get().getBypassEpochMillis() != null)) {
return user;
}
Optional<String> eRaUserId = getEraUserId(userInfoResponse);
if (eRaUserId.isPresent() && !eRaUserId.get().isEmpty()) {
return userService.updateRasLinkEraStatus(eRaUserId.get());
} else {
log.info(String.format("User does not have valid eRA %s", userInfoResponse.get(FEDERATED_IDENTITIES)));
}
return user;
}
Aggregations