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

The following examples show how to use com.google.api.client.auth.oauth2.ClientParametersAuthentication. 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: AuthorizationFlow.java    From android-oauth-client with Apache License 2.0 6 votes vote down vote up
/**
 * Returns a new OAuth 1.0a credential instance based on the given user ID.
 * 
 * @param userId user ID or {@code null} if not using a persisted credential
 *            store
 */
private OAuthHmacCredential new10aCredential(String userId) {
    ClientParametersAuthentication clientAuthentication = (ClientParametersAuthentication) getClientAuthentication();
    OAuthHmacCredential.Builder builder =
            new OAuthHmacCredential.Builder(getMethod(), clientAuthentication.getClientId(),
                    clientAuthentication.getClientSecret())
                    .setTransport(getTransport())
                    .setJsonFactory(getJsonFactory())
                    .setTokenServerEncodedUrl(getTokenServerEncodedUrl())
                    .setClientAuthentication(getClientAuthentication())
                    .setRequestInitializer(getRequestInitializer())
                    .setClock(getClock());
    if (getCredentialStore() != null) {
        builder.addRefreshListener(
                new CredentialStoreRefreshListener(userId, getCredentialStore()));
    }

    builder.getRefreshListeners().addAll(getRefreshListeners());

    return builder.build();
}
 
Example #2
Source File: AuthorizationFlow.java    From android-oauth-client with Apache License 2.0 6 votes vote down vote up
/**
 * Returns a new instance of a token request based on the given verifier
 * code. This step is defined in <a
 * href="http://oauth.net/core/1.0a/#auth_step3">Obtaining an Access
 * Token</a>.
 * 
 * @param temporaryCredentials
 * @param verifierCode
 * @return
 */
public OAuthGetAccessToken new10aTokenRequest(OAuthCredentialsResponse temporaryCredentials,
        String verifierCode) {
    OAuthGetAccessToken request = new OAuthGetAccessToken(getTokenServerEncodedUrl());
    request.temporaryToken = temporaryCredentials.token;
    request.transport = getTransport();

    OAuthHmacSigner signer = new OAuthHmacSigner();
    ClientParametersAuthentication clientAuthentication = (ClientParametersAuthentication) getClientAuthentication();
    signer.clientSharedSecret = clientAuthentication.getClientSecret();
    signer.tokenSharedSecret = temporaryCredentials.tokenSecret;

    request.signer = signer;
    request.consumerKey = clientAuthentication.getClientId();
    request.verifier = verifierCode;
    return request;
}
 
Example #3
Source File: OfflineCredentialsTest.java    From googleads-java-lib with Apache License 2.0 6 votes vote down vote up
/**
 * Tests generating OAuth2 credentials.
 */
@Test
public void testGenerateCredential_defaultTransport() throws Exception {
  OfflineCredentials offlineCredentials = new OfflineCredentials.Builder(oAuth2Helper)
      .forApi(OfflineCredentials.Api.AD_MANAGER)
      .withClientSecrets("clientId", "clientSecret")
      .withRefreshToken("refreshToken")
      .build();

  when(oAuth2Helper.callRefreshToken(Mockito.<Credential>anyObject())).thenReturn(true);

  Credential credential = offlineCredentials.generateCredential();

  assertEquals(
      "clientId",
      ((ClientParametersAuthentication) credential.getClientAuthentication()).getClientId());
  assertEquals(
      "clientSecret",
      ((ClientParametersAuthentication) credential.getClientAuthentication()).getClientSecret());
  assertEquals("refreshToken", credential.getRefreshToken());
  assertSame(ForApiBuilder.DEFAULT_HTTP_TRANSPORT, credential.getTransport());
}
 
Example #4
Source File: GoogleAuthorizationCodeTokenRequestTest.java    From google-api-java-client with Apache License 2.0 6 votes vote down vote up
public void test() {
  GoogleAuthorizationCodeTokenRequest request =
      new GoogleAuthorizationCodeTokenRequest(new MockHttpTransport(),
          new JacksonFactory(),
          CLIENT_ID,
          CLIENT_SECRET,
          CODE,
          REDIRECT_URI);
  ClientParametersAuthentication clientAuthentication =
      (ClientParametersAuthentication) request.getClientAuthentication();
  assertEquals(CLIENT_ID, clientAuthentication.getClientId());
  assertEquals(CLIENT_SECRET, clientAuthentication.getClientSecret());
  assertEquals(CODE, request.getCode());
  assertEquals(REDIRECT_URI, request.getRedirectUri());
  assertEquals("authorization_code", request.getGrantType());
  assertNull(request.getScopes());
  assertNotNull(request.getTokenServerUrl());
}
 
