net.openid.appauth.AuthorizationException Java Examples

The following examples show how to use net.openid.appauth.AuthorizationException. 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: OktaAppAuth.java    From okta-sdk-appauth-android with Apache License 2.0 6 votes vote down vote up
@MainThread
private void handleConfigurationRetrievalResult(AuthorizationServiceConfiguration config,
                                                AuthorizationException ex) {
    if (config == null) {
        Log.e(TAG, "Failed to retrieve discovery document", ex);
        mInitializationListener.get().onTokenFailure(ex);
        return;
    }

    Log.i(TAG, "Discovery document retrieved");
    mAuthStateManager.replace(new AuthState(config));
    mExecutor.submit(new Runnable() {
        @Override
        public void run() {
            initializeClient();
        }
    });
}
 
Example #2
Source File: TokenActivity.java    From AppAuth-Android with Apache License 2.0 6 votes vote down vote up
@WorkerThread
private void handleCodeExchangeResponse(
        @Nullable TokenResponse tokenResponse,
        @Nullable AuthorizationException authException) {

    mStateManager.updateAfterTokenResponse(tokenResponse, authException);
    if (!mStateManager.getCurrent().isAuthorized()) {
        final String message = "Authorization Code exchange failed"
                + ((authException != null) ? authException.error : "");

        // WrongThread inference is incorrect for lambdas
        //noinspection WrongThread
        runOnUiThread(() -> displayNotAuthorized(message));
    } else {
        runOnUiThread(this::displayAuthorized);
    }
}
 
Example #3
Source File: MainActivity.java    From appauth-android-codelab with Apache License 2.0 6 votes vote down vote up
/**
 * Exchanges the code, for the {@link TokenResponse}.
 *
 * @param intent represents the {@link Intent} from the Custom Tabs or the System Browser.
 */
private void handleAuthorizationResponse(@NonNull Intent intent) {
  AuthorizationResponse response = AuthorizationResponse.fromIntent(intent);
  AuthorizationException error = AuthorizationException.fromIntent(intent);
  final AuthState authState = new AuthState(response, error);
  if (response != null) {
    Log.i(LOG_TAG, String.format("Handled Authorization Response %s ", authState.toJsonString()));
    AuthorizationService service = new AuthorizationService(this);
    service.performTokenRequest(response.createTokenExchangeRequest(), new AuthorizationService.TokenResponseCallback() {
      @Override
      public void onTokenRequestCompleted(@Nullable TokenResponse tokenResponse, @Nullable AuthorizationException exception) {
        if (exception != null) {
          Log.w(LOG_TAG, "Token Exchange failed", exception);
        } else {
          if (tokenResponse != null) {
            authState.update(tokenResponse, exception);
            persistAuthState(authState);
            Log.i(LOG_TAG, String.format("Token Response [ Access Token: %s, ID Token: %s ]", tokenResponse.accessToken, tokenResponse.idToken));
          }
        }
      }
    });
  }
}
 
Example #4
Source File: MainActivity.java    From appauth-android-codelab with Apache License 2.0 6 votes vote down vote up
/**
 * Exchanges the code, for the {@link TokenResponse}.
 *
 * @param intent represents the {@link Intent} from the Custom Tabs or the System Browser.
 */
private void handleAuthorizationResponse(@NonNull Intent intent) {
  AuthorizationResponse response = AuthorizationResponse.fromIntent(intent);
  AuthorizationException error = AuthorizationException.fromIntent(intent);
  final AuthState authState = new AuthState(response, error);

  if (response != null) {
    Log.i(LOG_TAG, String.format("Handled Authorization Response %s ", authState.toJsonString()));
    AuthorizationService service = new AuthorizationService(this);
    service.performTokenRequest(response.createTokenExchangeRequest(), new AuthorizationService.TokenResponseCallback() {
      @Override
      public void onTokenRequestCompleted(@Nullable TokenResponse tokenResponse, @Nullable AuthorizationException exception) {
        if (exception != null) {
          Log.w(LOG_TAG, "Token Exchange failed", exception);
        } else {
          if (tokenResponse != null) {
            authState.update(tokenResponse, exception);
            persistAuthState(authState);
            Log.i(LOG_TAG, String.format("Token Response [ Access Token: %s, ID Token: %s ]", tokenResponse.accessToken, tokenResponse.idToken));
          }
        }
      }
    });
  }
}
 
