Search in sources :

Example 1 with WebAuthClient

use of com.okta.oidc.clients.web.WebAuthClient in project okta-oidc-android by okta.

the class SessionClientImplTest method setUp.

@Before
public void setUp() throws Exception {
    mContext = InstrumentationRegistry.getInstrumentation().getTargetContext();
    mEndPoint = new MockEndPoint();
    mGson = new Gson();
    mStorage = new SharedPreferenceStorage(mContext);
    String url = mEndPoint.getUrl();
    mClientFactory = new HttpClientFactory();
    mClientFactory.setClientType(mClientType);
    mConfig = TestValues.getConfigWithUrl(url);
    mProviderConfig = TestValues.getProviderConfiguration(url);
    mTokenResponse = TokenResponse.RESTORE.restore(TOKEN_RESPONSE);
    WebAuthClient okta = new Okta.WebAuthBuilder().withCallbackExecutor(mExecutor).withConfig(mConfig).withOktaHttpClient(mClientFactory.build()).withContext(mContext).withStorage(mStorage).withEncryptionManager(new EncryptionManagerStub()).create();
    mSessionClient = okta.getSessionClient();
    OktaState mOktaState = new OktaState(new OktaRepository(mStorage, mContext, new EncryptionManagerStub(), false, false));
    mOktaState.save(mTokenResponse);
    mOktaState.save(mProviderConfig);
}
Also used : SharedPreferenceStorage(com.okta.oidc.storage.SharedPreferenceStorage) OktaState(com.okta.oidc.OktaState) OktaRepository(com.okta.oidc.storage.OktaRepository) MockEndPoint(com.okta.oidc.util.MockEndPoint) Gson(com.google.gson.Gson) WebAuthClient(com.okta.oidc.clients.web.WebAuthClient) EncryptionManagerStub(com.okta.oidc.util.EncryptionManagerStub) Okta(com.okta.oidc.Okta) HttpClientFactory(com.okta.oidc.util.HttpClientFactory) Before(org.junit.Before)

Example 2 with WebAuthClient

use of com.okta.oidc.clients.web.WebAuthClient in project okta-oidc-android by okta.

the class SampleActivity method onCreate.