Example #5
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 #6
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 #7
Source File: OfflineCredentialsTest.java    From googleads-java-lib with Apache License 2.0 6 votes vote down vote up
/**
 * Tests generating OAuth2 credentials.
 */
@Test
public void testGenerateCredential() throws Exception {
  HttpTransport httpTransport = new NetHttpTransport();

  OfflineCredentials offlineCredentials = new OfflineCredentials.Builder(oAuth2Helper)
      .forApi(OfflineCredentials.Api.AD_MANAGER)
      .withClientSecrets("clientId", "clientSecret")
      .withRefreshToken("refreshToken")
      .withHttpTransport(httpTransport)
      .build();

  when(oAuth2Helper.callRefreshToken(Mockito.<Credential>anyObject())).thenReturn(true);

  Credential credential = offlineCredentials.generateCredential();

  assertEquals(
      "clientId",
      ((ClientParametersAuthentication) credential.getClientAuthentication()).getClientId());
  assertEquals(
      "clientSecret",
      ((ClientParametersAuthentication) credential.getClientAuthentication()).getClientSecret());
  assertEquals("refreshToken", credential.getRefreshToken());
  assertSame(httpTransport, credential.getTransport());
}
 
Example #8
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 #9
Source File: AuthorizationFlow.java    From android-oauth-client with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the response of a Request Token request as defined in <a
 * href="http://oauth.net/core/1.0a/#auth_step1">Obtaining an Unauthorized
 * Request Token</a>.
 * 
 * @param redirectUri the {@code oauth_callback} as defined in <a
 *            href="http://oauth.net/core/1.0a/#rfc.section.6.1.1">Consumer
 *            Obtains a Request Token</a>
 * @return
 * @throws IOException
 */
public OAuthCredentialsResponse new10aTemporaryTokenRequest(String redirectUri)
        throws IOException {
    OAuthGetTemporaryToken temporaryToken =
            new OAuthGetTemporaryToken(getTemporaryTokenRequestUrl());
    OAuthHmacSigner signer = new OAuthHmacSigner();
    ClientParametersAuthentication clientAuthentication = (ClientParametersAuthentication) getClientAuthentication();
    signer.clientSharedSecret = clientAuthentication.getClientSecret();
    temporaryToken.signer = signer;
    temporaryToken.consumerKey = clientAuthentication.getClientId();
    temporaryToken.callback = redirectUri;
    temporaryToken.transport = getTransport();
    return temporaryToken.execute();
}
 
Example #10
Source File: PlurkActivity.java    From android-oauth-client with Apache License 2.0 5 votes vote down vote up
public PlurkLoader(FragmentActivity activity, DateTime offset) {
    super(activity);
    this.offset = offset;
    oauth = OAuth.newInstance(activity.getApplicationContext(),
            activity.getSupportFragmentManager(),
            new ClientParametersAuthentication(PlurkConstants.CONSUMER_KEY,
                    PlurkConstants.CONSUMER_SECRET),
            PlurkConstants.AUTHORIZATION_VERIFIER_SERVER_URL,
            PlurkConstants.TOKEN_SERVER_URL,
            PlurkConstants.REDIRECT_URL,
            Lists.<String> newArrayList(),
            PlurkConstants.TEMPORARY_TOKEN_REQUEST_URL);
}
 
Example #11
Source File: InstagramActivity.java    From android-oauth-client with Apache License 2.0 5 votes vote down vote up
public InstagramLoader(FragmentActivity activity, String nextMaxId) {
    super(activity);
    this.nextMaxId = nextMaxId;
    oauth = OAuth.newInstance(activity.getApplicationContext(),
            activity.getSupportFragmentManager(),
            new ClientParametersAuthentication(InstagramConstants.CLIENT_ID, null),
            InstagramConstants.AUTHORIZATION_IMPLICIT_SERVER_URL,
            InstagramConstants.TOKEN_SERVER_URL,
            InstagramConstants.REDIRECT_URL,
            Arrays.asList(InstagramScopes.BASIC, InstagramScopes.COMMENTS,
                    InstagramScopes.LIKES, InstagramScopes.RELATIONSHIPS));
}
 
