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

The following examples show how to use com.google.api.client.auth.oauth2.AuthorizationCodeFlow. 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: OAuthServletCallback.java    From vpn-over-dns with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
protected AuthorizationCodeFlow initializeFlow() throws IOException {
	return new AuthorizationCodeFlow.Builder(BearerToken.authorizationHeaderAccessMethod(),
			new NetHttpTransport(),
			new JacksonFactory(),
			// token server URL:
			// new GenericUrl("https://server.example.com/token"),
			new GenericUrl("https://accounts.google.com/o/oauth2/auth"),
			new BasicAuthentication("458072371664.apps.googleusercontent.com",
					"mBp75wknGsGu0WMzHaHhqfXT"),
			"458072371664.apps.googleusercontent.com",
			// authorization server URL:
			"https://accounts.google.com/o/oauth2/auth").
			// setCredentialStore(new JdoCredentialStore(JDOHelper.getPersistenceManagerFactory("transactions-optional")))
			setCredentialStore(new MemoryCredentialStore()).setScopes("https://mail.google.com/")
			// setCredentialStore(new MyCredentialStore())
			.build();
}
 
Example #2
Source File: OAuthServlet.java    From vpn-over-dns with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
protected AuthorizationCodeFlow initializeFlow() throws IOException {
	return new AuthorizationCodeFlow.Builder(BearerToken.authorizationHeaderAccessMethod(),
			new NetHttpTransport(),
			new JacksonFactory(),
			// token server URL:
			// new GenericUrl("https://server.example.com/token"),
			new GenericUrl("https://accounts.google.com/o/oauth2/auth"),
			new BasicAuthentication("458072371664.apps.googleusercontent.com",
					"mBp75wknGsGu0WMzHaHhqfXT"),
			"458072371664.apps.googleusercontent.com",
			// authorization server URL:
			"https://accounts.google.com/o/oauth2/auth").
			// setCredentialStore(new JdoCredentialStore(JDOHelper.getPersistenceManagerFactory("transactions-optional")))
			setCredentialStore(new MemoryCredentialStore()).setScopes("https://mail.google.com/")
			// setCredentialStore(new MyCredentialStore())
			.build();
}
 
Example #3
Source File: DailyMotionSample.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. */
private static Credential authorize() throws Exception {
  OAuth2ClientCredentials.errorIfNotSpecified();
  // set up authorization code flow
  AuthorizationCodeFlow flow = new AuthorizationCodeFlow.Builder(BearerToken
      .authorizationHeaderAccessMethod(),
      HTTP_TRANSPORT,
      JSON_FACTORY,
      new GenericUrl(TOKEN_SERVER_URL),
      new ClientParametersAuthentication(
          OAuth2ClientCredentials.API_KEY, OAuth2ClientCredentials.API_SECRET),
      OAuth2ClientCredentials.API_KEY,
      AUTHORIZATION_SERVER_URL).setScopes(Arrays.asList(SCOPE))
      .setDataStoreFactory(DATA_STORE_FACTORY).build();
  // authorize
  LocalServerReceiver receiver = new LocalServerReceiver.Builder().setHost(
      OAuth2ClientCredentials.DOMAIN).setPort(OAuth2ClientCredentials.PORT).build();
  return new AuthorizationCodeInstalledApp(flow, receiver).authorize("user");
}
 
Example #4
Source File: PKCESample.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. */
private static Credential authorize() throws Exception {
    // set up authorization code flow
    String clientId = "pkce-test-client";
    AuthorizationCodeFlow flow = new AuthorizationCodeFlow.Builder(
            BearerToken.authorizationHeaderAccessMethod(),
            HTTP_TRANSPORT,
            JSON_FACTORY,
            new GenericUrl(TOKEN_SERVER_URL),
            new ClientParametersAuthentication(clientId, null),
            clientId,
            AUTHORIZATION_SERVER_URL)
            .setScopes(Arrays.asList(SCOPE))
            .enablePKCE()
            .setDataStoreFactory(DATA_STORE_FACTORY).build();
    // authorize
    LocalServerReceiver receiver = new LocalServerReceiver.Builder().setHost("127.0.0.1").build();
    return new AuthorizationCodeInstalledApp(flow, receiver).authorize("user");
}
 
