Search in sources :

Example 11 with TokenResponse

use of com.google.api.client.auth.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 12 with TokenResponse

use of com.google.api.client.auth.oauth2.TokenResponse in project hub-alert by blackducksoftware.

the class AzureBoardsProperties method requestTokens.

public Optional<Credential> requestTokens(AuthorizationCodeFlow authorizationCodeFlow, String authorizationCode) throws IOException {
    AuthorizationCodeTokenRequest tokenRequest = authorizationCodeFlow.newTokenRequest(authorizationCode);
    TokenResponse tokenResponse = tokenRequest.execute();
    Credential credential = authorizationCodeFlow.createAndStoreCredential(tokenResponse, oauthUserId);
    return Optional.ofNullable(credential);
}
Also used : Credential(com.google.api.client.auth.oauth2.Credential) StoredCredential(com.google.api.client.auth.oauth2.StoredCredential) TokenResponse(com.google.api.client.auth.oauth2.TokenResponse) AuthorizationCodeTokenRequest(com.google.api.client.auth.oauth2.AuthorizationCodeTokenRequest)

Example 13 with TokenResponse

use of com.google.api.client.auth.oauth2.TokenResponse in project hub-alert by blackducksoftware.

the class AzureCredential method executeRefreshToken.

@Override
protected TokenResponse executeRefreshToken() throws IOException {
    String refreshToken = getRefreshToken();
    if (refreshToken == null) {
        if (cachedRefreshToken == null) {
            return null;
        }
        refreshToken = cachedRefreshToken;
    }
    RefreshTokenRequest request = new RefreshTokenRequest(getTransport(), getJsonFactory(), new GenericUrl(getTokenServerEncodedUrl()), refreshToken);
    request.setClientAuthentication(getClientAuthentication());
    request.setRequestInitializer(getRequestInitializer());
    request.setResponseClass(AzureTokenResponse.class);
    request.put(AzureOAuthConstants.REQUEST_BODY_FIELD_ASSERTION, refreshToken);
    request.put(AzureOAuthConstants.REQUEST_BODY_FIELD_CLIENT_ASSERTION_TYPE, AzureOAuthConstants.DEFAULT_CLIENT_ASSERTION_TYPE);
    request.put(AzureOAuthConstants.REQUEST_BODY_FIELD_CLIENT_ASSERTION, clientSecret);
    request.put(AzureOAuthConstants.REQUEST_BODY_FIELD_REDIRECT_URI, redirectUri);
    return request.execute();
}
Also used : RefreshTokenRequest(com.google.api.client.auth.oauth2.RefreshTokenRequest) GenericUrl(com.google.api.client.http.GenericUrl)

Example 14 with TokenResponse

use of com.google.api.client.auth.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)

Aggregations

TokenResponse (com.google.api.client.auth.oauth2.TokenResponse)12 Credential (com.google.api.client.auth.oauth2.Credential)8 AuthorizationCodeFlow (com.google.api.client.auth.oauth2.AuthorizationCodeFlow)5 GenericUrl (com.google.api.client.http.GenericUrl)4 IOException (java.io.IOException)4 AuthorizationCodeRequestUrl (com.google.api.client.auth.oauth2.AuthorizationCodeRequestUrl)2 GoogleAuthorizationCodeFlow (com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow)2 GoogleCredential (com.google.api.client.googleapis.auth.oauth2.GoogleCredential)2 HashMap (java.util.HashMap)2 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)1 AuthorizationCodeResponseUrl (com.google.api.client.auth.oauth2.AuthorizationCodeResponseUrl)1 AuthorizationCodeTokenRequest (com.google.api.client.auth.oauth2.AuthorizationCodeTokenRequest)1 BearerToken (com.google.api.client.auth.oauth2.BearerToken)1 ClientParametersAuthentication (com.google.api.client.auth.oauth2.ClientParametersAuthentication)1 RefreshTokenRequest (com.google.api.client.auth.oauth2.RefreshTokenRequest)1 StoredCredential (com.google.api.client.auth.oauth2.StoredCredential)1 TokenRequest (com.google.api.client.auth.oauth2.TokenRequest)1 HttpRequest (com.google.api.client.http.HttpRequest)1 HttpRequestFactory (com.google.api.client.http.HttpRequestFactory)1 HttpRequestInitializer (com.google.api.client.http.HttpRequestInitializer)1