com.google.api.client.auth.oauth2.AuthorizationCodeRequestUrl Java Examples

The following examples show how to use com.google.api.client.auth.oauth2.AuthorizationCodeRequestUrl. 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: AuthorizationCodeInstalledApp.java    From google-oauth-java-client with Apache License 2.0 6 votes vote down vote up
/**
 * 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 #2
Source File: CustomAuthorizationCodeInstalledApp.java    From pentaho-kettle with Apache License 2.0 6 votes vote down vote up
protected void onAuthorization( AuthorizationCodeRequestUrl authorizationUrl ) throws IOException {
  String url = authorizationUrl.build();
  Spoon spoon = Spoon.getInstance();
  if ( spoon != null ) {

    Display.getDefault().syncExec( new Runnable() {

      public void run() {
        Shell shell = spoon.getShell();
        GoogleAuthorizationDialog authorizationDialog = new GoogleAuthorizationDialog( shell, getReceiver() );
        authorizationDialog.open( url );
      }
    } );

  } else {
    browse( url );
  }
}
 
Example #3
Source File: GApiGateway.java    From gdx-gamesvcs with Apache License 2.0 6 votes vote down vote up
/**
 * Authorizes the installed application to access user's protected data.
 */
public static void authorize(String userID, boolean driveAPI) throws IOException {
    // load client secrets

    // set up authorization code flow
    Collection<String> scopes = new ArrayList<String>();
    scopes.add(GamesScopes.GAMES);
    if (driveAPI)
        scopes.add(DriveScopes.DRIVE_APPDATA);

    GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(httpTransport, JSON_FACTORY,
            clientSecrets, scopes).setDataStoreFactory(dataStoreFactory).build();
    // authorize
    Credential credential = new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()) {
        // Override open browser not working well on Linux and maybe other
        // OS.
        protected void onAuthorization(AuthorizationCodeRequestUrl authorizationUrl) throws java.io.IOException {
            Gdx.net.openURI(authorizationUrl.build());
        }
    }.authorize(userID);

    games = new Games.Builder(httpTransport, JSON_FACTORY, credential).setApplicationName(applicationName).build();
    if (driveAPI)
        drive = new Drive.Builder(httpTransport, JSON_FACTORY, credential).setApplicationName(applicationName).build();

}
 
Example #4
Source File: OicSession.java    From oic-auth-plugin with MIT License 5 votes vote down vote up
/**
 * Starts the login session.
 * @return an {@link HttpResponse}
 */
@SuppressFBWarnings("J2EE_STORE_OF_NON_SERIALIZABLE_OBJECT_INTO_SESSION")
public HttpResponse doCommenceLogin() {
    // remember this in the session
    Stapler.getCurrentRequest().getSession().setAttribute(SESSION_NAME, this);
    AuthorizationCodeRequestUrl authorizationCodeRequestUrl = flow.newAuthorizationUrl().setState(state).setRedirectUri(redirectUrl);
    return new HttpRedirect(authorizationCodeRequestUrl.toString());
}
 
Example #5
Source File: OAuthAuthenticator.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * 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();
}
 
Example #6
Source File: OIDCRequestManager.java    From android-java-connect-rest-sample with MIT License 5 votes vote down vote up
/**
 * Generates an Authentication Request URL to the Authorization Endpoint to start an Code Flow.
 * When using the Code Flow, all tokens are returned from the Token Endpoint.
 * The Authorization Server can authenticate the Client before exchanging the Authorization Code
 * for an Access Token.
 * @see <a href="http://openid.net/specs/openid-connect-core-1_0.html#CodeFlowAuth">Code Flow</a>
 *
 * @param state the state used to maintain state between the request and the callback.
 * @return the Authentication Request URL
 */
private AuthorizationRequestUrl codeFlowAuthenticationUrl(String state) {

    List<String> scopesList = Arrays.asList(scopes);

    //noinspection UnnecessaryLocalVariable
    AuthorizationCodeRequestUrl request = new AuthorizationCodeRequestUrl(authorizationEndpoint, clientId)
            .setRedirectUri(redirectUrl)
            .setScopes(scopesList)
            .setState(state)
            .set("nonce", ""); //TODO: nonce is optional, needs to include per-session state and be unguessable to attackers. We should try to generate one.

    return request;
}
 