Example #5
Source File: AbstractSession.java    From scava with Eclipse Public License 2.0 5 votes vote down vote up
protected String retrieveAccessToken(String accessTokenUrl, String authorizationUrl, String clientId,
									 String clientSecret, List<String> scopes, String user) throws IOException {
	JsonFactory jsonFactory = new JacksonFactory();
	HttpTransport httpTransport = new NetHttpTransport();
	AuthorizationCodeFlow flow = new AuthorizationCodeFlow.Builder(BearerToken.authorizationHeaderAccessMethod(),
			httpTransport, jsonFactory, new GenericUrl(accessTokenUrl),
			new ClientParametersAuthentication(clientId, clientSecret), clientId, authorizationUrl)
			.setScopes(scopes).build();
	LocalServerReceiver receiver = new LocalServerReceiver.Builder().setHost(receiverHost).setPort(receiverPort)
			.build();
	return new AuthorizationCodeInstalledApp(flow, receiver).authorize(user).getAccessToken();
}
 
Example #6
Source File: OAuthAuthenticator.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * This method should be invoked by child class for initialization default instance of {@link
 * AuthorizationCodeFlow} that will be used for authorization
 */
protected void configure(
    String clientId,
    String clientSecret,
    String[] redirectUris,
    String authUri,
    String tokenUri,
    MemoryDataStoreFactory dataStoreFactory,
    List<String> scopes)
    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();

  LOG.debug(
      "clientId={}, clientSecret={}, redirectUris={} , authUri={}, tokenUri={}, dataStoreFactory={}",
      clientId,
      clientSecret,
      redirectUris,
      authUri,
      tokenUri,
      dataStoreFactory);

  configure(authorizationFlow, Arrays.asList(redirectUris));
}
 
Example #7
Source File: OAuthAuthenticator.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * This method should be invoked by child class for setting instance of {@link
 * AuthorizationCodeFlow} that will be used for authorization
 */
protected void configure(AuthorizationCodeFlow flow, List<String> redirectUris) {
  this.flow = flow;
  this.redirectUrisMap = new HashMap<>(redirectUris.size());
  for (String uri : redirectUris) {
    // Redirect URI may be in form urn:ietf:wg:oauth:2.0:oob os use java.net.URI instead of
    // java.net.URL
    this.redirectUrisMap.put(
        Pattern.compile("([a-z0-9\\-]+\\.)?" + URI.create(uri).getHost()), uri);
  }
}
 
Example #8
Source File: AuthorizationCodeInstalledApp.java    From google-oauth-java-client with Apache License 2.0 5 votes vote down vote up
/**
 * @param flow authorization code flow
 * @param receiver verification code receiver
 */
public AuthorizationCodeInstalledApp(
    AuthorizationCodeFlow flow, VerificationCodeReceiver receiver, Browser browser) {
  this.flow = Preconditions.checkNotNull(flow);
  this.receiver = Preconditions.checkNotNull(receiver);
  this.browser = browser;
}
 
Example #9
Source File: CustomAuthorizationCodeInstalledApp.java    From pentaho-kettle with Apache License 2.0 4 votes vote down vote up
public CustomAuthorizationCodeInstalledApp( AuthorizationCodeFlow flow, VerificationCodeReceiver receiver ) {
  super( flow, receiver );
}
 
Example #10
Source File: CustomAuthorizationCodeInstalledApp.java    From hop with Apache License 2.0 4 votes vote down vote up
public CustomAuthorizationCodeInstalledApp( AuthorizationCodeFlow flow, VerificationCodeReceiver receiver ) {
  super( flow, receiver );
}
 
Example #11
Source File: AuthorizationCodeInstalledApp.java    From google-oauth-java-client with Apache License 2.0 4 votes vote down vote up
/** Returns the authorization code flow. */
public final AuthorizationCodeFlow getFlow() {
  return flow;
}
 
Example #12
Source File: AuthorizationCodeInstalledApp.java    From google-oauth-java-client with Apache License 2.0 4 votes vote down vote up
/**
 * @param flow authorization code flow
 * @param receiver verification code receiver
 */
public AuthorizationCodeInstalledApp(
    AuthorizationCodeFlow flow, VerificationCodeReceiver receiver) {
  this(flow, receiver,  new DefaultBrowser());
}
 
Example #13
Source File: AuthorizationCodeInstalledAppTalend.java    From components with Apache License 2.0 4 votes vote down vote up
public AuthorizationCodeInstalledAppTalend(AuthorizationCodeFlow flow, VerificationCodeReceiver receiver) {
    super(flow, receiver);
}
 
Example #14
Source File: OAuth2Credentials.java    From rides-java-sdk with MIT License 4 votes vote down vote up
/**
 * Gets the underlying {@link AuthorizationCodeFlow}.
 */
public AuthorizationCodeFlow getAuthorizationCodeFlow() {
    return authorizationCodeFlow;
}
 
Example #15
Source File: OAuth2Credentials.java    From rides-java-sdk with MIT License 4 votes vote down vote up
/**
 * Sets the authorization code flow.
 */