Example #12
Source File: CustomizedProgressActivity.java    From android-oauth-client with Apache License 2.0 5 votes vote down vote up
@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    boolean fullScreen = getActivity().getSharedPreferences("Preference", 0)
        .getBoolean(SamplesActivity.KEY_AUTH_MODE, false);
    // setup credential store
    SharedPreferencesCredentialStore credentialStore =
            new SharedPreferencesCredentialStore(getActivity(),
                    SamplesConstants.CREDENTIALS_STORE_PREF_FILE, OAuth.JSON_FACTORY);
    // setup authorization flow
    AuthorizationFlow flow = new AuthorizationFlow.Builder(
            BearerToken.authorizationHeaderAccessMethod(),
            OAuth.HTTP_TRANSPORT,
            OAuth.JSON_FACTORY,
            new GenericUrl(FoursquareConstants.TOKEN_SERVER_URL),
            new ClientParametersAuthentication(FoursquareConstants.CLIENT_ID, null),
            FoursquareConstants.CLIENT_ID,
            FoursquareConstants.AUTHORIZATION_IMPLICIT_SERVER_URL)
            .setScopes(Lists.<String> newArrayList())
            .setCredentialStore(credentialStore)
            .build();
    // setup UI controller with customized layout
    AuthorizationDialogController controller =
            new CustomController(getFragmentManager(), fullScreen);
    // instantiate an OAuthManager instance
    oauth = new OAuthManager(flow, controller);
}
 
Example #13
Source File: OAuth.java    From android-oauth-client with Apache License 2.0 5 votes vote down vote up
public static OAuth newInstance(Context context,
        FragmentManager fragmentManager,
        ClientParametersAuthentication client,
        String authorizationRequestUrl,
        String tokenServerUrl,
        final String redirectUri,
        List<String> scopes) {
    return newInstance(context, fragmentManager, client,
            authorizationRequestUrl, tokenServerUrl, redirectUri, scopes, null);
}
 
Example #14
Source File: FlickrActivity.java    From android-oauth-client with Apache License 2.0 5 votes vote down vote up
public FlickrLoader(FragmentActivity activity) {
    super(activity);
    oauth = OAuth.newInstance(activity.getApplicationContext(),
            activity.getSupportFragmentManager(),
            new ClientParametersAuthentication(FlickrConstants.CONSUMER_KEY,
                    FlickrConstants.CONSUMER_SECRET),
            FlickrConstants.AUTHORIZATION_VERIFIER_SERVER_URL,
            FlickrConstants.TOKEN_SERVER_URL,
            FlickrConstants.REDIRECT_URL,
            Lists.<String> newArrayList(),
            FlickrConstants.TEMPORARY_TOKEN_REQUEST_URL);
}
 
Example #15
Source File: TwitterActivity.java    From android-oauth-client with Apache License 2.0 5 votes vote down vote up
public TwitterLoader(FragmentActivity activity, String nextMaxId) {
    super(activity);
    this.nextMaxId = nextMaxId;
    oauth = OAuth.newInstance(activity.getApplicationContext(),
            activity.getSupportFragmentManager(),
            new ClientParametersAuthentication(TwitterConstants.CONSUMER_KEY,
                    TwitterConstants.CONSUMER_SECRET),
            TwitterConstants.AUTHORIZATION_VERIFIER_SERVER_URL,
            TwitterConstants.TOKEN_SERVER_URL,
            TwitterConstants.REDIRECT_URL,
            Lists.<String> newArrayList(),
            TwitterConstants.TEMPORARY_TOKEN_REQUEST_URL);
}
 
Example #16
Source File: GitHubActivity.java    From android-oauth-client with Apache License 2.0 5 votes vote down vote up
public GitHubLoader(FragmentActivity activity, int since) {
    super(activity);
    this.page = since;
    this.oauth = OAuth.newInstance(activity.getApplicationContext(),
            activity.getSupportFragmentManager(),
            new ClientParametersAuthentication(GitHubConstants.CLIENT_ID,
                    GitHubConstants.CLIENT_SECRET),
            GitHubConstants.AUTHORIZATION_CODE_SERVER_URL,
            GitHubConstants.TOKEN_SERVER_URL,
            GitHubConstants.REDIRECT_URL,
            Lists.<String> newArrayList());
}
 
