Search in sources :

Example 31 with TokenResponse

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();
        }
    }
}
Also used : Credential(com.google.api.client.auth.oauth2.Credential) TokenResponse(com.google.api.client.auth.oauth2.TokenResponse) AuthorizationCodeResponseUrl(com.google.api.client.auth.oauth2.AuthorizationCodeResponseUrl)

Example 32 with TokenResponse

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"));
}
Also used : HttpRequest(com.google.api.client.http.HttpRequest) Credential(com.google.api.client.auth.oauth2.Credential) TokenResponse(com.google.api.client.auth.oauth2.TokenResponse) HttpRequestFactory(com.google.api.client.http.HttpRequestFactory) GenericUrl(com.google.api.client.http.GenericUrl) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Example 33 with TokenResponse

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);
}
Also used : Credential(com.google.api.client.auth.oauth2.Credential) TokenResponse(com.google.api.client.auth.oauth2.TokenResponse) AuthorizationCodeFlow(com.google.api.client.auth.oauth2.AuthorizationCodeFlow) AuthorizationCodeInstalledAppSecureOverride(org.dataportabilityproject.shared.auth.AuthorizationCodeInstalledAppSecureOverride)

Example 34 with TokenResponse

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();
    }
}
Also used : AuthorizationCodeRequestUrl(com.google.api.client.auth.oauth2.AuthorizationCodeRequestUrl) Credential(com.google.api.client.auth.oauth2.Credential) TokenResponse(com.google.api.client.auth.oauth2.TokenResponse)

Example 35 with TokenResponse

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;
}
Also used : RAS_OIDC_CLIENT(org.pmiops.workbench.ras.RasOidcClientConfig.RAS_OIDC_CLIENT) ACR_CLAIM(org.pmiops.workbench.ras.RasLinkConstants.ACR_CLAIM) URLDecoder(java.net.URLDecoder) Provider(javax.inject.Provider) Id_TOKEN_FIELD_NAME(org.pmiops.workbench.ras.RasLinkConstants.Id_TOKEN_FIELD_NAME) AccessModuleStatus(org.pmiops.workbench.model.AccessModuleStatus) Autowired(org.springframework.beans.factory.annotation.Autowired) Level(java.util.logging.Level) Service(org.springframework.stereotype.Service) TokenResponse(com.google.api.client.auth.oauth2.TokenResponse) RAS_AUTH_CODE_SCOPES(org.pmiops.workbench.ras.RasLinkConstants.RAS_AUTH_CODE_SCOPES) Qualifier(org.springframework.beans.factory.annotation.Qualifier) JsonNode(com.fasterxml.jackson.databind.JsonNode) ERA_COMMONS_PROVIDER_NAME(org.pmiops.workbench.ras.RasLinkConstants.ERA_COMMONS_PROVIDER_NAME) PREFERRED_USERNAME_FIELD_NAME(org.pmiops.workbench.ras.RasLinkConstants.PREFERRED_USERNAME_FIELD_NAME) UserService(org.pmiops.workbench.db.dao.UserService) FEDERATED_IDENTITIES(org.pmiops.workbench.ras.RasLinkConstants.FEDERATED_IDENTITIES) LOGIN_GOV_IDENTIFIER_LOWER_CASE(org.pmiops.workbench.ras.RasLinkConstants.LOGIN_GOV_IDENTIFIER_LOWER_CASE) ACR_CLAIM_IAL_2_IDENTIFIER(org.pmiops.workbench.ras.RasLinkConstants.ACR_CLAIM_IAL_2_IDENTIFIER) IDENTITY_USERID(org.pmiops.workbench.ras.RasLinkConstants.IDENTITY_USERID) IOException(java.io.IOException) Logger(java.util.logging.Logger) StandardCharsets(java.nio.charset.StandardCharsets) AccessModule(org.pmiops.workbench.model.AccessModule) AccessModuleService(org.pmiops.workbench.access.AccessModuleService) IDENTITIES(org.pmiops.workbench.ras.RasLinkConstants.IDENTITIES) ServerErrorException(org.pmiops.workbench.exceptions.ServerErrorException) ForbiddenException(org.pmiops.workbench.exceptions.ForbiddenException) OpenIdConnectClient.decodedJwt(org.pmiops.workbench.ras.OpenIdConnectClient.decodedJwt) Optional(java.util.Optional) DbUser(org.pmiops.workbench.db.model.DbUser) UnsupportedEncodingException(java.io.UnsupportedEncodingException) ForbiddenException(org.pmiops.workbench.exceptions.ForbiddenException) TokenResponse(com.google.api.client.auth.oauth2.TokenResponse) JsonNode(com.fasterxml.jackson.databind.JsonNode) AccessModuleStatus(org.pmiops.workbench.model.AccessModuleStatus) IOException(java.io.IOException) ServerErrorException(org.pmiops.workbench.exceptions.ServerErrorException) DbUser(org.pmiops.workbench.db.model.DbUser)

Aggregations

TokenResponse (com.google.api.client.auth.oauth2.TokenResponse)48 IOException (java.io.IOException)23 GenericUrl (com.google.api.client.http.GenericUrl)22 Credential (com.google.api.client.auth.oauth2.Credential)20 ClientParametersAuthentication (com.google.api.client.auth.oauth2.ClientParametersAuthentication)16 AuthorizationCodeFlow (com.google.api.client.auth.oauth2.AuthorizationCodeFlow)15 Map (java.util.Map)13 NetHttpTransport (com.google.api.client.http.javanet.NetHttpTransport)12 TokenResponse (com.microsoft.identity.common.internal.providers.oauth2.TokenResponse)11 BearerToken (com.google.api.client.auth.oauth2.BearerToken)9 TokenResult (com.microsoft.identity.common.internal.providers.oauth2.TokenResult)8 Logger (org.slf4j.Logger)8 LoggerFactory (org.slf4j.LoggerFactory)8 Test (org.junit.Test)7 URL (java.net.URL)6 HashMap (java.util.HashMap)6 List (java.util.List)6 Timed (com.codahale.metrics.annotation.Timed)5 AuthorizationCodeRequestUrl (com.google.api.client.auth.oauth2.AuthorizationCodeRequestUrl)5 Collections (java.util.Collections)5