net.openid.appauth.AuthState Java Examples

The following examples show how to use net.openid.appauth.AuthState. 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: AuthStateManagerTest.java    From okta-sdk-appauth-android with Apache License 2.0 6 votes vote down vote up
@Test
public void testWriteStateLocksPreferencesBeforeActing() {
    assertThat(mPrefs.contains(KEY_STATE)).isFalse();

    mPrefsLock.lock();
    try {
        sut.writeState(new AuthState());
        fail("Expected " + IllegalStateException.class.getSimpleName() + " to be thrown");
    } catch (IllegalStateException e) {
        assertThat(mPrefsLock.getHoldCount()).isEqualTo(1);
        assertThat(mPrefs.contains(KEY_STATE)).isFalse();
    }

    mPrefsLock.unlock();
    sut.writeState(new AuthState());
    assertThat(mPrefsLock.getHoldCount()).isEqualTo(0);
    assertThat(mPrefs.getString(KEY_STATE, null)).isNotNull();
}
 
Example #2
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 #3
Source File: TokenActivity.java    From AppAuth-Android with Apache License 2.0 6 votes vote down vote up
@MainThread
private void signOut() {
    // discard the authorization and token state, but retain the configuration and
    // dynamic client registration (if applicable), to save from retrieving them again.
    AuthState currentState = mStateManager.getCurrent();
    AuthState clearedState =
            new AuthState(currentState.getAuthorizationServiceConfiguration());
    if (currentState.getLastRegistrationResponse() != null) {
        clearedState.update(currentState.getLastRegistrationResponse());
    }
    mStateManager.replace(clearedState);

    Intent mainIntent = new Intent(this, LoginActivity.class);
    mainIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    startActivity(mainIntent);
    finish();
}
 
Example #4
Source File: AuthStateManager.java    From AppAuth-Android with Apache License 2.0 6 votes vote down vote up
@AnyThread
private void writeState(@Nullable AuthState state) {
    mPrefsLock.lock();
    try {
        SharedPreferences.Editor editor = mPrefs.edit();
        if (state == null) {
            editor.remove(KEY_STATE);
        } else {
            editor.putString(KEY_STATE, state.jsonSerializeString());
        }

        if (!editor.commit()) {
            throw new IllegalStateException("Failed to write state to shared prefs");
        }
    } finally {
        mPrefsLock.unlock();
    }
}
 
Example #5
Source File: AuthStateManager.java    From AppAuth-Android with Apache License 2.0 6 votes vote down vote up
@AnyThread
@NonNull
private AuthState readState() {
    mPrefsLock.lock();
    try {
        String currentState = mPrefs.getString(KEY_STATE, null);
        if (currentState == null) {
            return new AuthState();
        }

        try {
            return AuthState.jsonDeserialize(currentState);
        } catch (JSONException ex) {
            Log.w(TAG, "Failed to deserialize stored auth state - discarding");
            return new AuthState();
        }
    } finally {
        mPrefsLock.unlock();
    }
}
 
Example #6
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 #7
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 #8
Source File: AuthStateManager.java    From okta-sdk-appauth-android with Apache License 2.0 6 votes vote down vote up
@AnyThread
@VisibleForTesting
void writeState(@Nullable AuthState state) {
    mPrefsLock.lock();
    try {
        SharedPreferences.Editor editor = mPrefs.edit();
        if (state == null) {
            editor.remove(KEY_STATE);
        } else {
            editor.putString(KEY_STATE, state.jsonSerializeString());
        }

        if (!editor.commit()) {
            throw new IllegalStateException("Failed to write state to shared prefs");
        }
    } finally {
        mPrefsLock.unlock();
    }
}
 
Example #9
Source File: AuthStateManager.java    From okta-sdk-appauth-android with Apache License 2.0 6 votes vote down vote up
@AnyThread
@NonNull
@VisibleForTesting
AuthState readState() {
    mPrefsLock.lock();
    try {
        String currentState = mPrefs.getString(KEY_STATE, null);
        if (currentState == null) {
            return new AuthState();
        }

        try {
            return AuthState.jsonDeserialize(currentState);
        } catch (JSONException ex) {
            Log.w(TAG, "Failed to deserialize stored auth state - discarding");
            return new AuthState();
        }
    } finally {
        mPrefsLock.unlock();
    }
}
 