Example #17
Source File: MicrosoftCredentialFactory.java    From data-transfer-project with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a {@link Credential} objects with the given {@link TokensAndUrlAuthData} which supports
 * refreshing tokens.
 */
public Credential createCredential(TokensAndUrlAuthData authData) {
  return new Credential.Builder(BearerToken.authorizationHeaderAccessMethod())
      .setTransport(httpTransport)
      .setJsonFactory(jsonFactory)
      .setClientAuthentication(
          new ClientParametersAuthentication(appCredentials.getKey(), appCredentials.getSecret()))
      .setTokenServerEncodedUrl(authData.getTokenServerEncodedUrl())
      .build()
      .setAccessToken(authData.getAccessToken())
      .setRefreshToken(authData.getRefreshToken())
      .setExpiresInSeconds(EXPIRE_TIME_IN_SECONDS);
}
 
Example #18
Source File: GCalGoogleOAuth.java    From openhab1-addons with Eclipse Public License 2.0 5 votes vote down vote up
private static Credential newCredential(String userId, DataStore<StoredCredential> credentialDataStore) {

        Credential.Builder builder = new Credential.Builder(BearerToken.authorizationHeaderAccessMethod())
                .setTransport(HTTP_TRANSPORT).setJsonFactory(JSON_FACTORY)
                .setTokenServerEncodedUrl("https://accounts.google.com/o/oauth2/token")
                .setClientAuthentication(new ClientParametersAuthentication(client_id, client_secret))
                .setRequestInitializer(null).setClock(Clock.SYSTEM);

        builder.addRefreshListener(new DataStoreCredentialRefreshListener(userId, credentialDataStore));

        return builder.build();
    }
 
Example #19
Source File: GoogleIdTokenAuth.java    From styx with Apache License 2.0 5 votes vote down vote up
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 #20
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 #21
Source File: OAuth.java    From JayPS-AndroidApp with MIT License 5 votes vote down vote up
public static OAuth newInstance(Context context,
        FragmentManager fragmentManager,
        ClientParametersAuthentication client,
        String authorizationRequestUrl,
        String tokenServerUrl,
        final String redirectUri,
        List<String> scopes) {
    return newInstance(context, fragmentManager, client,
            authorizationRequestUrl, tokenServerUrl, redirectUri, scopes, null);
}
 
Example #22
Source File: GoogleAuthorizationCodeFlow.java    From google-api-java-client with Apache License 2.0 5 votes vote down vote up
/**
 * @param transport HTTP transport
 * @param jsonFactory JSON factory
 * @param clientSecrets Google client secrets
 * @param scopes collection of scopes to be joined by a space separator
 *
 * @since 1.15
 */
public Builder(HttpTransport transport, JsonFactory jsonFactory,
    GoogleClientSecrets clientSecrets, Collection<String> scopes) {
  super(BearerToken.authorizationHeaderAccessMethod(), transport, jsonFactory, new GenericUrl(
      GoogleOAuthConstants.TOKEN_SERVER_URL), new ClientParametersAuthentication(
      clientSecrets.getDetails().getClientId(), clientSecrets.getDetails().getClientSecret()),
      clientSecrets.getDetails().getClientId(), GoogleOAuthConstants.AUTHORIZATION_SERVER_URL);
  setScopes(scopes);
}
 