@Override
protected void onCreate(Bundle savedInstanceState) {
    Log.d(TAG, "onCreate");
    super.onCreate(savedInstanceState);
    setContentView(R.layout.sample_activity);
    mCancel = findViewById(R.id.cancel);
    mCheckExpired = findViewById(R.id.check_expired);
    mSignInBrowser = findViewById(R.id.sign_in);
    mSignInNative = findViewById(R.id.sign_in_native);
    mSignOut = findViewById(R.id.sign_out);
    mClearData = findViewById(R.id.clear_data);
    mRevokeContainer = findViewById(R.id.revoke_token);
    mRevokeAccess = findViewById(R.id.revoke_access);
    mRevokeRefresh = findViewById(R.id.revoke_refresh);
    mRefreshToken = findViewById(R.id.refresh_token);
    mGetProfile = findViewById(R.id.get_profile);
    mProgressBar = findViewById(R.id.progress_horizontal);
    mTvStatus = findViewById(R.id.status);
    mIntrospectRefresh = findViewById(R.id.introspect_refresh);
    mIntrospectAccess = findViewById(R.id.introspect_access);
    mIntrospectId = findViewById(R.id.introspect_id);
    mSwitch = findViewById(R.id.switch1);
    mEditText = findViewById(R.id.login_hint);
    mStorageOidc = new SharedPreferenceStorage(this);
    boolean checked = getSharedPreferences(SampleActivity.class.getName(), MODE_PRIVATE).getBoolean(PREF_SWITCH, true);
    mIsSessionSignIn = getSharedPreferences(SampleActivity.class.getName(), MODE_PRIVATE).getBoolean(PREF_NON_WEB, true);
    mSwitch.setChecked(checked);
    mSwitch.setOnCheckedChangeListener((buttonView, isChecked) -> {
        // reset callbacks
        setupCallback();
        if (getSessionClient().isAuthenticated()) {
            showAuthenticatedMode();
        } else {
            showSignedOutMode();
        }
        mSwitch.setText(isChecked ? "OIDC" : "OAuth2");
    });
    mCheckExpired.setOnClickListener(v -> {
        SessionClient client = getSessionClient();
        try {
            mTvStatus.setText(client.getTokens().isAccessTokenExpired() ? "token expired" : "token not expired");
        } catch (AuthorizationException e) {
            Log.d(TAG, "", e);
        }
    });
    mIntrospectRefresh.setOnClickListener(v -> {
        showNetworkProgress(true);
        SessionClient client = getSessionClient();
        String refreshToken;
        try {
            refreshToken = client.getTokens().getRefreshToken();
            client.introspectToken(refreshToken, TokenTypeHint.REFRESH_TOKEN, new RequestCallback<IntrospectInfo, AuthorizationException>() {

                @Override
                public void onSuccess(@NonNull IntrospectInfo result) {
                    mTvStatus.setText("RefreshToken active: " + result.isActive());
                    mProgressBar.setVisibility(View.GONE);
                }

                @Override
                public void onError(String error, AuthorizationException exception) {
                    mTvStatus.setText("RefreshToken Introspect error");
                    mProgressBar.setVisibility(View.GONE);
                }
            });
        } catch (AuthorizationException e) {
            Log.d(TAG, "", e);
        }
    });
    mIntrospectAccess.setOnClickListener(v -> {
        showNetworkProgress(true);
        SessionClient client = getSessionClient();
        try {
            client.introspectToken(client.getTokens().getAccessToken(), TokenTypeHint.ACCESS_TOKEN, new RequestCallback<IntrospectInfo, AuthorizationException>() {

                @Override
                public void onSuccess(@NonNull IntrospectInfo result) {
                    mTvStatus.setText("AccessToken active: " + result.isActive());
                    mProgressBar.setVisibility(View.GONE);
                }

                @Override
                public void onError(String error, AuthorizationException exception) {
                    mTvStatus.setText("AccessToken Introspect error");
                    mProgressBar.setVisibility(View.GONE);
                }
            });
        } catch (AuthorizationException e) {
            Log.d(TAG, "", e);
        }
    });
    mIntrospectId.setOnClickListener(v -> {
        showNetworkProgress(true);
        SessionClient client = getSessionClient();
        try {
            client.introspectToken(client.getTokens().getIdToken(), TokenTypeHint.ID_TOKEN, new RequestCallback<IntrospectInfo, AuthorizationException>() {

                @Override
                public void onSuccess(@NonNull IntrospectInfo result) {
                    mTvStatus.setText("IdToken active: " + result.isActive());
                    mProgressBar.setVisibility(View.GONE);
                }

                @Override
                public void onError(String error, AuthorizationException exception) {
                    mTvStatus.setText("IdToken Introspect error");
                    mProgressBar.setVisibility(View.GONE);
                }
            });
        } catch (AuthorizationException e) {
            Log.d(TAG, "", e);
        }
    });
    mGetProfile.setOnClickListener(v -> getProfile());
    mRefreshToken.setOnClickListener(v -> {
        showNetworkProgress(true);
        SessionClient client = getSessionClient();
        client.refreshToken(new RequestCallback<Tokens, AuthorizationException>() {

            @Override
            public void onSuccess(@NonNull Tokens result) {
                mTvStatus.setText("token refreshed");
                showNetworkProgress(false);
            }

            @Override
            public void onError(String error, AuthorizationException exception) {
                mTvStatus.setText(exception.errorDescription);
                showNetworkProgress(false);
            }
        });
    });
    mRevokeRefresh.setOnClickListener(v -> {
        SessionClient client = getSessionClient();
        try {
            Tokens tokens = client.getTokens();
            if (tokens != null && tokens.getRefreshToken() != null) {
                mProgressBar.setVisibility(View.VISIBLE);
                client.revokeToken(client.getTokens().getRefreshToken(), new RequestCallback<Boolean, AuthorizationException>() {

                    @Override
                    public void onSuccess(@NonNull Boolean result) {
                        String status = "Revoke refresh token : " + result;
                        Log.d(TAG, status);
                        mTvStatus.setText(status);
                        mProgressBar.setVisibility(View.GONE);
                    }

                    @Override
                    public void onError(String error, AuthorizationException exception) {
                        Log.d(TAG, exception.error + " revokeRefreshToken onError " + error, exception);
                        mTvStatus.setText(error);
                        mProgressBar.setVisibility(View.GONE);
                    }
                });
            }
        } catch (AuthorizationException e) {
            Log.d(TAG, "", e);
        }
    });
    mRevokeAccess.setOnClickListener(v -> {
        SessionClient client = getSessionClient();
        try {
            Tokens tokens = client.getTokens();
            if (tokens != null && tokens.getAccessToken() != null) {
                mProgressBar.setVisibility(View.VISIBLE);
                client.revokeToken(client.getTokens().getAccessToken(), new RequestCallback<Boolean, AuthorizationException>() {

                    @Override
                    public void onSuccess(@NonNull Boolean result) {
                        String status = "Revoke Access token : " + result;
                        Log.d(TAG, status);
                        mTvStatus.setText(status);
                        mProgressBar.setVisibility(View.GONE);
                    }

                    @Override
                    public void onError(String error, AuthorizationException exception) {
                        Log.d(TAG, exception.error + " revokeAccessToken onError " + error, exception);
                        mTvStatus.setText(error);
                        mProgressBar.setVisibility(View.GONE);
                    }
                });
            }
        } catch (AuthorizationException e) {
            Log.d(TAG, "", e);
        }
    });
    mSignOut.setOnClickListener(v -> {
        showNetworkProgress(true);
        WebAuthClient client = getWebAuthClient();
        client.signOutOfOkta(this);
    });
    mClearData.setOnClickListener(v -> {
        SessionClient client = getSessionClient();
        client.clear();
        mTvStatus.setText("clear data");
        showSignedOutMode();
    });
    mSignInBrowser.setOnClickListener(v -> {
        showNetworkProgress(true);
        WebAuthClient client = getWebAuthClient();
        String loginHint = mEditText.getEditableText().toString();
        if (!TextUtils.isEmpty(loginHint)) {
            mPayload = new AuthenticationPayload.Builder().setLoginHint(loginHint).build();
        }
        client.signIn(this, mPayload);
    });
    mSignInNative.setOnClickListener(v -> {
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        Fragment prev = getSupportFragmentManager().findFragmentByTag("signin");
        if (prev != null) {
            ft.remove(prev);
        }
        ft.addToBackStack(null);
        mSignInDialog = new SignInDialog();
        mSignInDialog.setListener(this);
        mSignInDialog.show(ft, "signin");
    });
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        mAuthenticationClient = AuthenticationClients.builder().setOrgUrl(BuildConfig.DISCOVERY_URI).build();
    } else {
        mSignInNative.setVisibility(View.GONE);
    }
    // Example of using JSON file to create config
    mOidcConfig = new OIDCConfig.Builder().withJsonFile(this, R.raw.okta_oidc_config).create();
    // Example of config
    mOidcConfig = new OIDCConfig.Builder().clientId(BuildConfig.CLIENT_ID).redirectUri(BuildConfig.REDIRECT_URI).endSessionRedirectUri(BuildConfig.END_SESSION_URI).scopes(BuildConfig.SCOPES).discoveryUri(BuildConfig.DISCOVERY_URI).create();
    mOAuth2Config = new OIDCConfig.Builder().clientId(BuildConfig.CLIENT_ID).redirectUri(BuildConfig.REDIRECT_URI).endSessionRedirectUri(BuildConfig.END_SESSION_URI).scopes(BuildConfig.SCOPES).discoveryUri(BuildConfig.DISCOVERY_URI + "/oauth2/default").create();
    // use custom connection factory
    MyConnectionFactory factory = new MyConnectionFactory();
    factory.setClientType(MyConnectionFactory.USE_SYNC_OK_HTTP);
    try {
        mEncryptedSharedPref = new EncryptedSharedPreferenceStorage(this);
    } catch (GeneralSecurityException | IOException ex) {
        Log.d(TAG, "Unable to initialize EncryptedSharedPreferenceStorage", ex);
    }
    mWebOAuth2 = new Okta.WebAuthBuilder().withConfig(mOAuth2Config).withContext(getApplicationContext()).withStorage(mEncryptedSharedPref).withEncryptionManager(new NoEncryption()).setRequireHardwareBackedKeyStore(!isEmulator()).supportedBrowsers(// chrome is always supported by default
    FIRE_FOX).create();
    mSessionOAuth2Client = mWebOAuth2.getSessionClient();
    Okta.WebAuthBuilder builder = new Okta.WebAuthBuilder().withConfig(mOidcConfig).withContext(getApplicationContext()).withStorage(mStorageOidc).withCallbackExecutor(null).withEncryptionManager(new DefaultEncryptionManager(this)).setRequireHardwareBackedKeyStore(!isEmulator()).withTabColor(0).withOktaHttpClient(factory.build()).supportedBrowsers(FIRE_FOX);
    mWebAuth = builder.create();
    mSessionClient = mWebAuth.getSessionClient();
    mAuthClient = new Okta.AuthBuilder().withConfig(mOidcConfig).withContext(getApplicationContext()).withStorage(new SharedPreferenceStorage(this)).withEncryptionManager(new DefaultEncryptionManager(this)).setRequireHardwareBackedKeyStore(false).withCallbackExecutor(null).create();
    mSessionNonWebClient = mAuthClient.getSessionClient();
    if (getSessionClient().isAuthenticated()) {
        showAuthenticatedMode();
    }
    mCancel.setOnClickListener(v -> {
        // cancel web auth requests
        getWebAuthClient().cancel();
        // cancel session requests
        getSessionClient().cancel();
        showNetworkProgress(false);
    });
    setupCallback();
}
Also used : SessionClient(com.okta.oidc.clients.sessions.SessionClient) AuthorizationException(com.okta.oidc.util.AuthorizationException) Okta(com.okta.oidc.Okta) Fragment(androidx.fragment.app.Fragment) AuthenticationPayload(com.okta.oidc.AuthenticationPayload) FragmentTransaction(androidx.fragment.app.FragmentTransaction) OIDCConfig(com.okta.oidc.OIDCConfig) DefaultEncryptionManager(com.okta.oidc.storage.security.DefaultEncryptionManager) IntrospectInfo(com.okta.oidc.net.response.IntrospectInfo) Tokens(com.okta.oidc.Tokens) GeneralSecurityException(java.security.GeneralSecurityException) IOException(java.io.IOException) SharedPreferenceStorage(com.okta.oidc.storage.SharedPreferenceStorage) WebAuthClient(com.okta.oidc.clients.web.WebAuthClient)