Example #10
Source File: AuthStateManager.java    From AppAuth-Android with Apache License 2.0 5 votes vote down vote up
@AnyThread
@NonNull
public AuthState getCurrent() {
    if (mCurrentAuthState.get() != null) {
        return mCurrentAuthState.get();
    }

    AuthState state = readState();
    if (mCurrentAuthState.compareAndSet(null, state)) {
        return state;
    } else {
        return mCurrentAuthState.get();
    }
}
 
Example #11
Source File: MainActivity.java    From appauth-android-codelab with Apache License 2.0 5 votes vote down vote up
@Nullable
private AuthState restoreAuthState() {
  String jsonString = getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE)
      .getString(AUTH_STATE, null);
  if (!TextUtils.isEmpty(jsonString)) {
    try {
      return AuthState.fromJson(jsonString);
    } catch (JSONException jsonException) {
      // should never happen
    }
  }
  return null;
}
 
Example #12
Source File: MainActivity.java    From appauth-android-codelab with Apache License 2.0 5 votes vote down vote up
@Nullable
private AuthState restoreAuthState() {
  String jsonString = getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE)
      .getString(AUTH_STATE, null);
  if (!TextUtils.isEmpty(jsonString)) {
    try {
      return AuthState.fromJson(jsonString);
    } catch (JSONException jsonException) {
      // should never happen
    }
  }
  return null;
}
 
Example #13
Source File: MainActivity.java    From appauth-android-codelab with Apache License 2.0 5 votes vote down vote up
@Nullable
private AuthState restoreAuthState() {
  String jsonString = getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE)
      .getString(AUTH_STATE, null);
  if (!TextUtils.isEmpty(jsonString)) {
    try {
      return AuthState.fromJson(jsonString);
    } catch (JSONException jsonException) {
      // should never happen
    }
  }
  return null;
}
 
Example #14
Source File: LoginActivity.java    From AppAuth-Android with Apache License 2.0 5 votes vote down vote up
@MainThread
private void displayAuthOptions() {
    findViewById(R.id.auth_container).setVisibility(View.VISIBLE);
    findViewById(R.id.loading_container).setVisibility(View.GONE);
    findViewById(R.id.error_container).setVisibility(View.GONE);

    AuthState state = mAuthStateManager.getCurrent();
    AuthorizationServiceConfiguration config = state.getAuthorizationServiceConfiguration();

    String authEndpointStr;
    if (config.discoveryDoc != null) {
        authEndpointStr = "Discovered auth endpoint: \n";
    } else {
        authEndpointStr = "Static auth endpoint: \n";
    }
    authEndpointStr += config.authorizationEndpoint;
    ((TextView)findViewById(R.id.auth_endpoint)).setText(authEndpointStr);

    String clientIdStr;
    if (state.getLastRegistrationResponse() != null) {
        clientIdStr = "Dynamic client ID: \n";
    } else {
        clientIdStr = "Static client ID: \n";
    }
    clientIdStr += mClientId;
    ((TextView)findViewById(R.id.client_id)).setText(clientIdStr);
}
 
Example #15
Source File: AuthStateManager.java    From AppAuth-Android with Apache License 2.0 5 votes vote down vote up
@AnyThread
@NonNull
public AuthState replace(@NonNull AuthState state) {
    writeState(state);
    mCurrentAuthState.set(state);
    return state;
}
 
Example #16
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 #17
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 #18
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 #19
Source File: LoginActivity.java    From AppAuth-Android with Apache License 2.0 5 votes vote down vote up
/**
 * Initializes the authorization service configuration if necessary, either from the local
 * static values or by retrieving an OpenID discovery document.
 */