Example #5
Source File: LoginActivity.java    From AirMapSDK-Android with Apache License 2.0 6 votes vote down vote up
@Override
public void onTokenRequestCompleted(TokenResponse tokenResponse, AuthorizationException exception) {
    // exchange succeeded
    if (tokenResponse != null) {
        // send credentials via private broadcast back to callback
        sendBroadcast(tokenResponse);

        // close invisible activity
        finish();

    // authorization failed, check exception
    } else {
        if (exception != null) {
            Log.e("Token request failed", exception.toString());
        }

        //TODO: send failure via private broadcast back to callback?

        // close invisible activity
        finish();
    }
}
 
Example #6
Source File: UserInfoActivity.java    From okta-sdk-appauth-android with Apache License 2.0 6 votes vote down vote up
/**
 * Demonstrates how to manually refresh the access token.
 */
@MainThread
private void refreshAccessToken() {
    displayLoading("Refreshing access token");
    mOktaAppAuth.refreshAccessToken(new OktaAppAuth.OktaAuthListener() {
        @Override
        public void onSuccess() {
            runOnUiThread(() -> displayAuthorizationInfo());
        }

        @Override
        public void onTokenFailure(@NonNull AuthorizationException ex) {
            runOnUiThread(() -> showSnackbar(getString(R.string.token_failure_message)));
        }
    });
}
 
Example #7
Source File: UserInfoActivity.java    From okta-sdk-appauth-android with Apache License 2.0 6 votes vote down vote up
@MainThread
private void clearData() {
    mOktaAppAuth.revoke(new OktaAppAuth.OktaRevokeListener() {
        @Override
        public void onSuccess() {
            mOktaAppAuth.clearSession();
            startActivity(new Intent(UserInfoActivity.this, StartActivity.class));
            finish();
        }

        @Override
        public void onError(AuthorizationException ex) {
            showSnackbar("Unable to clean data");
        }
    });
}
 
Example #8
Source File: OktaManagementActivity.java    From okta-sdk-appauth-android with Apache License 2.0 6 votes vote down vote up
@WorkerThread
private void handleCodeExchangeResponse(
        @Nullable TokenResponse tokenResponse,
        @Nullable AuthorizationException authException) {

    mStateManager.updateAfterTokenResponse(tokenResponse, authException);
    if (!mStateManager.getCurrent().isAuthorized()) {
        final String message = "Authorization Code exchange failed"
                + ((authException != null) ? authException.error : "");
        Log.e(TAG, message);
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                sendPendingIntent(mCancelIntent);
            }
        });
    } else {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                sendPendingIntent(mCompleteIntent);
            }
        });
    }
}
 
Example #9
Source File: OktaManagementActivity.java    From okta-sdk-appauth-android with Apache License 2.0 6 votes vote down vote up
@Override
protected void onStart() {
    super.onStart();
    OAuthClientConfiguration config = OAuthClientConfiguration.getInstance(this);
    if (config.hasConfigurationChanged()) {
        signOut();
        return;
    }
    // the stored AuthState is incomplete, so check if we are currently receiving the result of
    // the authorization flow from the browser.
    AuthorizationManagementResponse response =
            AuthorizationManagementResponse.fromIntent(getIntent());
    AuthorizationException ex = AuthorizationException.fromIntent(getIntent());

    if (ex != null || response == null) {
        Log.w(TAG, "Authorization flow failed: " + ex);
        sendPendingIntent(mCancelIntent);
    } else if (isLoginFlow(response)) {
        runLoginFlow((AuthorizationResponse) response, ex);
    } else {
        sendPendingIntent(mCompleteIntent);
    }

}
 