Example #7
Source File: AuthorizationCodeInstalledAppTalend.java    From components with Apache License 2.0 5 votes vote down vote up
@Override
protected void onAuthorization(AuthorizationCodeRequestUrl authorizationUrl) throws IOException {
    try {
        Desktop.isDesktopSupported();
        browse(authorizationUrl.build());
    } catch (Exception e) {
        LOG.warn("Failed to open browser with Desktop browse method.");
        browseWithProgramLauncher(authorizationUrl.build());
    }
}
 
Example #8
Source File: AbstractAuthorizationCodeServlet.java    From google-oauth-java-client with Apache License 2.0 5 votes vote down vote up
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp)
    throws IOException, ServletException {
  lock.lock();
  try {
    // load credential from persistence store
    String userId = getUserId(req);
    if (flow == null) {
      flow = initializeFlow();
    }
    credential = flow.loadCredential(userId);
    // if credential found with an access token, invoke the user code
    if (credential != null && credential.getAccessToken() != null) {
      try {
        super.service(req, resp);
        return;
      } catch (HttpResponseException e) {
        // if access token is null, assume it is because auth failed and we need to re-authorize
        // but if access token is not null, it is some other problem
        if (credential.getAccessToken() != null) {
          throw e;
        }
      }
    }
    // redirect to the authorization flow
    AuthorizationCodeRequestUrl authorizationUrl = flow.newAuthorizationUrl();
    authorizationUrl.setRedirectUri(getRedirectUri(req));
    onAuthorization(req, resp, authorizationUrl);
    credential = null;
  } finally {
    lock.unlock();
  }
}
 
Example #9
Source File: CustomAuthorizationCodeInstalledApp.java    From hop with Apache License 2.0 5 votes vote down vote up
protected void onAuthorization( AuthorizationCodeRequestUrl authorizationUrl ) throws IOException {
  String url = authorizationUrl.build();
  HopGui hopGui = HopGui.getInstance();
  if ( hopGui != null ) {

    Display.getDefault().syncExec( () -> {
      Shell shell = hopGui.getShell();
      GoogleAuthorizationDialog authorizationDialog = new GoogleAuthorizationDialog( shell, getReceiver() );
      authorizationDialog.open( url );
    } );

  } else {
    browse( url );
  }
}
 
Example #10
Source File: OpenIdConnectAuthenticator.java    From fess with Apache License 2.0 5 votes vote down vote up
protected String getAuthUrl(final HttpServletRequest request) {
    final String state = UuidUtil.create();
    request.getSession().setAttribute(OIC_STATE, state);
    return new AuthorizationCodeRequestUrl(getOicAuthServerUrl(), getOicClientId())//
            .setScopes(Arrays.asList(getOicScope()))//
            .setResponseTypes(Arrays.asList("code"))//
            .setRedirectUri(getOicRedirectUrl())//
            .setState(state)//
            .build();
}
 
Example #11
Source File: OAuthManager.java    From android-oauth-client with Apache License 2.0 4 votes vote down vote up
/**
 * Authorizes the Android application to access user's protected data using
 * the Explicit Authorization Code flow in OAuth 2.0.
 * 
 * @param userId user ID or {@code null} if not using a persisted credential
 *            store
 * @param callback Callback to invoke when the request completes,
 *            {@code null} for no callback
 * @param handler {@link Handler} identifying the callback thread,
 *            {@code null} for the main thread
 * @return An {@link OAuthFuture} which resolves to a {@link Credential}
 */
