return (GoogleTokenResponse) flow.newTokenRequest(code).setRedirectUri("http://localhost:8080/appweb/ServletOAuth2Callback").execute();
@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(); } } }
flow.newTokenRequest(req.getParameter("code")) .setRedirectUri(WebUtil.buildUrl(req, "/oauth2callback")).execute();
/** * Handles the callback from the OAuth provider, returning a valid Credential if successful. * @param code * @param userId * @return * @throws IOException */ public Credential authorize(String code, @Nullable String userId) throws IOException { String redirectUri = getRedirectUrl(); AuthorizationCodeFlow codeFlow = createCodeFlow(); TokenResponse response = codeFlow .newTokenRequest(code) .setRedirectUri(redirectUri) .setScopes(scopes) .execute(); return codeFlow.createAndStoreCredential(response, userId); }
private UserInfo getUserInfo(String code) { try { final TokenResponse tokenResponse = codeFlow.newTokenRequest(code) .setRedirectUri(configuration.getRedirectedUri()) .execute(); Plus plus = new Plus. Builder(httpTransport, jacksonFactory, codeFlow.createAndStoreCredential(tokenResponse, null)) .setApplicationName(configuration.getApplicationName()) .build(); return toUserInfo(plus.people().get("me").execute()); } catch (IOException e) { log.error("Exception occurred during google oauth2 authentication: {}", e.getMessage()); throw new DlabException("Exception occurred during google oauth2 authentication: " + e.getMessage()); } }
/** * Returns an authorized Bitbucket API service. * @param authorizationCode authorization code received by the redirection * endpoint * @param redirectionEndpoint redirection endpoint URI that was used in the * authorization request; if this argument is <code>null</code>, the * <code>redirect_uri</code> parameter shall not be used. * @return authorized Bitbucket REST API service * @throws IOException if an I/O exception has occurred * @throws NullPointerException if this object has no client credentials */ public Service getService( String authorizationCode, URI redirectionEndpoint) throws IOException { AuthorizationCodeFlow flow = getAuthorizationCodeFlow(true); AuthorizationCodeTokenRequest request = flow.newTokenRequest(authorizationCode); if (redirectionEndpoint != null) { request.setRedirectUri(redirectionEndpoint.toString()); } TokenResponse tokenResponse = request.execute(); String tokenType = tokenResponse.getTokenType(); if (!tokenType.equals(BEARER_TOKEN_TYPE)) { throw new UnknownServiceException("Unsupported token type"); } return new RestService( flow.createAndStoreCredential(tokenResponse, getUser())); }
public Credential authorize() { String authorizationUrl = new AuthorizationCodeRequestUrl(AUTHORIZATION_SERVER_URL, OAuth2ClientCredentials.CLIENT_ID).setRedirectUri(URN_IETF_WG_OAUTH_2_0_OOB).setScopes(SCOPES).build(); System.out.println("Please point your browser to the following URL and copy the access token provided after having authorized this application to access your Google Drive:"); System.out.println(authorizationUrl); String code = readCode(); AuthorizationCodeFlow codeFlow = new AuthorizationCodeFlow.Builder( BearerToken.authorizationHeaderAccessMethod(), HTTP_TRANSPORT, JSON_FACTORY, new GenericUrl( TOKEN_SERVER_URL), new ClientParametersAuthentication(OAuth2ClientCredentials.CLIENT_ID, OAuth2ClientCredentials.CLIENT_SECRET), OAuth2ClientCredentials.CLIENT_ID, AUTHORIZATION_SERVER_URL ).setScopes(SCOPES).build(); try { TokenResponse response = codeFlow.newTokenRequest(code).setScopes(SCOPES).setRedirectUri(URN_IETF_WG_OAUTH_2_0_OOB).execute(); return codeFlow.createAndStoreCredential(response, null); } catch (IOException e) { throw new JDriveSyncException(JDriveSyncException.Reason.IOException, "Failed to execute token request and store credentials: " + e.getMessage(), e); } }
/** * Authenticates using the authorization code for the user and stores the Credential in the * underlying {@link DataStore}. * @throws AuthException If the credential could not be created. */ public Credential authenticate(String authorizationCode, String userId) throws AuthException { Preconditions.checkNotNull(authorizationCode, "Authorization code must not be null"); AuthorizationCodeTokenRequest tokenRequest = authorizationCodeFlow.newTokenRequest(authorizationCode); TokenResponse tokenResponse; try { tokenResponse = tokenRequest .setRedirectUri(redirectUri) .setScopes(scopes) .execute(); } catch (IOException e) { throw new AuthException("Unable to request token.", e); } try { return authorizationCodeFlow.createAndStoreCredential(tokenResponse, userId); } catch (IOException e) { throw new AuthException("Unable to create and store credential.", e); } }
@Override public HttpResponse onSuccess(String authorizationCode) { try { IdTokenResponse response = IdTokenResponse.execute( flow.newTokenRequest(authorizationCode).setRedirectUri(buildOAuthRedirectUrl()) ); IdToken idToken = IdToken.parse( JSON_FACTORY, response.getIdToken()); Object username = idToken.getPayload().get(userNameField); if(username==null) { return HttpResponses.error(500,"no field '"+userNameField+"' was suppied in the token payload to be used as the username"); } if(failedCheckOfTokenField(idToken)) { return HttpResponses.errorWithoutStack(401, "Unauthorized"); } flow.createAndStoreCredential(response, null); loginAndSetUserData(username.toString(), new GrantedAuthority[] { SecurityRealm.AUTHENTICATED_AUTHORITY }, idToken); return new HttpRedirect(redirectOnFinish); } catch (IOException e) { return HttpResponses.error(500,e); } } }.doCommenceLogin();
@Override public Credential handleAuthorizationCallback(HttpServletRequest request) { // Checking if there was an error such as the user denied access String error = getError(request); if (error != null) { throw new NuxeoException("There was an error: \"" + error + "\"."); } // Checking conditions on the "code" URL parameter String code = getAuthorizationCode(request); if (code == null) { throw new NuxeoException("There is not code provided as QueryParam."); } try { AuthorizationCodeFlow flow = getAuthorizationCodeFlow(); String redirectUri = getCallbackUrl(request); TokenResponse tokenResponse = flow.newTokenRequest(code) .setScopes(scopes.isEmpty() ? null : scopes) // some providers do not // support the 'scopes' param .setRedirectUri(redirectUri) .execute(); // Create a unique userId to use with the credential store String userId = getOrCreateServiceUser(request, tokenResponse.getAccessToken()); return flow.createAndStoreCredential(tokenResponse, userId); } catch (IOException e) { throw new NuxeoException("Failed to retrieve credential", e); } }
public Credential authorize(VerificationCodeReceiver receiver, String redirectUri) throws IOException { String code = receiver.waitForCode(); AuthorizationCodeFlow codeFlow = new AuthorizationCodeFlow.Builder( BearerToken.authorizationHeaderAccessMethod(), HTTP_TRANSPORT, JSON_FACTORY, new GenericUrl(TOKEN_SERVER_URL), new ClientParametersAuthentication( OAuth2ClientCredentials.CLIENT_ID, OAuth2ClientCredentials.CLIENT_SECRET), OAuth2ClientCredentials.CLIENT_ID, AUTHORIZATION_SERVER_URL).setScopes(SCOPE).build(); TokenResponse response = codeFlow.newTokenRequest(code) .setRedirectUri(redirectUri).setScopes(SCOPE).execute(); return codeFlow.createAndStoreCredential(response, null); }
final TokenResponse response = flow.newTokenRequest(input.getPassword()) .setRedirectUri(redirectUri).setScopes(scopes.isEmpty() ? null : scopes) .executeUnparsed().parseAs(PermissiveTokenResponse.class).toTokenResponse();
public Credential authorize(VerificationCodeReceiver receiver, String redirectUri) throws IOException { String code = receiver.waitForCode(); AuthorizationCodeFlow codeFlow = new AuthorizationCodeFlow.Builder( BearerToken.authorizationHeaderAccessMethod(), HTTP_TRANSPORT, JSON_FACTORY, new GenericUrl(TOKEN_SERVER_URL), new ClientParametersAuthentication( BaseCloudExample.getAPIKey(), BaseCloudExample.getAPISecret()), BaseCloudExample.getAPIKey(), AUTHORIZATION_SERVER_URL).setScopes(SCOPES).build(); TokenResponse response = codeFlow.newTokenRequest(code) .setRedirectUri(redirectUri).setScopes(SCOPES).execute(); return codeFlow.createAndStoreCredential(response, null); }
/** * 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(); } }
flow.newTokenRequest(code) .setRequestInitializer( request -> {