For IntelliJ IDEA,
Android Studio or Eclipse



public void setToken(String userId, OAuthToken token) throws IOException { flow.createAndStoreCredential( new TokenResponse().setAccessToken(token.getToken()).setScope(token.getScope()), userId); } }
/** * Create authentication URL. * * @param requestUrl URL of current HTTP request. This parameter required to be able determine URL * for redirection after authentication. If URL contains query parameters they will be copy to * 'state' parameter and returned to callback method. * @param scopes specify exactly what type of access needed * @return URL for authentication */ public String getAuthenticateUrl(URL requestUrl, List<String> scopes) throws OAuthAuthenticationException { if (!isConfigured()) { throw new OAuthAuthenticationException("Authenticator is not configured"); } AuthorizationCodeRequestUrl url = flow.newAuthorizationUrl().setRedirectUri(findRedirectUrl(requestUrl)).setScopes(scopes); url.setState(prepareState(requestUrl)); return url.build(); }
/** * Invalidate OAuth token for specified user. * * @param userId user * @return <code>true</code> if OAuth token invalidated and <code>false</code> otherwise, e.g. if * user does not have token yet */ public boolean invalidateToken(String userId) throws IOException { Credential credential = flow.loadCredential(userId); if (credential != null) { flow.getCredentialDataStore().delete(userId); return true; } return false; }
private String getUserFromUrl(AuthorizationCodeResponseUrl authorizationCodeResponseUrl) throws IOException { String state = authorizationCodeResponseUrl.getState(); if (!(state == null || state.isEmpty())) { String decoded = URLDecoder.decode(state, "UTF-8"); String[] items = decoded.split("&"); for (String str : items) { if (str.startsWith("userId=")) { return str.substring(7, str.length()); } } } return null; }
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. "); flow.newTokenRequest(code) .setRequestInitializer( request -> { if (request.getParser() == null) { request.setParser(flow.getJsonFactory().createJsonObjectParser()); .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 IOException("Authenticator is not configured"); Credential credential = flow.loadCredential(userId); if (credential == null) { return null; final Long expirationTime = credential.getExpiresInSeconds(); if (expirationTime != null && expirationTime < 0) { boolean tokenRefreshed; try { tokenRefreshed = credential.refreshToken(); } catch (IOException ioEx) { tokenRefreshed = false; credential = flow.loadCredential(userId); } else { return newDto(OAuthToken.class).withToken(credential.getAccessToken());
throws IOException { final AuthorizationCodeFlow authorizationFlow = new AuthorizationCodeFlow.Builder( BearerToken.authorizationHeaderAccessMethod(), new NetHttpTransport(), new JacksonFactory(), new GenericUrl(tokenUri), new ClientParametersAuthentication(clientId, clientSecret), clientId, authUri) .setDataStoreFactory(dataStoreFactory) .setScopes(scopes) .build();
TokenResponse tokenResponse = new TokenResponse(); tokenResponse.setAccessToken(accessToken); tokenResponse.setRefreshToken(refreshToken); tokenResponse.setExpiresInSeconds(3600L); tokenResponse.setScope("https://www.googleapis.com/auth/androidpublisher"); tokenResponse.setTokenType("Bearer");
/** * Initializes the given request. */ @Override public final void initialize(final HttpRequest request) { request.setReadTimeout(2 * ONEMINITUES); // 2 minutes read timeout final HttpUnsuccessfulResponseHandler backoffHandler = new HttpBackOffUnsuccessfulResponseHandler( new ExponentialBackOff()) .setSleeper(sleeper); request.setInterceptor(wrappedCredential); request.setUnsuccessfulResponseHandler( (request1, response, supportsRetry) -> { if (wrappedCredential.handleResponse(request1, response, supportsRetry)) { // If credential decides it can handle it, the return code or message indicated // something specific to authentication, and no backoff is desired. return true; } else if (backoffHandler.handleResponse(request1, response, supportsRetry)) { // Otherwise, we defer to the judgement of our internal backoff handler. LOG.info("Retrying " + request1.getUrl().toString()); return true; } else { return false; } }); request.setIOExceptionHandler( new HttpBackOffIOExceptionHandler(new ExponentialBackOff()) .setSleeper(sleeper)); } }
/** * @param credential existing credential to copy from */ public StoredCredential(Credential credential) { setAccessToken(credential.getAccessToken()); setRefreshToken(credential.getRefreshToken()); setExpirationTimeMilliseconds(credential.getExpirationTimeMilliseconds()); }
/** * Returns the authorization header using the user's OAuth 2.0 credentials. * * @param requestUrl the URL being requested * @param requestMethod the HTTP method of the request * @return the authorization header to be used for the request */ public String getAuthorizationHeader(URL requestUrl, String requestMethod) { return HEADER_PREFIX + this.credential.getAccessToken(); }
/** Stores the updated credential in the credential store. */ public void makePersistent(Credential credential) throws IOException { credentialStore.store(userId, credential); } }
StoredCredential toStoredCredential() { return new StoredCredential().setAccessToken(accessToken) .setRefreshToken(refreshToken).setExpirationTimeMilliseconds(expirationTimeMillis); } }
/** * Store information from the credential. * * @param credential credential whose {@link Credential#getAccessToken access token}, * {@link Credential#getRefreshToken refresh token}, and * {@link Credential#getExpirationTimeMilliseconds expiration time} need to be stored */ void store(Credential credential) { accessToken = credential.getAccessToken(); refreshToken = credential.getRefreshToken(); expirationTimeMillis = credential.getExpirationTimeMilliseconds(); }
/** * Store information from the credential. * * @param credential credential whose {@link Credential#getAccessToken access token}, * {@link Credential#getRefreshToken refresh token}, and * {@link Credential#getExpirationTimeMilliseconds expiration time} need to be stored */ void store(Credential credential) { accessToken = credential.getAccessToken(); refreshToken = credential.getRefreshToken(); expirationTimeMillis = credential.getExpirationTimeMilliseconds(); }