public OAuthFuture<Credential> authorizeExplicitly(final String userId,
        final OAuthCallback<Credential> callback, Handler handler) {
    Preconditions.checkNotNull(userId);

    final Future2Task<Credential> task = new Future2Task<Credential>(handler, callback) {

        @Override
        public void doWork() throws Exception {
            try {
                Credential credential = mFlow.loadCredential(userId);
                LOGGER.info("authorizeExplicitly");
                if (credential != null && credential.getAccessToken() != null
                        && (credential.getRefreshToken() != null ||
                                credential.getExpiresInSeconds() == null ||
                        credential.getExpiresInSeconds() > 60)) {
                    set(credential);
                    return;
                }

                String redirectUri = mUIController.getRedirectUri();

                AuthorizationCodeRequestUrl authorizationUrl = mFlow
                        .newExplicitAuthorizationUrl()
                        .setRedirectUri(redirectUri);
                mUIController.requestAuthorization(authorizationUrl);

                String code = mUIController.waitForExplicitCode();
                TokenResponse response = mFlow.newTokenRequest(code)
                        .setRedirectUri(redirectUri).execute();
                credential = mFlow.createAndStoreCredential(response, userId);
                set(credential);
            } finally {
                mUIController.stop();
            }
        }

    };

    // run the task in a background thread
    submitTaskToExecutor(task);

    return task;
}
 
Example #12
Source File: DialogFragmentController.java    From android-oauth-client with Apache License 2.0 4 votes vote down vote up
@Override
public void requestAuthorization(AuthorizationCodeRequestUrl authorizationRequestUrl) {
    internalRequestAuthorization(authorizationRequestUrl);
}
 
Example #13
Source File: OAuthDialogFragment.java    From android-oauth-client with Apache License 2.0 4 votes vote down vote up
@TargetApi(HONEYCOMB)
public static final OAuthDialogFragment newInstance(
        GenericUrl authorizationRequestUrl,
        DialogFragmentController controller) {
    Bundle args = new Bundle();
    args.putString(ARG_AUTHORIZATION_REQUEST_URL, authorizationRequestUrl.build());
    if (authorizationRequestUrl instanceof OAuthAuthorizeTemporaryTokenUrl) {
        args.putString(ARG_AUTHORIZATION_TYPE, AUTHORIZATION_10A);
    } else if (authorizationRequestUrl instanceof AuthorizationCodeRequestUrl) {
        args.putString(ARG_AUTHORIZATION_TYPE, AUTHORIZATION_EXPLICIT);
    } else {
        args.putString(ARG_AUTHORIZATION_TYPE, AUTHORIZATION_IMPLICIT);
    }
    BaseDialogFragmentImpl fragImpl;
    OAuthDialogFragment frag;
    if (controller.getFragmentManager() instanceof android.support.v4.app.FragmentManager) {
        fragImpl = new SupportDialogFragmentImpl();
        frag = new OAuthDialogFragment((android.support.v4.app.DialogFragment) fragImpl,
            controller.fullScreen, controller.horizontalProgress, controller.hideFullScreenTitle);
        if (controller.hideFullScreenTitle) {
            if (SDK_INT >= ICE_CREAM_SANDWICH) {
                ((android.support.v4.app.DialogFragment) fragImpl).setStyle(android.support
                        .v4.app.DialogFragment.STYLE_NORMAL,
                    android.R.style.Theme_Holo_Light_NoActionBar_Fullscreen
                );
            } else {
                ((android.support.v4.app.DialogFragment) fragImpl).setStyle(android.support
                        .v4.app.DialogFragment.STYLE_NORMAL,
                    android.R.style.Theme_Black_NoTitleBar_Fullscreen
                );
            }
        }
    } else {
        fragImpl = new NativeDialogFragmentImpl();
        frag = new OAuthDialogFragment((android.app.DialogFragment) fragImpl,
            controller.fullScreen, controller.horizontalProgress, controller.hideFullScreenTitle);
        if (controller.hideFullScreenTitle) {
            if (SDK_INT >= ICE_CREAM_SANDWICH) {
                ((android.app.DialogFragment) fragImpl).setStyle(DialogFragment.STYLE_NORMAL,
                    android.R.style.Theme_Holo_Light_NoActionBar_Fullscreen);
            } else {
                ((android.app.DialogFragment) fragImpl).setStyle(DialogFragment.STYLE_NORMAL,
                    android.R.style.Theme_Black_NoTitleBar_Fullscreen);
            }
        }
    }
    fragImpl.setDialogFragmentCompat(frag);
    frag.setArguments(args);
    frag.setController(controller);
    return frag;
}
 