Example #23
Source File: StravaActivity.java    From android-oauth-client with Apache License 2.0 4 votes vote down vote up
@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    boolean fullScreen = getActivity().getSharedPreferences("Preference", 0)
            .getBoolean(SamplesActivity.KEY_AUTH_MODE, false);
    // setup credential store
    SharedPreferencesCredentialStore credentialStore =
            new SharedPreferencesCredentialStore(getActivity(),
                    SamplesConstants.CREDENTIALS_STORE_PREF_FILE, OAuth.JSON_FACTORY);
    // setup authorization flow
    AuthorizationFlow flow = new AuthorizationFlow.Builder(
            BearerToken.queryParameterAccessMethod(),
            OAuth.HTTP_TRANSPORT,
            OAuth.JSON_FACTORY,
            new GenericUrl(StravaConstants.URL_TOKEN),
            new ClientParametersAuthentication(StravaConstants.CLIENT_ID,
                    StravaConstants.CLIENT_SECRET),
            StravaConstants.CLIENT_ID,
            StravaConstants.URL_AUTHORIZE)
            .setScopes(Arrays.asList(StravaScopes.SCOPE_PUBLIC))
            .setCredentialStore(credentialStore)
            .setRequestInitializer(new HttpRequestInitializer() {
                @Override
                public void initialize(HttpRequest request) throws IOException {}
            })
            .build();
    // setup UI controller
    AuthorizationDialogController controller =
            new DialogFragmentController(getFragmentManager(), fullScreen) {
                @Override
                public String getRedirectUri() throws IOException {
                    return StravaConstants.REDIRECT_URL;
                }

                @Override
                public boolean isJavascriptEnabledForWebView() {
                    return true;
                }

                @Override
                public boolean disableWebViewCache() {
                    return false;
                }

                @Override
                public boolean removePreviousCookie() {
                    return false;
                }

            };
    // instantiate an OAuthManager instance
    oauth = new OAuthManager(flow, controller);
}
 
Example #24
Source File: ArtikOAuthManager.java    From mirror with Apache License 2.0 4 votes vote down vote up
public static ArtikOAuthManager newInstance(Activity activity, String clientId) {
    // create the ClientParametersAuthentication object
    final ClientParametersAuthentication client = new ClientParametersAuthentication(clientId, null);

    // create JsonFactory
    final JsonFactory jsonFactory = new JacksonFactory();

    // setup credential store
    final SharedPreferencesCredentialStore credentialStore =
            new SharedPreferencesCredentialStore(activity, CREDENTIALS_STORE_PREF_FILE, jsonFactory);

    // setup authorization flow
    AuthorizationFlow flow = new AuthorizationFlow.Builder(
            BearerToken.authorizationHeaderAccessMethod(),
            AndroidHttp.newCompatibleTransport(),
            jsonFactory,
            new GenericUrl(TOKEN_URL),
            client,
            client.getClientId(),
            AUTHORIZATION_URL)
            //.setScopes(scopes)
            .setCredentialStore(credentialStore)
            .build();

    // setup authorization UI controller
    AuthorizationDialogController controller =
            new DialogFragmentController(activity.getFragmentManager()) {
                @Override
                public String getRedirectUri() throws IOException {
                    return REDIRECT_URL;
                }

                @Override
                public boolean isJavascriptEnabledForWebView() {
                    return true;
                }

                @Override
                public boolean disableWebViewCache() {
                    return false;
                }

                @Override
                public boolean removePreviousCookie() {
                    return false;
                }
            };
    return new ArtikOAuthManager(flow, controller);
}
 
Example #25
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 #26
Source File: SimpleOAuth10aActivity.java    From android-oauth-client with Apache License 2.0 4 votes vote down vote up
@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    boolean fullScreen = getActivity().getSharedPreferences("Preference", 0)
        .getBoolean(SamplesActivity.KEY_AUTH_MODE, false);
    // setup credential store
    SharedPreferencesCredentialStore credentialStore =
            new SharedPreferencesCredentialStore(getActivity(),
                    SamplesConstants.CREDENTIALS_STORE_PREF_FILE, OAuth.JSON_FACTORY);
    // setup authorization flow
    AuthorizationFlow flow = new AuthorizationFlow.Builder(
            BearerToken.authorizationHeaderAccessMethod(),
            OAuth.HTTP_TRANSPORT,
            OAuth.JSON_FACTORY,
            new GenericUrl(LinkedInConstants.OAUTH_TOKEN_SERVER_URL),
            new ClientParametersAuthentication(LinkedInConstants.CLIENT_ID,
                    LinkedInConstants.CLIENT_SECRET),
            LinkedInConstants.CLIENT_ID,
            LinkedInConstants.AUTHORIZATION_VERIFIER_SERVER_URL)
            .setTemporaryTokenRequestUrl(LinkedInConstants.TEMPORARY_TOKEN_REQUEST_URL)
            .setScopes(Arrays.asList(LinkedInScopes.READ_BASICPROFILE,
                    LinkedInScopes.READ_FULLPROFILE))
            .setCredentialStore(credentialStore)
            .build();
    // setup UI controller
    AuthorizationDialogController controller =
            new DialogFragmentController(getFragmentManager(), fullScreen) {
                @Override
                public String getRedirectUri() throws IOException {
                    return LinkedInConstants.REDIRECT_URL;
                }

                @Override
                public boolean isJavascriptEnabledForWebView() {
                    return true;
                }

                @Override
                public boolean disableWebViewCache() {
                    return false;
                }

                @Override
                public boolean removePreviousCookie() {
                    return false;
                }

            };
    // instantiate an OAuthManager instance
    oauth10a = new OAuthManager(flow, controller);
}
 