Example #10
Source File: OktaManagementActivity.java    From okta-sdk-appauth-android with Apache License 2.0 6 votes vote down vote up
private void runLoginFlow(AuthorizationResponse response, AuthorizationException ex) {

        if (mStateManager.getCurrent().isAuthorized()) {
            sendPendingIntent(mCompleteIntent);
            return;
        }

        if (response != null || ex != null) {
            mStateManager.updateAfterAuthorization(response, ex);
        }

        if (response != null && response.authorizationCode != null) {
            // authorization code exchange is required
            exchangeAuthorizationCode(response);
        }
    }
 
Example #11
Source File: AuthStateManager.java    From AppAuth-Android with Apache License 2.0 5 votes vote down vote up
@AnyThread
@NonNull
public AuthState updateAfterAuthorization(
        @Nullable AuthorizationResponse response,
        @Nullable AuthorizationException ex) {
    AuthState current = getCurrent();
    current.update(response, ex);
    return replace(current);
}
 
Example #12
Source File: OktaAppAuth.java    From okta-sdk-appauth-android with Apache License 2.0 5 votes vote down vote up
@WorkerThread
private void handleAccessTokenResponse(
        @Nullable TokenResponse tokenResponse,
        @Nullable AuthorizationException authException,
        @NonNull OktaAuthListener listener) {
    mAuthStateManager.updateAfterTokenResponse(tokenResponse, authException);
    if (authException == null) {
        listener.onSuccess();
    } else {
        Log.i(TAG, "Encountered an error with the access token response", authException);
        listener.onTokenFailure(authException);
    }
}
 
Example #13
Source File: LoginActivity.java    From AirMapSDK-Android with Apache License 2.0 5 votes vote down vote up
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    overridePendingTransition(0, 0);

    // parse response & exception
    Intent intent = getIntent();
    AuthorizationResponse response = AuthorizationResponse.fromIntent(intent);
    AuthorizationException exception = AuthorizationException.fromIntent(intent);

    // authorization completed
    if (response != null) {
        Timber.e("authorization completed: " + response.jsonSerializeString());

        // create authorization service to exchange token
        authService = new AuthorizationService(this);
        authService.performTokenRequest(response.createTokenExchangeRequest(), this);

    // authorization failed, check exception
    } else if (exception != null) {
        Timber.e("authorization failed: " + exception.toString());

        // if cancelled, just close activity
        if (exception.code == AuthorizationException.GeneralErrors.USER_CANCELED_AUTH_FLOW.code) {
            finish();
        }
    }
}
 
Example #14
Source File: OktaAppAuth.java    From okta-sdk-appauth-android with Apache License 2.0 5 votes vote down vote up
@WorkerThread
private void doInit(final Context context, final ConnectionBuilder connectionBuilder,
                    final OktaAuthListener listener) {
    mInitializationListener.set(listener);
    recreateAuthorizationService(context);

    if (mConfiguration.hasConfigurationChanged()) {
        // discard any existing authorization state due to the change of configuration
        Log.i(TAG, "Configuration change detected, discarding old state");
        mAuthStateManager.replace(new AuthState());
        if (!mConfiguration.isValid()) {
            Log.e(TAG, "Configuration was invalid: " + mConfiguration.getConfigurationError());
            listener.onTokenFailure(
                    AuthorizationException.GeneralErrors.INVALID_DISCOVERY_DOCUMENT);
            return;
        }
        mConfiguration.acceptConfiguration();
    }


    if (mAuthStateManager.getCurrent().getAuthorizationServiceConfiguration() != null) {
        // configuration is already created, skip to client initialization
        Log.i(TAG, "auth config already established");
        initializeClient();
        return;
    }

    Log.i(TAG, "Retrieving OpenID discovery doc");
    AuthorizationServiceConfiguration.fetchFromUrl(
            mConfiguration.getDiscoveryUri(),
            new AuthorizationServiceConfiguration.RetrieveConfigurationCallback() {
                @Override
                public void onFetchConfigurationCompleted(
                        @Nullable AuthorizationServiceConfiguration serviceConfiguration,
                        @Nullable AuthorizationException ex) {
                    handleConfigurationRetrievalResult(serviceConfiguration, ex);
                }
            },
            connectionBuilder);
}
 