public Builder setAuthorizationCodeFlow(AuthorizationCodeFlow authorizationCodeFlow) {
    this.authorizationCodeFlow = authorizationCodeFlow;
    return this;
}
 
Example #16
Source File: Oauth2AuthorizationCodeServlet.java    From java-docs-samples with Apache License 2.0 4 votes vote down vote up
@Override
protected AuthorizationCodeFlow initializeFlow() throws IOException {
  return Utils.newFlow();
}
 
Example #17
Source File: Oauth2CallbackServlet.java    From java-docs-samples with Apache License 2.0 4 votes vote down vote up
/**
 * Loads the authorization code flow to be used across all HTTP servlet requests (only called
 * during the first HTTP servlet request with an authorization code).
 */
@Override
protected AuthorizationCodeFlow initializeFlow() throws IOException {
  return Utils.newFlow();
}
 
Example #18
Source File: OicSecurityRealm.java    From oic-auth-plugin with MIT License 4 votes vote down vote up
/**
 * Handles the the securityRealm/commenceLogin resource and sends the user off to the IdP
 * @param from the relative URL to the page that the user has just come from
 * @param referer the HTTP referer header (where to redirect the user back to after login has finished)
 * @return an {@link HttpResponse} object
*/
public HttpResponse doCommenceLogin(@QueryParameter String from, @Header("Referer") final String referer) {
    final String redirectOnFinish = determineRedirectTarget(from, referer);

    final AuthorizationCodeFlow flow = new AuthorizationCodeFlow.Builder(
            BearerToken.queryParameterAccessMethod(),
            httpTransport,
            JSON_FACTORY,
            new GenericUrl(tokenServerUrl),
            new ClientParametersAuthentication(
                    clientId,
                    clientSecret.getPlainText()
            ),
            clientId,
            authorizationServerUrl
    )
        .setScopes(Arrays.asList(scopes))
        .build();

    return new OicSession(flow, from, buildOAuthRedirectUrl()) {
        @Override
        public HttpResponse onSuccess(String authorizationCode) {
            try {
                AuthorizationCodeTokenRequest tokenRequest = flow.newTokenRequest(authorizationCode)
                    .setRedirectUri(buildOAuthRedirectUrl());
                // Supplying scope is not allowed when obtaining an access token with an authorization code.
                tokenRequest.setScopes(Collections.<String>emptyList());

                IdTokenResponse response = IdTokenResponse.execute(tokenRequest);

                this.setIdToken(response.getIdToken());

                IdToken idToken = IdToken.parse(JSON_FACTORY, response.getIdToken());

                Object username;
                GenericJson userInfo = null;
                if (Strings.isNullOrEmpty(userInfoServerUrl)) {
                    username = getField(idToken.getPayload(), userNameField);
                    if(username == null) {
                        return HttpResponses.error(500,"no field '" + userNameField + "' was supplied in the token payload to be used as the username");
                    }
                } else {
                    userInfo = getUserInfo(flow, response.getAccessToken());
                    username = getField(userInfo, userNameField);
                    if(username == null) {
                        return HttpResponses.error(500,"no field '" + userNameField + "' was supplied by the UserInfo payload to be used as the username");
                    }
                }

                if(failedCheckOfTokenField(idToken)) {
                    return HttpResponses.errorWithoutStack(401, "Unauthorized");
                }

                flow.createAndStoreCredential(response, null);

                loginAndSetUserData(username.toString(), idToken, userInfo);

                return new HttpRedirect(redirectOnFinish);

            } catch (IOException e) {
                return HttpResponses.error(500,e);
            }

        }
    }.doCommenceLogin();
}
 
Example #19
Source File: OicSession.java    From oic-auth-plugin with MIT License 4 votes vote down vote up
OicSession(AuthorizationCodeFlow flow, String from, String redirectUrl) {
    this.flow = flow;
    this.from = from;
    this.redirectUrl = redirectUrl;
}
 
Example #20
Source File: AbstractAuthorizationCodeServlet.java    From google-oauth-java-client with Apache License 2.0 2 votes vote down vote up
/**
 * Loads the authorization code flow to be used across all HTTP servlet requests (only called
 * during the first HTTP servlet request).
 */
protected abstract AuthorizationCodeFlow initializeFlow() throws ServletException, IOException;
 
Example #21
Source File: AbstractAuthorizationCodeCallbackServlet.java    From google-oauth-java-client with Apache License 2.0 2 votes vote down vote up
/**
 * Loads the authorization code flow to be used across all HTTP servlet requests (only called
 * during the first HTTP servlet request with an authorization code).
 */
protected abstract AuthorizationCodeFlow initializeFlow() throws ServletException, IOException;