Example 3 with WebAuthClient

use of com.okta.oidc.clients.web.WebAuthClient in project okta-oidc-android by okta.

the class OktaTest method testAsyncWebBuilder.

@Test
public void testAsyncWebBuilder() {
    Okta.WebAuthBuilder builder = mock(Okta.WebAuthBuilder.class);
    WebAuthClient otherClient = new Okta.WebAuthBuilder().withConfig(mConfig).withStorage(mStorage).withContext(mContext).withOktaHttpClient(mHttpClient).withCallbackExecutor(mExecutor).withTabColor(tabColor).supportedBrowsers(supportBrowsers).withEncryptionManager(mEncryptionManager).create();
    when(builder.create()).thenReturn(otherClient);
    builder.withConfig(mConfig);
    verify(builder).withConfig(mConfig);
    builder.withStorage(mStorage);
    verify(builder).withStorage(mStorage);
    builder.withOktaHttpClient(mHttpClient);
    verify(builder).withOktaHttpClient(mHttpClient);
    builder.withContext(mContext);
    verify(builder).withContext(mContext);
    builder.withCallbackExecutor(mExecutor);
    verify(builder).withCallbackExecutor(mExecutor);
    builder.withTabColor(tabColor);
    verify(builder).withTabColor(tabColor);
    builder.supportedBrowsers(supportBrowsers);
    verify(builder).supportedBrowsers(supportBrowsers);
    builder.withEncryptionManager(mEncryptionManager);
    verify(builder).withEncryptionManager(mEncryptionManager);
    Object client = builder.create();
    verify(builder).create();
    assertEquals(otherClient, client);
}
Also used : WebAuthClient(com.okta.oidc.clients.web.WebAuthClient) SyncWebAuthClient(com.okta.oidc.clients.web.SyncWebAuthClient) Test(org.junit.Test)