@WorkerThread
private void initializeAppAuth() {
    Log.i(TAG, "Initializing AppAuth");
    recreateAuthorizationService();

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

    // if we are not using discovery, build the authorization service configuration directly
    // from the static configuration values.
    if (mConfiguration.getDiscoveryUri() == null) {
        Log.i(TAG, "Creating auth config from res/raw/auth_config.json");
        AuthorizationServiceConfiguration config = new AuthorizationServiceConfiguration(
                mConfiguration.getAuthEndpointUri(),
                mConfiguration.getTokenEndpointUri(),
                mConfiguration.getRegistrationEndpointUri());

        mAuthStateManager.replace(new AuthState(config));
        initializeClient();
        return;
    }

    // WrongThread inference is incorrect for lambdas
    // noinspection WrongThread
    runOnUiThread(() -> displayLoading("Retrieving discovery document"));
    Log.i(TAG, "Retrieving OpenID discovery doc");
    AuthorizationServiceConfiguration.fetchFromUrl(
            mConfiguration.getDiscoveryUri(),
            this::handleConfigurationRetrievalResult,
            mConfiguration.getConnectionBuilder());
}
 
Example #20
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 #21
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 #22
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 #23
Source File: OktaAppAuth.java    From okta-sdk-appauth-android with Apache License 2.0 5 votes vote down vote up
/**
 * Removes all stored information on current session like
 * Tokens and Authentication Server config.
 * NOTE: After removal {@link OktaAppAuth#init} should be called.
 */
public void clearSession() {
    // discard the authorization and token state, but retain the configuration and
    // dynamic client registration (if applicable), to save from retrieving them again.
    AuthState currentState = mAuthStateManager.getCurrent();
    if (currentState.getAuthorizationServiceConfiguration() != null) {
        AuthState clearedState =
                new AuthState(currentState.getAuthorizationServiceConfiguration());
        if (currentState.getLastRegistrationResponse() != null) {
            clearedState.update(currentState.getLastRegistrationResponse());
        }
        mAuthStateManager.replace(clearedState);
    }
}
 
Example #24
Source File: SharedPreferencesRepository.java    From AppAuthIdentityServer4 with Apache License 2.0 5 votes vote down vote up
public AuthState getAuthState() {
    String authStateString =  PreferenceManager.getDefaultSharedPreferences(mContext).getString("AuthState",null);
    if(authStateString != null){
        try {
            return AuthState.jsonDeserialize(authStateString);
        } catch (JSONException e) {
            e.printStackTrace();
            return null;
        }
    }
    return null;

}
 
Example #25
Source File: MyApp.java    From AppAuthIdentityServer4 with Apache License 2.0 5 votes vote down vote up
@Override
public void onCreate() {
	super.onCreate();

	mSharedPrefRep = new SharedPreferencesRepository(this);

	AuthState authState = mSharedPrefRep.getAuthState();
	if(authState != null)
		Token = authState.getIdToken();

}
 
Example #26
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 #27
Source File: AuthStateManagerTest.java    From okta-sdk-appauth-android with Apache License 2.0 5 votes vote down vote up
@Test
public void testWriteStateRemovesKeyWhenWritingNull() {
    sut.writeState(new AuthState());
    assertThat(mPrefs.getString(KEY_STATE, null)).isNotNull();

    sut.writeState(null);
    assertThat(mPrefs.contains(KEY_STATE)).isFalse();
}
 
Example #28
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 #29
Source File: AuthStateManager.java    From okta-sdk-appauth-android with Apache License 2.0 5 votes vote down vote up
/**
 * Replaces the current AuthState in {@link SharedPreferences} with the provided once.
 *
 * @param state The updated AuthState
 * @return The AuthState which was stored in the SharedPreferences
 */
@AnyThread
@NonNull
public AuthState replace(@NonNull AuthState state) {
    writeState(state);
    mCurrentAuthState.set(state);
    return state;
}
 
Example #30
Source File: AuthStateManager.java    From okta-sdk-appauth-android with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the current AuthState stored in the {@link SharedPreferences}.
 *
 * @return the stored AuthState
 */
@AnyThread
@NonNull
public AuthState getCurrent() {
    if (mCurrentAuthState.get() != null) {
        return mCurrentAuthState.get();
    }

    AuthState state = readState();
    if (mCurrentAuthState.compareAndSet(null, state)) {
        return state;
    } else {
        return mCurrentAuthState.get();
    }
}