Example #15
Source File: AuthStateManager.java    From AppAuth-Android with Apache License 2.0 5 votes vote down vote up
@AnyThread
@NonNull
public AuthState updateAfterTokenResponse(
        @Nullable TokenResponse response,
        @Nullable AuthorizationException ex) {
    AuthState current = getCurrent();
    current.update(response, ex);
    return replace(current);
}
 
Example #16
Source File: AuthStateManager.java    From AppAuth-Android with Apache License 2.0 5 votes vote down vote up
@AnyThread
@NonNull
public AuthState updateAfterRegistration(
        RegistrationResponse response,
        AuthorizationException ex) {
    AuthState current = getCurrent();
    if (ex != null) {
        return current;
    }

    current.update(response);
    return replace(current);
}
 
Example #17
Source File: TokenActivity.java    From AppAuth-Android with Apache License 2.0 5 votes vote down vote up
@Override
protected void onStart() {
    super.onStart();

    if (mExecutor.isShutdown()) {
        mExecutor = Executors.newSingleThreadExecutor();
    }

    if (mStateManager.getCurrent().isAuthorized()) {
        displayAuthorized();
        return;
    }

    // the stored AuthState is incomplete, so check if we are currently receiving the result of
    // the authorization flow from the browser.
    AuthorizationResponse response = AuthorizationResponse.fromIntent(getIntent());
    AuthorizationException ex = AuthorizationException.fromIntent(getIntent());

    if (response != null || ex != null) {
        mStateManager.updateAfterAuthorization(response, ex);
    }

    if (response != null && response.authorizationCode != null) {
        // authorization code exchange is required
        mStateManager.updateAfterAuthorization(response, ex);
        exchangeAuthorizationCode(response);
    } else if (ex != null) {
        displayNotAuthorized("Authorization flow failed: " + ex.getMessage());
    } else {
        displayNotAuthorized("No authorization state retained - reauthorization required");
    }
}
 
Example #18
Source File: TokenActivity.java    From AppAuth-Android with Apache License 2.0 5 votes vote down vote up
@WorkerThread
private void handleAccessTokenResponse(
        @Nullable TokenResponse tokenResponse,
        @Nullable AuthorizationException authException) {
    mStateManager.updateAfterTokenResponse(tokenResponse, authException);
    runOnUiThread(this::displayAuthorized);
}
 
Example #19
Source File: LoginActivity.java    From AppAuth-Android with Apache License 2.0 5 votes vote down vote up
@MainThread
private void handleConfigurationRetrievalResult(
        AuthorizationServiceConfiguration config,
        AuthorizationException ex) {
    if (config == null) {
        Log.i(TAG, "Failed to retrieve discovery document", ex);
        displayError("Failed to retrieve discovery document: " + ex.getMessage(), true);
        return;
    }

    Log.i(TAG, "Discovery document retrieved");
    mAuthStateManager.replace(new AuthState(config));
    mExecutor.submit(this::initializeClient);
}
 
Example #20
Source File: LoginActivity.java    From AppAuth-Android with Apache License 2.0 5 votes vote down vote up
@MainThread
private void handleRegistrationResponse(
        RegistrationResponse response,
        AuthorizationException ex) {
    mAuthStateManager.updateAfterRegistration(response, ex);
    if (response == null) {
        Log.i(TAG, "Failed to dynamically register client", ex);
        displayErrorLater("Failed to register client: " + ex.getMessage(), true);
        return;
    }

    Log.i(TAG, "Dynamically registered client: " + response.clientId);
    mClientId.set(response.clientId);
    initializeAuthRequest();
}
 
Example #21
Source File: AuthStateManager.java    From okta-sdk-appauth-android with Apache License 2.0 5 votes vote down vote up
/**
 * Called after the token exchange is complete or a refresh token is used to acquire a new
 * access token.
 *
 * @param response The TokenResponse from the Authorization Server
 * @param ex Any AuthorizationException that occurred during the token exchange
 * @return The updated AuthState
 */
@AnyThread
@NonNull
public AuthState updateAfterTokenResponse(
        @Nullable TokenResponse response,
        @Nullable AuthorizationException ex) {
    AuthState current = getCurrent();
    current.update(response, ex);
    return replace(current);
}
 