Example #14
Source File: AbstractAuthorizationCodeServlet.java    From google-oauth-java-client with Apache License 2.0 2 votes vote down vote up
/**
 * Handles user authorization by redirecting to the OAuth 2.0 authorization server.
 *
 * <p>
 * Default implementation is to call {@code resp.sendRedirect(authorizationUrl.build())}.
 * Subclasses may override to provide optional parameters such as the recommended state parameter.
 * Sample implementation:
 * </p>
 *
 * <pre>
&#64;Override
protected void onAuthorization(HttpServletRequest req, HttpServletResponse resp,
    AuthorizationCodeRequestUrl authorizationUrl) throws ServletException, IOException {
  authorizationUrl.setState("xyz");
  super.onAuthorization(req, resp, authorizationUrl);
}
 * </pre>
 *
 * @param authorizationUrl authorization code request URL
 * @param req HTTP servlet request
 * @throws ServletException servlet exception
 * @since 1.11
 */
protected void onAuthorization(HttpServletRequest req, HttpServletResponse resp,
    AuthorizationCodeRequestUrl authorizationUrl) throws ServletException, IOException {
  resp.sendRedirect(authorizationUrl.build());
}
 
Example #15
Source File: AuthorizationCodeInstalledApp.java    From google-oauth-java-client with Apache License 2.0 2 votes vote down vote up
/**
 * Handles user authorization by redirecting to the OAuth 2.0 authorization server.
 *
 * <p>
 * Default implementation is to call {@code browse(authorizationUrl.build())}. Subclasses may
 * override to provide optional parameters such as the recommended state parameter. Sample
 * implementation:
 * </p>
 *
 * <pre>
&#64;Override
protected void onAuthorization(AuthorizationCodeRequestUrl authorizationUrl) throws IOException {
  authorizationUrl.setState("xyz");
  super.onAuthorization(authorizationUrl);
}
 * </pre>
 *
 * @param authorizationUrl authorization URL
 * @throws IOException I/O exception
 */
protected void onAuthorization(AuthorizationCodeRequestUrl authorizationUrl) throws IOException {
  String url = authorizationUrl.build();
  Preconditions.checkNotNull(url);
  browser.browse(url);
}
 
Example #16
Source File: AuthorizationUIController.java    From android-oauth-client with Apache License 2.0 2 votes vote down vote up
/**
 * Handles user authorization by redirecting to the OAuth 2.0 authorization
 * server as defined in <a
 * href="http://tools.ietf.org/html/rfc6749#section-4.1.1">Authorization
 * Request</a>.
 * 
 * @param authorizationRequestUrl
 */
void requestAuthorization(AuthorizationCodeRequestUrl authorizationRequestUrl);
 
Example #17
Source File: AuthorizationFlow.java    From android-oauth-client with Apache License 2.0 2 votes vote down vote up
/**
 * Returns a new instance of an explicit authorization code request URL.
 * <p>
 * This is a builder for an authorization web page to allow the end user to
 * authorize the application to access their protected resources and that
 * returns an authorization code. It uses the
 * {@link #getAuthorizationServerEncodedUrl()}, {@link #getClientId()}, and
 * {@link #getScopes()}. Sample usage:
 * </p>
 * 
 * <pre>
 * private AuthorizationFlow flow;
 * 
 * public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
 *     String url = flow.newExplicitAuthorizationUrl().setState(&quot;xyz&quot;)
 *             .setRedirectUri(&quot;https://client.example.com/rd&quot;).build();
 *     response.sendRedirect(url);
 * }
 * </pre>
 */
public AuthorizationCodeRequestUrl newExplicitAuthorizationUrl() {
    return newAuthorizationUrl();
}