Example #27
Source File: SimpleOAuth2ExplicitActivity.java    From android-oauth-client with Apache License 2.0 4 votes vote down vote up
@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    boolean fullScreen = getActivity().getSharedPreferences("Preference", 0)
        .getBoolean(SamplesActivity.KEY_AUTH_MODE, false);
    // setup credential store
    SharedPreferencesCredentialStore credentialStore =
            new SharedPreferencesCredentialStore(getActivity(),
                    SamplesConstants.CREDENTIALS_STORE_PREF_FILE, OAuth.JSON_FACTORY);
    // setup authorization flow
    AuthorizationFlow flow = new AuthorizationFlow.Builder(
            BearerToken.authorizationHeaderAccessMethod(),
            OAuth.HTTP_TRANSPORT,
            OAuth.JSON_FACTORY,
            new GenericUrl(LinkedInConstants.OAUTH2_TOKEN_SERVER_URL),
            new ClientParametersAuthentication(LinkedInConstants.CLIENT_ID,
                    LinkedInConstants.CLIENT_SECRET),
            LinkedInConstants.CLIENT_ID,
            LinkedInConstants.AUTHORIZATION_CODE_SERVER_URL)
            .setScopes(Arrays.asList(LinkedInScopes.READ_BASICPROFILE,
                    LinkedInScopes.READ_FULLPROFILE))
            .setCredentialStore(credentialStore)
            .build();
    // setup UI controller
    AuthorizationDialogController controller =
            new DialogFragmentController(getFragmentManager(), fullScreen) {
                @Override
                public String getRedirectUri() throws IOException {
                    return LinkedInConstants.REDIRECT_URL;
                }

                @Override
                public boolean isJavascriptEnabledForWebView() {
                    return true;
                }

                @Override
                public boolean disableWebViewCache() {
                    return false;
                }

                @Override
                public boolean removePreviousCookie() {
                    return false;
                }

            };
    // instantiate an OAuthManager instance
    oauth = new OAuthManager(flow, controller);
}
 
Example #28
Source File: OAuth.java    From android-oauth-client with Apache License 2.0 4 votes vote down vote up
public static OAuth newInstance(Context context,
        FragmentManager fragmentManager,
        ClientParametersAuthentication client,
        String authorizationRequestUrl,
        String tokenServerUrl,
        final String redirectUri,
        List<String> scopes,
        String temporaryTokenRequestUrl) {
    Preconditions.checkNotNull(client.getClientId());
    boolean fullScreen = context.getSharedPreferences("Preference", 0)
        .getBoolean(SamplesActivity.KEY_AUTH_MODE, false);
    // setup credential store
    SharedPreferencesCredentialStore credentialStore =
            new SharedPreferencesCredentialStore(context,
                    SamplesConstants.CREDENTIALS_STORE_PREF_FILE, JSON_FACTORY);
    // setup authorization flow
    AuthorizationFlow.Builder flowBuilder = new AuthorizationFlow.Builder(
            BearerToken.authorizationHeaderAccessMethod(),
            HTTP_TRANSPORT,
            JSON_FACTORY,
            new GenericUrl(tokenServerUrl),
            client,
            client.getClientId(),
            authorizationRequestUrl)
            .setScopes(scopes)
            .setCredentialStore(credentialStore);
    // set temporary token request url for 1.0a flow if applicable
    if (!TextUtils.isEmpty(temporaryTokenRequestUrl)) {
        flowBuilder.setTemporaryTokenRequestUrl(temporaryTokenRequestUrl);
    }
    AuthorizationFlow flow = flowBuilder.build();
    // setup authorization UI controller
    AuthorizationDialogController controller =
            new DialogFragmentController(fragmentManager, fullScreen) {

                @Override
                public String getRedirectUri() throws IOException {
                    return redirectUri;
                }

                @Override
                public boolean isJavascriptEnabledForWebView() {
                    return true;
                }

                @Override
                public boolean disableWebViewCache() {
                    return false;
                }

                @Override
                public boolean removePreviousCookie() {
                    return false;
                }

            };
    return new OAuth(flow, controller);
}
 