Example #22
Source File: TokenService.java    From AppAuthIdentityServer4 with Apache License 2.0 5 votes vote down vote up
@Override
public void run() {

    if(MyApp.Token == null)
        return;

    final AuthManager authManager = AuthManager.getInstance(TokenService.this);

    final AuthState authState = authManager.getAuthState();


    if(authState.getNeedsTokenRefresh()) {
        //Get New Token

        ClientSecretPost clientSecretPost = new ClientSecretPost(authManager.getAuth().getClientSecret());
        final TokenRequest request = authState.createTokenRefreshRequest();
        final AuthorizationService authService = authManager.getAuthService();

        authService.performTokenRequest(request, clientSecretPost, new AuthorizationService.TokenResponseCallback() {
            @Override
            public void onTokenRequestCompleted(@Nullable TokenResponse response, @Nullable AuthorizationException ex) {
                if(ex != null){
                    ex.printStackTrace();
                    return;
                }
                authManager.updateAuthState(response,ex);
                MyApp.Token = authState.getIdToken();
            }
        });

    }

}
 
Example #23
Source File: SessionAuthorizeActivity.java    From okta-sdk-appauth-android with Apache License 2.0 5 votes vote down vote up
/**
 * Initializes the OktaAppAuth object. This is required before it can be used to authorize
 * users for your app.
 */
@MainThread
private void initializeOktaAuth() {
    Log.i(TAG, "Initializing OktaAppAuth");
    displayLoading(getString(R.string.loading_initializing));

    mOktaAppAuth.init(
            this,
            new OktaAppAuth.OktaAuthListener() {
                @Override
                public void onSuccess() {
                    runOnUiThread(() -> {
                        if (mOktaAppAuth.isUserLoggedIn()) {
                            Log.i(TAG, "User is already authenticated, proceeding " +
                                    "to token activity");
                            startActivity(new Intent(SessionAuthorizeActivity.this,
                                    UserInfoActivity.class));
                            finish();
                        } else {
                            Log.i(TAG, "Login activity setup finished");
                            displayAuthOptions();
                        }
                    });
                }

                @Override
                public void onTokenFailure(@NonNull AuthorizationException ex) {
                    runOnUiThread(() -> showMessage(getString(R.string.init_failure)
                            + ":"
                            + ex.errorDescription));
                }
            });
}
 
Example #24
Source File: LoginActivity.java    From okta-sdk-appauth-android with Apache License 2.0 5 votes vote down vote up
/**
 * Initializes the OktaAppAuth object. This is required before it can be used to authorize
 * users for your app.
 */
@MainThread
private void initializeOktaAuth() {
    Log.i(TAG, "Initializing OktaAppAuth");
    displayLoading(getString(R.string.loading_initializing));

    mOktaAppAuth.init(
            this,
            new OktaAppAuth.OktaAuthListener() {
                @Override
                public void onSuccess() {
                    runOnUiThread(() -> {
                        if (mOktaAppAuth.isUserLoggedIn()) {
                            Log.i(TAG, "User is already authenticated, proceeding " +
                                    "to token activity");
                            startActivity(new Intent(LoginActivity.this,
                                    UserInfoActivity.class));
                            finish();
                        } else {
                            Log.i(TAG, "Login activity setup finished");
                            displayAuthOptions();
                        }
                    });
                }

                @Override
                public void onTokenFailure(@NonNull AuthorizationException ex) {
                    runOnUiThread(() -> showMessage(getString(R.string.init_failure)
                            + ":"
                            + ex.errorDescription));
                }
            },
            getColorCompat(R.color.colorPrimary));
}
 
Example #25
Source File: AuthStateManager.java    From okta-sdk-appauth-android with Apache License 2.0 5 votes vote down vote up
/**
 * Called after the app receives the callback from the authorization code flow. This updates
 * the state to prepare for the token exchange.
 *
 * @param response The AuthorizationResponse from the Authorization Server
 * @param ex Any AuthorizationException that occurred during the authorization code flow
 * @return The updated AuthState
 */