Aggregations

WebAuthClient (com.okta.oidc.clients.web.WebAuthClient)3 Okta (com.okta.oidc.Okta)2 SharedPreferenceStorage (com.okta.oidc.storage.SharedPreferenceStorage)2 Fragment (androidx.fragment.app.Fragment)1 FragmentTransaction (androidx.fragment.app.FragmentTransaction)1 Gson (com.google.gson.Gson)1 AuthenticationPayload (com.okta.oidc.AuthenticationPayload)1 OIDCConfig (com.okta.oidc.OIDCConfig)1 OktaState (com.okta.oidc.OktaState)1 Tokens (com.okta.oidc.Tokens)1 SessionClient (com.okta.oidc.clients.sessions.SessionClient)1 SyncWebAuthClient (com.okta.oidc.clients.web.SyncWebAuthClient)1 IntrospectInfo (com.okta.oidc.net.response.IntrospectInfo)1 OktaRepository (com.okta.oidc.storage.OktaRepository)1 DefaultEncryptionManager (com.okta.oidc.storage.security.DefaultEncryptionManager)1 AuthorizationException (com.okta.oidc.util.AuthorizationException)1 EncryptionManagerStub (com.okta.oidc.util.EncryptionManagerStub)1 HttpClientFactory (com.okta.oidc.util.HttpClientFactory)1 MockEndPoint (com.okta.oidc.util.MockEndPoint)1 IOException (java.io.IOException)1