Example #29
Source File: SimpleOAuth2ImplicitActivity.java    From android-oauth-client with Apache License 2.0 4 votes vote down vote up
@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    boolean fullScreen = getActivity().getSharedPreferences("Preference", 0)
        .getBoolean(SamplesActivity.KEY_AUTH_MODE, false);
    // setup credential store
    SharedPreferencesCredentialStore credentialStore =
            new SharedPreferencesCredentialStore(getActivity(),
                    SamplesConstants.CREDENTIALS_STORE_PREF_FILE, OAuth.JSON_FACTORY);
    // setup authorization flow
    AuthorizationFlow flow = new AuthorizationFlow.Builder(
            BearerToken.authorizationHeaderAccessMethod(),
            OAuth.HTTP_TRANSPORT,
            OAuth.JSON_FACTORY,
            new GenericUrl(FoursquareConstants.TOKEN_SERVER_URL),
            new ClientParametersAuthentication(FoursquareConstants.CLIENT_ID, null),
            FoursquareConstants.CLIENT_ID,
            FoursquareConstants.AUTHORIZATION_IMPLICIT_SERVER_URL)
            .setScopes(Lists.<String> newArrayList())
            .setCredentialStore(credentialStore)
            .build();
    // setup UI controller
    AuthorizationDialogController controller =
            new DialogFragmentController(getFragmentManager(), fullScreen) {
                @Override
                public String getRedirectUri() throws IOException {
                    return FoursquareConstants.REDIRECT_URL;
                }

                @Override
                public boolean isJavascriptEnabledForWebView() {
                    return true;
                }

                @Override
                public boolean disableWebViewCache() {
                    return false;
                }

                @Override
                public boolean removePreviousCookie() {
                    return false;
                }

            };
    // instantiate an OAuthManager instance
    oauth = new OAuthManager(flow, controller);
}
 
Example #30
Source File: SimpleOAuth2ExplicitActivity.java    From android-oauth-client with Apache License 2.0 4 votes vote down vote up
@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    boolean fullScreen = getActivity().getSharedPreferences("Preference", 0)
        .getBoolean(SamplesActivity.KEY_AUTH_MODE, false);
    // setup credential store
    SharedPreferencesCredentialStore credentialStore =
            new SharedPreferencesCredentialStore(getActivity(),
                    SamplesConstants.CREDENTIALS_STORE_PREF_FILE, OAuth.JSON_FACTORY);
    // setup authorization flow
    AuthorizationFlow flow = new AuthorizationFlow.Builder(
            BearerToken.authorizationHeaderAccessMethod(),
            OAuth.HTTP_TRANSPORT,
            OAuth.JSON_FACTORY,
            new GenericUrl(FoursquareConstants.TOKEN_SERVER_URL),
            new ClientParametersAuthentication(FoursquareConstants.CLIENT_ID,
                    FoursquareConstants.CLIENT_SECRET),
            FoursquareConstants.CLIENT_ID,
            FoursquareConstants.AUTHORIZATION_CODE_SERVER_URL)
            .setScopes(Lists.<String> newArrayList())
            .setCredentialStore(credentialStore)
            .build();
    // setup UI controller
    AuthorizationDialogController controller =
            new DialogFragmentController(getFragmentManager(), fullScreen) {
                @Override
                public String getRedirectUri() throws IOException {
                    return FoursquareConstants.REDIRECT_URL;
                }

                @Override
                public boolean isJavascriptEnabledForWebView() {
                    return true;
                }

                @Override
                public boolean disableWebViewCache() {
                    return false;
                }

                @Override
                public boolean removePreviousCookie() {
                    return false;
                }

            };
    // instantiate an OAuthManager instance
    oauth = new OAuthManager(flow, controller);
}