@AnyThread
@NonNull
public AuthState updateAfterAuthorization(
        @Nullable AuthorizationResponse response,
        @Nullable AuthorizationException ex) {
    AuthState current = getCurrent();
    current.update(response, ex);
    return replace(current);
}
 
Example #26
Source File: OktaAppAuth.java    From okta-sdk-appauth-android with Apache License 2.0 5 votes vote down vote up
/**
 * Refreshes the access token if a refresh token is available to do so. This method will
 * do nothing if there is no refresh token.
 *
 * @param listener An OktaAuthSuccessListener that will be called once the refresh is complete
 */
public void refreshAccessToken(final OktaAuthListener listener) {
    if (!hasRefreshToken()) {
        Log.d(TAG, "Calling refreshAccessToken without a refresh token");
        listener.onTokenFailure(AuthorizationException.TokenRequestErrors.INVALID_REQUEST);
        return;
    }

    ClientAuthentication clientAuthentication;
    try {
        clientAuthentication = mAuthStateManager.getCurrent().getClientAuthentication();
    } catch (UnsupportedAuthenticationMethod ex) {
        Log.e(TAG, "Token request cannot be made; client authentication for the token "
                + "endpoint could not be constructed (%s)", ex);
        listener.onTokenFailure(AuthorizationException.TokenRequestErrors.INVALID_REQUEST);
        return;
    }


    createAuthorizationServiceIfNeeded().performTokenRequest(
            mAuthStateManager.getCurrent().createTokenRefreshRequest(),
            clientAuthentication,
            new AuthorizationService.TokenResponseCallback() {
                @Override
                public void onTokenRequestCompleted(@Nullable TokenResponse tokenResponse,
                                                    @Nullable AuthorizationException
                                                            authException) {
                    handleAccessTokenResponse(
                            tokenResponse,
                            authException,
                            listener);
                }
            });
}
 
Example #27
Source File: OktaAppAuth.java    From okta-sdk-appauth-android with Apache License 2.0 4 votes vote down vote up
/**
 * Performs revocation of accessToken and refreshToken if they are available.
 *
 * @param listener revocation callback {@link OktaRevokeListener}
 */
public void revoke(@NonNull final OktaRevokeListener listener) {

    if (!isUserLoggedIn()) {
        throw new IllegalStateException("No logged in user found");
    }
    if (mConfiguration.hasConfigurationChanged()) {
        throw new IllegalStateException("Okta Configuration has changed");
    }
    if (mAuthStateManager.getCurrent().getAuthorizationServiceConfiguration() == null) {
        throw new IllegalStateException("Okta should be initialized first");
    }

    if (mAuthStateManager.getCurrent().getRefreshToken() != null) {
        //if we have refresh token we have to perform revoke it first
        mExecutor.submit(new Runnable() {
            @Override
            public void run() {
                doRevoke(
                        mAuthStateManager.getCurrent().getRefreshToken(),
                        new OktaRevokeListener() {
                        @Override
                        public void onSuccess() {
                                doRevoke(mAuthStateManager
                                                .getCurrent().getAccessToken(),
                                        listener);
                        }

                        @Override
                        public void onError(AuthorizationException ex) {
                                listener.onError(ex);
                        }
                    });
            }
        });
    } else {
        mExecutor.submit(new Runnable() {
            @Override
            public void run() {
                doRevoke(mAuthStateManager.getCurrent().getAccessToken(), listener);
            }
        });
    }

}
 
Example #28
Source File: AuthManager.java    From AppAuthIdentityServer4 with Apache License 2.0 4 votes vote down vote up
public void updateAuthState(TokenResponse response, AuthorizationException ex){
	mAuthState.update(response,ex);
	mSharedPrefRep.saveAuthState(mAuthState);
}
 
