com.google.api.client.auth.oauth2.TokenResponse Java Examples
The following examples show how to use
com.google.api.client.auth.oauth2.TokenResponse.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: CloudShellCredential.java From google-api-java-client with Apache License 2.0 | 6 votes |
@Override protected TokenResponse executeRefreshToken() throws IOException { Socket socket = new Socket("localhost", this.getAuthPort()); socket.setSoTimeout(READ_TIMEOUT_MS); TokenResponse token = new TokenResponse(); try { PrintWriter out = new PrintWriter(socket.getOutputStream(), true); out.println(GET_AUTH_TOKEN_REQUEST); BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream())); // Ignore the size line input.readLine(); Collection<Object> messageArray = jsonFactory.createJsonParser(input) .parseArray(LinkedList.class, Object.class); String accessToken = ((List<Object>) messageArray).get(ACCESS_TOKEN_INDEX).toString(); token.setAccessToken(accessToken); } finally { socket.close(); } return token; }
Example #2
Source File: AuthenticatorActivity.java From android-java-connect-rest-sample with MIT License | 6 votes |
private void createAccount(TokenResponse response) { Log.d(TAG, "Creating account."); String accountType = getString(R.string.account_authenticator_type); String claimAsAccountName = "name"; //FIXME : this be some kind of oidc client parameter. What to do... what to do... String accountName = getAccountName(response, claimAsAccountName); account = new Account(accountName, accountType); accountManager.getAccountManager().addAccountExplicitly(account, null, null); Log.d(TAG, String.format("Saved tokens : (AT %1$s) (RT %2$s)", response.getAccessToken(), response.getRefreshToken())); // Store the tokens in the account saveTokens(response); Log.d(TAG, "Account created."); }
Example #3
Source File: AuthenticatorActivity.java From android-java-connect-rest-sample with MIT License | 6 votes |
@Override protected Boolean doInBackground(String... args) { String authCode = args[0]; String returnedState = args[1]; boolean didStoreTokens = false; if (secureState.equalsIgnoreCase(returnedState)) { Log.i(TAG, "Requesting access_token with AuthCode : " + authCode); try { TokenResponse response = requestManager.requestTokensWithCodeGrant(authCode); didStoreTokens = createOrUpdateAccount(response); } catch (IOException e) { Log.e(TAG, "Could not get response from the token endpoint", e); } } else { Log.e(TAG, "Local and returned states don't match"); } return didStoreTokens; }
Example #4
Source File: CredentialFromAccessTokenProviderClassFactory.java From hadoop-connectors with Apache License 2.0 | 6 votes |
@Override protected TokenResponse executeRefreshToken() throws IOException { accessTokenProvider.refresh(); AccessToken accessToken = Preconditions.checkNotNull( accessTokenProvider.getAccessToken(), "Access Token cannot be null!"); String token = Preconditions.checkNotNull(accessToken.getToken(), "Access Token cannot be null!"); Long expirationTimeMilliSeconds = accessToken.getExpirationTimeMilliSeconds(); return new TokenResponse() .setAccessToken(token) .setExpiresInSeconds( expirationTimeMilliSeconds == null ? null : (expirationTimeMilliSeconds - clock.currentTimeMillis()) / 1000); }
Example #5
Source File: AuthorizationCodeInstalledApp.java From google-oauth-java-client with Apache License 2.0 | 6 votes |
/** * 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 IOException { try { Credential credential = flow.loadCredential(userId); if (credential != null && (credential.getRefreshToken() != null || credential.getExpiresInSeconds() == null || credential.getExpiresInSeconds() > 60)) { return credential; } // open in browser String redirectUri = receiver.getRedirectUri(); AuthorizationCodeRequestUrl authorizationUrl = flow.newAuthorizationUrl().setRedirectUri(redirectUri); onAuthorization(authorizationUrl); // receive authorization code and exchange it for an access token String code = receiver.waitForCode(); TokenResponse response = flow.newTokenRequest(code).setRedirectUri(redirectUri).execute(); // store credential and return it return flow.createAndStoreCredential(response, userId); } finally { receiver.stop(); } }
Example #6
Source File: GitLabContext.java From git-as-svn with GNU General Public License v2.0 | 6 votes |
@NotNull public static GitLabToken obtainAccessToken(@NotNull String gitlabUrl, @NotNull String username, @NotNull String password, boolean sudoScope) throws IOException { try { final OAuthGetAccessToken tokenServerUrl = new OAuthGetAccessToken(gitlabUrl + "/oauth/token?scope=api" + (sudoScope ? "%20sudo" : "")); final TokenResponse oauthResponse = new PasswordTokenRequest(transport, JacksonFactory.getDefaultInstance(), tokenServerUrl, username, password).execute(); return new GitLabToken(TokenType.ACCESS_TOKEN, oauthResponse.getAccessToken()); } catch (TokenResponseException e) { if (sudoScope && e.getStatusCode() == HttpURLConnection.HTTP_UNAUTHORIZED) { // Fallback for pre-10.2 gitlab versions final GitlabSession session = GitlabAPI.connect(gitlabUrl, username, password); return new GitLabToken(TokenType.PRIVATE_TOKEN, session.getPrivateToken()); } else { throw new GitlabAPIException(e.getMessage(), e.getStatusCode(), e); } } }
Example #7
Source File: ApigeeDataClient.java From apigee-android-sdk with Apache License 2.0 | 6 votes |
/** * Used to get an OAuth 2 access_token using the password grant_type synchronously. * * @param accessTokenURL The accessTokenURL * @param username The username of the user to login * @param password The password of the user to login * @param clientId The clientId * @return The TokenResponse object if we successfully gathered the token or null if the attempt was not successful. */ public TokenResponse oauth2AccessToken(String accessTokenURL, String username, String password, String clientId) { validateNonEmptyParam(accessTokenURL, "accessTokenURL"); validateNonEmptyParam(username, "username"); validateNonEmptyParam(password, "password"); TokenResponse tokenResponse = null; // Make sure clientId is just non-null. Otherwise we will possibly crash or get an unneeded exception. if( clientId == null ) { clientId = ""; } try { AuthorizationRequestUrl authorizationRequestUrl = new AuthorizationRequestUrl(accessTokenURL, clientId, Collections.singleton("token")); PasswordTokenRequest passwordTokenRequest = new PasswordTokenRequest(new NetHttpTransport(), new JacksonFactory(), authorizationRequestUrl, username, password); tokenResponse = passwordTokenRequest.execute(); } catch (Exception exception) { } return tokenResponse; }
Example #8
Source File: ApigeeDataClient.java From apigee-android-sdk with Apache License 2.0 | 6 votes |
/** * Stores the given OAuth 2 token response within a file data store. * The stored token response can then retrieved using the getOAuth2TokenDataFromStore method. * * @param storageId a string object that is used to store the token response * @param tokenResponse the token response containing the OAuth 2 token information. * @return If the token response was stored or not. */ public Boolean storeOAuth2TokenData(String storageId, TokenResponse tokenResponse) { Boolean wasStored = false; try { File oauth2StorageFolder = new File(this.context.getFilesDir(),"oauth2StorageFolder"); oauth2StorageFolder.mkdirs(); FileDataStoreFactory fileDataStoreFactory = new FileDataStoreFactory(oauth2StorageFolder); DataStore<StoredCredential> storedCredentialDataStore = fileDataStoreFactory.getDataStore(storageId); Credential oauth2Credential = new Credential(BearerToken.authorizationHeaderAccessMethod()).setFromTokenResponse( tokenResponse); StoredCredential storedOAuth2Credential = new StoredCredential(oauth2Credential); storedCredentialDataStore.set(storageId,storedOAuth2Credential); wasStored = true; } catch ( Exception exception ) { logInfo("Exception storing OAuth2TokenData :" + exception.getLocalizedMessage()); } return wasStored; }
Example #9
Source File: GoogleCredentialFactory.java From data-transfer-project with Apache License 2.0 | 6 votes |
/** Refreshes and updates the given credential */ public Credential refreshCredential(Credential credential) throws IOException, InvalidTokenException { try { TokenResponse tokenResponse = new RefreshTokenRequest( httpTransport, jsonFactory, new GenericUrl(credential.getTokenServerEncodedUrl()), credential.getRefreshToken()) .setClientAuthentication(credential.getClientAuthentication()) .setRequestInitializer(credential.getRequestInitializer()) .execute(); return credential.setFromTokenResponse(tokenResponse); } catch (TokenResponseException e) { TokenErrorResponse details = e.getDetails(); if (details != null && details.getError().equals("invalid_grant")) { throw new InvalidTokenException("Unable to refresh token.", e); } else { throw e; } } }
Example #10
Source File: AppIdentityCredential.java From google-api-java-client with Apache License 2.0 | 5 votes |
@Override protected TokenResponse executeRefreshToken() throws IOException { GetAccessTokenResult tokenResult = appIdentity.getAppIdentityService() .getAccessToken(appIdentity.getScopes()); TokenResponse response = new TokenResponse(); response.setAccessToken(tokenResult.getAccessToken()); long expiresInSeconds = (tokenResult.getExpirationTime().getTime() - System.currentTimeMillis()) / 1000; response.setExpiresInSeconds(expiresInSeconds); return response; }
Example #11
Source File: AuthenticatorActivity.java From android-java-connect-rest-sample with MIT License | 5 votes |
private void saveTokens(TokenResponse response) { try { accountManager.saveTokens(account, response); } catch (UserNotAuthenticatedWrapperException e) { showAuthenticationScreen(ASK_USER_ENCRYPT_PIN_REQUEST_CODE); } }
Example #12
Source File: MendeleyClient.java From slr-toolkit with Eclipse Public License 1.0 | 5 votes |
/** * This Method exchanges the authorization code for an access token. * If successful the Tokens and Expiration Date will be stored. * * @param code The authorization code from the user interface response has to be passed * @throws IOException * @throws TokenMgrException * @throws ParseException */ public void requestAccessToken(String code) throws IOException, TokenMgrException, ParseException { try { TokenResponse response = new AuthorizationCodeTokenRequest(new NetHttpTransport(), new JacksonFactory(), new GenericUrl("https://api.mendeley.com/oauth/token"),code) .setRedirectUri("https://localhost") .setGrantType("authorization_code") .setClientAuthentication( new BasicAuthentication("4335", "sSFcbUA38RS9Cpm7")).execute(); this.access_token = response.getAccessToken(); this.refresh_token = response.getRefreshToken(); this.expires_at = this.generateExpiresAtFromExpiresIn(response.getExpiresInSeconds().intValue()); updatePreferenceStore(); refreshTokenIfNecessary(); } catch (TokenResponseException e) { if (e.getDetails() != null) { System.err.println("Error: " + e.getDetails().getError()); if (e.getDetails().getErrorDescription() != null) { System.err.println(e.getDetails().getErrorDescription()); } if (e.getDetails().getErrorUri() != null) { System.err.println(e.getDetails().getErrorUri()); } } else { System.err.println(e.getMessage()); } } }
Example #13
Source File: MendeleyClient.java From slr-toolkit with Eclipse Public License 1.0 | 5 votes |
/** * This Methods uses the refresh Token to retrieve a renewed access token * * @param code Refresh Token * @return This returns if the request was successful. * @throws IOException * @throws TokenMgrException * @throws ParseException */ public boolean requestRefreshAccessToken(String code) throws IOException, TokenMgrException, ParseException { try { RefreshTokenRequest request = new RefreshTokenRequest(new NetHttpTransport(), new JacksonFactory(), new GenericUrl("https://api.mendeley.com/oauth/token"),code) .setRefreshToken(code) .set("redirect_uri", "https://localhost") .setGrantType("refresh_token") .setClientAuthentication( new BasicAuthentication("4335", "sSFcbUA38RS9Cpm7")); TokenResponse response = request.execute(); this.access_token = response.getAccessToken(); this.refresh_token = response.getRefreshToken(); this.expires_at = this.generateExpiresAtFromExpiresIn(response.getExpiresInSeconds().intValue()); updatePreferenceStore(); refreshTokenIfNecessary(); return true; } catch (TokenResponseException e) { if (e.getDetails() != null) { System.err.println("Error: " + e.getDetails().getError()); if (e.getDetails().getErrorDescription() != null) { System.err.println(e.getDetails().getErrorDescription()); } if (e.getDetails().getErrorUri() != null) { System.err.println(e.getDetails().getErrorUri()); } } else { System.err.println(e.getMessage()); } return false; } }
Example #14
Source File: ApigeeDataClient.java From apigee-android-sdk with Apache License 2.0 | 5 votes |
/** * Used to get an OAuth 2 access_token using the password grant_type asynchronously. * * @param accessTokenURL The accessTokenURL * @param username The username of the user to login * @param password The password of the user to login * @param clientId The clientId * @param callback The callback that will be executed when we have finished. */ public void oauth2AccessTokenAsync(final String accessTokenURL, final String username, final String password, final String clientId, OAuth2ResponseCallback callback) { validateNonEmptyParam(accessTokenURL, "accessTokenURL"); validateNonEmptyParam(username,"username"); validateNonEmptyParam(password,"password"); (new ClientAsyncTask<TokenResponse>(callback) { @Override public TokenResponse doTask() { return oauth2AccessToken(accessTokenURL, username, password, clientId); } }).execute(); }
Example #15
Source File: HadoopCredentialConfigurationTest.java From hadoop-connectors with Apache License 2.0 | 5 votes |
@Test public void metadataServiceIsUsedByDefault() throws Exception { TokenResponse token = new TokenResponse().setAccessToken("metadata-test-token"); MockHttpTransport transport = mockTransport(jsonDataResponse(token)); CredentialFactory.setStaticHttpTransport(transport); CredentialFactory credentialFactory = getCredentialFactory(); Credential credential = credentialFactory.getCredential(TEST_SCOPES); assertThat(credential.getAccessToken()).isEqualTo("metadata-test-token"); }
Example #16
Source File: CredentialFactory.java From hadoop-connectors with Apache License 2.0 | 5 votes |
@Override protected TokenResponse executeRefreshToken() throws IOException { if (getServiceAccountPrivateKey() == null) { return super.executeRefreshToken(); } // service accounts: no refresh token; instead use private key to request new access token JsonWebSignature.Header header = new JsonWebSignature.Header() .setAlgorithm("RS256") .setType("JWT") .setKeyId(getServiceAccountPrivateKeyId()); long currentTime = getClock().currentTimeMillis(); JsonWebToken.Payload payload = new JsonWebToken.Payload() .setIssuer(getServiceAccountId()) .setAudience(getTokenServerEncodedUrl()) .setIssuedAtTimeSeconds(currentTime / 1000) .setExpirationTimeSeconds(currentTime / 1000 + DEFAULT_TOKEN_EXPIRATION_SECONDS) .setSubject(getServiceAccountUser()); payload.put("scope", WHITESPACE_JOINER.join(getServiceAccountScopes())); try { String assertion = JsonWebSignature.signUsingRsaSha256( getServiceAccountPrivateKey(), getJsonFactory(), header, payload); TokenRequest request = new TokenRequest( getTransport(), getJsonFactory(), new GenericUrl(getTokenServerEncodedUrl()), "urn:ietf:params:oauth:grant-type:jwt-bearer") .setRequestInitializer(getRequestInitializer()); request.put("assertion", assertion); return request.execute(); } catch (GeneralSecurityException e) { throw new IOException("Failed to refresh token", e); } }
Example #17
Source File: CredentialFactory.java From hadoop-connectors with Apache License 2.0 | 5 votes |
@Override protected TokenResponse executeRefreshToken() throws IOException { HttpRequest request = getTransport() .createRequestFactory(getRequestInitializer()) .buildGetRequest(new GenericUrl(getTokenServerEncodedUrl())) .setParser(new JsonObjectParser(getJsonFactory())); request.getHeaders().set("Metadata-Flavor", "Google"); return request.execute().parseAs(TokenResponse.class); }
Example #18
Source File: GoogleCredentialWithIamAccessToken.java From hadoop-connectors with Apache License 2.0 | 5 votes |
@Override protected TokenResponse executeRefreshToken() throws IOException { GenerateAccessTokenResponse accessTokenResponse = generateAccessToken(); TokenResponse tokenResponse = new TokenResponse().setAccessToken(accessTokenResponse.getAccessToken()); if (isNullOrEmpty(accessTokenResponse.getExpireTime())) { return tokenResponse; } Instant expirationTimeInInstant = Instant.parse(accessTokenResponse.getExpireTime()); long expirationTimeMilliSeconds = expirationTimeInInstant.getEpochSecond(); return tokenResponse.setExpiresInSeconds( expirationTimeMilliSeconds - clock.currentTimeMillis() / 1000); }
Example #19
Source File: OpenIdConnectAuthenticator.java From fess with Apache License 2.0 | 5 votes |
protected TokenResponse getTokenUrl(final String code) throws IOException { return new AuthorizationCodeTokenRequest(httpTransport, jsonFactory, new GenericUrl(getOicTokenServerUrl()), code)// .setGrantType("authorization_code")// .setRedirectUri(getOicRedirectUrl())// .set("client_id", getOicClientId())// .set("client_secret", getOicClientSecret())// .execute(); }
Example #20
Source File: ComputeCredential.java From google-api-java-client with Apache License 2.0 | 5 votes |
@Override protected TokenResponse executeRefreshToken() throws IOException { GenericUrl tokenUrl = new GenericUrl(getTokenServerEncodedUrl()); HttpRequest request = getTransport().createRequestFactory().buildGetRequest(tokenUrl); request.setParser(new JsonObjectParser(getJsonFactory())); request.getHeaders().set("Metadata-Flavor", "Google"); return request.execute().parseAs(TokenResponse.class); }
Example #21
Source File: GoogleCredential.java From google-api-java-client with Apache License 2.0 | 5 votes |
@Override @Beta protected TokenResponse executeRefreshToken() throws IOException { if (serviceAccountPrivateKey == null) { return super.executeRefreshToken(); } // service accounts: no refresh token; instead use private key to request new access token JsonWebSignature.Header header = new JsonWebSignature.Header(); header.setAlgorithm("RS256"); header.setType("JWT"); header.setKeyId(serviceAccountPrivateKeyId); JsonWebToken.Payload payload = new JsonWebToken.Payload(); long currentTime = getClock().currentTimeMillis(); payload.setIssuer(serviceAccountId); payload.setAudience(getTokenServerEncodedUrl()); payload.setIssuedAtTimeSeconds(currentTime / 1000); payload.setExpirationTimeSeconds(currentTime / 1000 + 3600); payload.setSubject(serviceAccountUser); payload.put("scope", Joiner.on(' ').join(serviceAccountScopes)); try { String assertion = JsonWebSignature.signUsingRsaSha256( serviceAccountPrivateKey, getJsonFactory(), header, payload); TokenRequest request = new TokenRequest( getTransport(), getJsonFactory(), new GenericUrl(getTokenServerEncodedUrl()), "urn:ietf:params:oauth:grant-type:jwt-bearer"); request.put("assertion", assertion); return request.execute(); } catch (GeneralSecurityException exception) { IOException e = new IOException(); e.initCause(exception); throw e; } }
Example #22
Source File: MicrosoftCredentialFactory.java From data-transfer-project with Apache License 2.0 | 5 votes |
/** * Refreshes and updates the given credential */ public Credential refreshCredential(Credential credential) throws IOException { TokenResponse tokenResponse = new RefreshTokenRequest(httpTransport, jsonFactory, new GenericUrl(credential.getTokenServerEncodedUrl()), credential.getRefreshToken()) .setClientAuthentication(credential.getClientAuthentication()) .setRequestInitializer(credential.getRequestInitializer()).execute(); return credential.setFromTokenResponse(tokenResponse); }
Example #23
Source File: DefaultCredentialProvider.java From google-api-java-client with Apache License 2.0 | 5 votes |
@Override protected TokenResponse executeRefreshToken() throws IOException { GenericUrl tokenUrl = new GenericUrl(getTokenServerEncodedUrl()); HttpRequest request = getTransport().createRequestFactory().buildGetRequest(tokenUrl); JsonObjectParser parser = new JsonObjectParser(getJsonFactory()); request.setParser(parser); request.getHeaders().set("Metadata-Flavor", "Google"); request.setThrowExceptionOnExecuteError(false); HttpResponse response = request.execute(); int statusCode = response.getStatusCode(); if (statusCode == HttpStatusCodes.STATUS_CODE_OK) { InputStream content = response.getContent(); if (content == null) { // Throw explicitly rather than allow a later null reference as default mock // transports return success codes with empty contents. throw new IOException("Empty content from metadata token server request."); } return parser.parseAndClose(content, response.getContentCharset(), TokenResponse.class); } if (statusCode == HttpStatusCodes.STATUS_CODE_NOT_FOUND) { throw new IOException(String.format("Error code %s trying to get security access token from" + " Compute Engine metadata for the default service account. This may be because" + " the virtual machine instance does not have permission scopes specified.", statusCode)); } throw new IOException(String.format("Unexpected Error code %s trying to get security access" + " token from Compute Engine metadata for the default service account: %s", statusCode, response.parseAsString())); }
Example #24
Source File: OAuthClient.java From kickflip-android-sdk with Apache License 2.0 | 5 votes |
protected void storeAccessToken(TokenResponse tokenResponse) { Calendar cal = Calendar.getInstance(); cal.add(Calendar.SECOND, (int) (tokenResponse.getExpiresInSeconds() - 60)); long tokenExpirtyTime = cal.getTimeInMillis(); getContext().getSharedPreferences(mConfig.getCredentialStoreName(), mContext.MODE_PRIVATE).edit() .putString(ACCESS_TOKEN_KEY, tokenResponse.getAccessToken()) .putLong(ACCESS_TOKEN_EXP_KEY, tokenExpirtyTime) .putString(CLIENT_ID, mConfig.getClientId()) .apply(); }
Example #25
Source File: AbstractAuthorizationCodeCallbackServlet.java From google-oauth-java-client with Apache License 2.0 | 5 votes |
@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(); } } }
Example #26
Source File: ApigeeDataClient.java From apigee-android-sdk with Apache License 2.0 | 5 votes |
/** * Used to get an OAuth 2 access_token using the client_credentials grant_type asynchronously. * * @param accessTokenURL The url used to get the access_token * @param clientId The client_id * @param clientSecret The client_secret * @param callback The callback that will be executed when we have finished. */ public void oauth2AccessTokenAsync(final String accessTokenURL, final String clientId, final String clientSecret, OAuth2ResponseCallback callback) { validateNonEmptyParam(accessTokenURL, "accessTokenURL"); validateNonEmptyParam(clientId,"clientId"); validateNonEmptyParam(clientSecret,"clientSecret"); (new ClientAsyncTask<TokenResponse>(callback) { @Override public TokenResponse doTask() { return oauth2AccessToken(accessTokenURL,clientId,clientSecret); } }).execute(); }
Example #27
Source File: OpenIdConnectAuthenticator.java From fess with Apache License 2.0 | 5 votes |
protected LoginCredential processCallback(final HttpServletRequest request, final String code) { try { final TokenResponse tr = getTokenUrl(code); final String[] jwt = ((String) tr.get("id_token")).split("\\."); final String jwtHeader = new String(Base64.decodeBase64(jwt[0]), Constants.UTF_8_CHARSET); final String jwtClaim = new String(Base64.decodeBase64(jwt[1]), Constants.UTF_8_CHARSET); final String jwtSigniture = new String(Base64.decodeBase64(jwt[2]), Constants.UTF_8_CHARSET); if (logger.isDebugEnabled()) { logger.debug("jwtHeader: {}", jwtHeader); logger.debug("jwtClaim: {}", jwtClaim); logger.debug("jwtSigniture: {}", jwtSigniture); } // TODO validate signiture final Map<String, Object> attributes = new HashMap<>(); attributes.put("accesstoken", tr.getAccessToken()); attributes.put("refreshtoken", tr.getRefreshToken() == null ? "null" : tr.getRefreshToken()); attributes.put("tokentype", tr.getTokenType()); attributes.put("expire", tr.getExpiresInSeconds()); attributes.put("jwtheader", jwtHeader); attributes.put("jwtclaim", jwtClaim); attributes.put("jwtsign", jwtSigniture); if (logger.isDebugEnabled()) { logger.debug("attribute: {}", attributes); } parseJwtClaim(jwtClaim, attributes); return new OpenIdConnectCredential(attributes); } catch (final IOException e) { if (logger.isDebugEnabled()) { logger.debug("Failed to process callbacked request.", e); } } return null; }
Example #28
Source File: AuthenticatorActivity.java From android-java-connect-rest-sample with MIT License | 5 votes |
@Override protected Boolean doInBackground(String... args) { String userName = args[0]; String userPwd = args[1]; boolean didStoreTokens = false; Log.d(TAG, "Requesting access_token with username : " + userName); try { TokenResponse response = requestManager.requestTokensWithPasswordGrant(userName, userPwd); didStoreTokens = createOrUpdateAccount(response); } catch (IOException e) { Log.e(TAG, "Could not get response from the token endpoint", e); } return didStoreTokens; }
Example #29
Source File: GoogleIdTokenAuth.java From styx with Apache License 2.0 | 5 votes |
private String getUserToken(UserCredentials credentials) throws IOException { log.debug("Fetching user id token"); final TokenRequest request = new RefreshTokenRequest( this.httpTransport, JSON_FACTORY, new GenericUrl(credentials.toBuilder().getTokenServerUri()), credentials.getRefreshToken()) .setClientAuthentication(new ClientParametersAuthentication( credentials.getClientId(), credentials.getClientSecret())) .setRequestInitializer(new HttpCredentialsAdapter(credentials)); final TokenResponse response = request.execute(); return (String) response.get("id_token"); }
Example #30
Source File: GoogleIdTokenAuth.java From styx with Apache License 2.0 | 5 votes |
private String getServiceAccountIdTokenUsingAccessToken(GoogleCredentials credentials, String serviceAccount, String targetAudience) throws IOException { final String tokenServerUrl = "https://oauth2.googleapis.com/token"; final Header header = jwtHeader(); final JsonWebToken.Payload payload = jwtPayload( targetAudience, serviceAccount, tokenServerUrl); final Iam iam = new Iam.Builder(httpTransport, JSON_FACTORY, new HttpCredentialsAdapter(withScopes(credentials, IamScopes.all()))).build(); final String content = Base64.encodeBase64URLSafeString(JSON_FACTORY.toByteArray(header)) + "." + Base64.encodeBase64URLSafeString(JSON_FACTORY.toByteArray(payload)); byte[] contentBytes = StringUtils.getBytesUtf8(content); final SignBlobResponse signResponse; try { signResponse = iam.projects().serviceAccounts() .signBlob("projects/-/serviceAccounts/" + serviceAccount, new SignBlobRequest() .encodeBytesToSign(contentBytes)) .execute(); } catch (GoogleJsonResponseException e) { if (e.getStatusCode() == 403) { throw new IOException( "Unable to sign request for id token, missing Service Account Token Creator role for self on " + serviceAccount + " or IAM api not enabled?", e); } throw e; } final String assertion = content + "." + signResponse.getSignature(); final TokenRequest request = new TokenRequest( httpTransport, JSON_FACTORY, new GenericUrl(tokenServerUrl), "urn:ietf:params:oauth:grant-type:jwt-bearer"); request.put("assertion", assertion); final TokenResponse tokenResponse = request.execute(); return (String) tokenResponse.get("id_token"); }