Example #29
Source File: RNAppAuthModule.java    From react-native-app-auth with MIT License 4 votes vote down vote up
@ReactMethod
public void register(
    String issuer,
    final ReadableArray redirectUris,
    final ReadableArray responseTypes,
    final ReadableArray grantTypes,
    final String subjectType,
    final String tokenEndpointAuthMethod,
    final ReadableMap additionalParameters,
    final ReadableMap serviceConfiguration,
    final boolean dangerouslyAllowInsecureHttpRequests,
    final ReadableMap headers,
    final Promise promise
) {
    this.parseHeaderMap(headers);
    final ConnectionBuilder builder = createConnectionBuilder(dangerouslyAllowInsecureHttpRequests, this.registrationRequestHeaders);
    final AppAuthConfiguration appAuthConfiguration = this.createAppAuthConfiguration(builder);
    final HashMap<String, String> additionalParametersMap = MapUtil.readableMapToHashMap(additionalParameters);

    // when serviceConfiguration is provided, we don't need to hit up the OpenID well-known id endpoint
    if (serviceConfiguration != null || hasServiceConfiguration(issuer)) {
        try {
            final AuthorizationServiceConfiguration serviceConfig = hasServiceConfiguration(issuer)? getServiceConfiguration(issuer) : createAuthorizationServiceConfiguration(serviceConfiguration);
            registerWithConfiguration(
                    serviceConfig,
                    appAuthConfiguration,
                    redirectUris,
                    responseTypes,
                    grantTypes,
                    subjectType,
                    tokenEndpointAuthMethod,
                    additionalParametersMap,
                    promise
            );
        } catch (Exception e) {
            promise.reject("registration_failed", e.getMessage());
        }
    } else {
        final Uri issuerUri = Uri.parse(issuer);
        AuthorizationServiceConfiguration.fetchFromUrl(
                buildConfigurationUriFromIssuer(issuerUri),
                new AuthorizationServiceConfiguration.RetrieveConfigurationCallback() {
                    public void onFetchConfigurationCompleted(
                            @Nullable AuthorizationServiceConfiguration fetchedConfiguration,
                            @Nullable AuthorizationException ex) {
                        if (ex != null) {
                            promise.reject("service_configuration_fetch_error", getErrorMessage(ex));
                            return;
                        }

                        setServiceConfiguration(issuer, fetchedConfiguration);

                        registerWithConfiguration(
                                fetchedConfiguration,
                                appAuthConfiguration,
                                redirectUris,
                                responseTypes,
                                grantTypes,
                                subjectType,
                                tokenEndpointAuthMethod,
                                additionalParametersMap,
                                promise
                        );
                    }
                },
                builder);
    }
}
 
Example #30
Source File: TokenActivity.java    From AppAuth-Android with Apache License 2.0 4 votes vote down vote up
@MainThread
private void fetchUserInfo(String accessToken, String idToken, AuthorizationException ex) {
    if (ex != null) {
        Log.e(TAG, "Token refresh failed when fetching user info");
        mUserInfoJson.set(null);
        runOnUiThread(this::displayAuthorized);
        return;
    }

    AuthorizationServiceDiscovery discovery =
            mStateManager.getCurrent()
                    .getAuthorizationServiceConfiguration()
                    .discoveryDoc;

    URL userInfoEndpoint;
    try {
        userInfoEndpoint =
                mConfiguration.getUserInfoEndpointUri() != null
                    ? new URL(mConfiguration.getUserInfoEndpointUri().toString())
                    : new URL(discovery.getUserinfoEndpoint().toString());
    } catch (MalformedURLException urlEx) {
        Log.e(TAG, "Failed to construct user info endpoint URL", urlEx);
        mUserInfoJson.set(null);
        runOnUiThread(this::displayAuthorized);
        return;
    }

    mExecutor.submit(() -> {
        try {
            HttpURLConnection conn =
                    (HttpURLConnection) userInfoEndpoint.openConnection();
            conn.setRequestProperty("Authorization", "Bearer " + accessToken);
            conn.setInstanceFollowRedirects(false);
            String response = Okio.buffer(Okio.source(conn.getInputStream()))
                    .readString(Charset.forName("UTF-8"));
            mUserInfoJson.set(new JSONObject(response));
        } catch (IOException ioEx) {
            Log.e(TAG, "Network error when querying userinfo endpoint", ioEx);
            showSnackbar("Fetching user info failed");
        } catch (JSONException jsonEx) {
            Log.e(TAG, "Failed to parse userinfo response");
            showSnackbar("Failed to parse user info");
        }

        runOnUiThread(this::displayAuthorized);
    });
}