### Install react-native-keychain with npm Source: https://oblador.github.io/react-native-keychain/docs Use this command to install the library using npm. Ensure you have Node.js and npm installed. ```bash npm install react-native-keychain ``` -------------------------------- ### Install react-native-keychain with pnpm Source: https://oblador.github.io/react-native-keychain/docs Use this command to install the library using pnpm. Ensure you have Node.js and pnpm installed. ```bash pnpm add react-native-keychain ``` -------------------------------- ### Install react-native-keychain with Yarn Source: https://oblador.github.io/react-native-keychain/docs Use this command to install the library using Yarn. Ensure you have Node.js and Yarn installed. ```bash yarn add react-native-keychain ``` -------------------------------- ### Configure Jest Setup File Source: https://oblador.github.io/react-native-keychain/docs/jest Add a reference to your setup file in jest.config.js. This file will be executed before your tests. ```javascript module.exports = { // ... other configurations ... setupFiles: ['/jest.setup.js'], }; ``` -------------------------------- ### Example Unit Test for Keychain Operations Source: https://oblador.github.io/react-native-keychain/docs/jest Write unit tests to verify that your functions correctly interact with the mocked Keychain module. This example demonstrates saving, retrieving, checking existence, resetting credentials, and getting supported biometry types. ```javascript import Keychain from 'react-native-keychain'; describe('Keychain Manager', () => { it('should save and retrieve credentials', async () => { // Mock saving credentials await Keychain.setGenericPassword('testUser', 'testPassword'); expect(Keychain.setGenericPassword).toHaveBeenCalledWith( 'testUser', 'testPassword' ); // Mock retrieving credentials const credentials = await Keychain.getGenericPassword(); expect(credentials).toEqual({ username: 'mockUser', password: 'mockPassword', service: 'mockService', storage: 'mockStorage', }); }); it('should check if a password exists', async () => { const exists = await Keychain.hasGenericPassword(); expect(exists).toBe(true); }); it('should reset credentials', async () => { const reset = await Keychain.resetGenericPassword(); expect(reset).toBe(true); }); it('should get supported biometry type', async () => { const biometryType = await Keychain.getSupportedBiometryType(); expect(biometryType).toBe('MOCK_TouchID'); }); }); ``` -------------------------------- ### Mock react-native-keychain in Jest Setup Source: https://oblador.github.io/react-native-keychain/docs/jest In your jest.setup.js file, import your mock and use jest.mock to replace the actual module. Ensure the path to your mock is correct. ```javascript // jest.setup.js import keychainMock from './path/to/keychainMock'; jest.mock('react-native-keychain', () => keychainMock); ``` -------------------------------- ### getSecurityLevel Source: https://oblador.github.io/react-native-keychain/docs/api Gets the current security level of the keychain. ```APIDOC ## getSecurityLevel ### Description Gets the current security level of the keychain. ### Method `getSecurityLevel(): Promise` ### Parameters None ### Response #### Success Response (200) - **SECURITY_LEVEL**: The current security level. ``` -------------------------------- ### getAllGenericPasswordServices Source: https://oblador.github.io/react-native-keychain/docs/api/functions/getAllGenericPasswordServices Gets all service keys used in generic password keychain entries. ```APIDOC ## Function: getAllGenericPasswordServices() > **getAllGenericPasswordServices**(`options`?): `Promise`<`string`[]> Gets all service keys used in generic password keychain entries. ## Parameters​ • **options?** : `GetAllOptions` ## Returns​ `Promise`<`string`[]> Resolves to an array of strings representing service keys. ## Example​ ```javascript const services = await Keychain.getAllGenericPasswordServices(); console.log('Services:', services); ``` ## Defined in​ index.ts:121 ``` -------------------------------- ### Get All Generic Password Services Source: https://oblador.github.io/react-native-keychain/docs/api/functions/getAllGenericPasswordServices Use this function to retrieve all service keys for generic password entries. The result is an array of strings representing the service keys. ```javascript const services = await Keychain.getAllGenericPasswordServices(); console.log('Services:', services); ``` -------------------------------- ### Get Security Level Source: https://oblador.github.io/react-native-keychain/docs/api/functions/getSecurityLevel Call getSecurityLevel() to determine the device's supported security level. Log the result to the console. ```javascript const securityLevel = await Keychain.getSecurityLevel(); console.log('Security Level:', securityLevel); ``` -------------------------------- ### getSupportedBiometryType Source: https://oblador.github.io/react-native-keychain/docs/api Gets the type of biometric authentication supported by the device. ```APIDOC ## getSupportedBiometryType ### Description Gets the type of biometric authentication supported by the device. ### Method `getSupportedBiometryType(): Promise` ### Parameters None ### Response #### Success Response (200) - **BIOMETRY_TYPE | null**: The type of biometric authentication supported, or null if none is supported. ``` -------------------------------- ### getSupportedBiometryType Source: https://oblador.github.io/react-native-keychain/docs/api/functions/getSupportedBiometryType Gets the type of biometric authentication supported by the device. Returns a Promise that resolves to a BIOMETRY_TYPE if supported, otherwise null. ```APIDOC ## Function: getSupportedBiometryType() > **getSupportedBiometryType**(): `Promise`<`null` | `BIOMETRY_TYPE`> Gets the type of biometric authentication supported by the device. ## Returns​ `Promise`<`null` | `BIOMETRY_TYPE`> Resolves to a `BIOMETRY_TYPE` when supported, otherwise `null`. ## Example​ ```javascript const biometryType = await Keychain.getSupportedBiometryType(); console.log('Supported Biometry Type:', biometryType); ``` ## Defined in​ index.ts:231 ``` -------------------------------- ### Get Supported Biometry Type Source: https://oblador.github.io/react-native-keychain/docs/api/functions/getSupportedBiometryType Call this function to determine the biometric authentication method available on the device. The result indicates whether fingerprint, face recognition, or no biometric support is present. ```javascript const biometryType = await Keychain.getSupportedBiometryType(); console.log('Supported Biometry Type:', biometryType); ``` -------------------------------- ### GetAllOptions Source: https://oblador.github.io/react-native-keychain/docs/api/type-aliases/GetAllOptions Defines the options for retrieving all keychain items. The `skipUIAuth` option allows for skipping user authentication prompts on iOS. ```APIDOC ## Type Alias: GetAllOptions > **GetAllOptions** : `object` ### Type declaration​ #### skipUIAuth?​ > `optional` **skipUIAuth** : `boolean` Whether items requiring user authentication should be skipped #### Platform​ iOS ## Defined in​ types.ts:92 ``` -------------------------------- ### SetOptions Source: https://oblador.github.io/react-native-keychain/docs/api/type-aliases/SetOptions Configuration options for setting keychain items. ```APIDOC ## Type Alias: SetOptions > **SetOptions** : `object` & `BaseOptions` & `AccessControlOption` ### accessible? > `optional` **accessible** : `ACCESSIBLE` Specifies when a keychain item is accessible. #### Platform​ iOS, visionOS #### Default​ ``` ACCESSIBLE.AFTER_FIRST_UNLOCK ``` ### authenticationPrompt? > `optional` **authenticationPrompt** : `AuthenticationPrompt` Authentication prompt details or a title string. #### Default​ ```json { "title": "Authenticate to retrieve secret", "cancel": "Cancel" } ``` ### securityLevel? > `optional` **securityLevel** : `SECURITY_LEVEL` The desired security level of the keychain item. #### Platform​ Android ### storage? > `optional` **storage** : `STORAGE_TYPE` The storage type. #### Platform​ Android #### Default​ ``` 'Best available storage' ``` ## Defined in​ types.ts:46 ``` -------------------------------- ### BaseOptions Source: https://oblador.github.io/react-native-keychain/docs/api/type-aliases/BaseOptions Defines the configuration options for keychain operations. ```APIDOC ## Type Alias: BaseOptions > **BaseOptions** : `object` ### Type declaration #### accessGroup? > `optional` **accessGroup** : `string` The access group to share keychain items between apps. * **Platform**: iOS, visionOS #### cloudSync? > `optional` **cloudSync** : `boolean` Whether to synchronize the keychain item to iCloud. * **Platform**: iOS #### server? > `optional` **server** : `string` The server name to associate with the keychain item. #### service? > `optional` **service** : `string` The service name to associate with the keychain item. * **Default**: `'App bundle ID'` ``` -------------------------------- ### GetOptions Type Declaration Source: https://oblador.github.io/react-native-keychain/docs/api/type-aliases/GetOptions Defines the structure of options for retrieving keychain items. It includes optional `accessControl` and `authenticationPrompt` properties. ```APIDOC ## Type Alias: GetOptions > **GetOptions** : `object` & `BaseOptions` & `AccessControlOption` ## Type declaration​ ### accessControl? > `optional` **accessControl** : `ACCESS_CONTROL` The access control policy to use for the keychain item. ### authenticationPrompt? > `optional` **authenticationPrompt** : `AuthenticationPrompt` Authentication prompt details or a title string. #### Default​ ```json { "title": "Authenticate to retrieve secret", "cancel": "Cancel" } ``` ## Defined in​ types.ts:75 ``` -------------------------------- ### AuthenticationPrompt Options Source: https://oblador.github.io/react-native-keychain/docs/api/type-aliases/AuthenticationPrompt This object allows customization of the authentication prompt displayed to the user. It includes optional fields for the cancel button text, description, subtitle, and title. ```APIDOC ## Type Alias: AuthenticationPrompt > **AuthenticationPrompt** : `object` Options for authentication prompt displayed to the user. ## Type declaration​ ### cancel? > `optional` **cancel** : `string` The cancel button text for the authentication prompt. #### Platform​ Android ### description? > `optional` **description** : `string` The description for the authentication prompt. #### Platform​ Android ### subtitle? > `optional` **subtitle** : `string` The subtitle for the authentication prompt. #### Platform​ Android ### title? > `optional` **title** : `string` The title for the authentication prompt. ## Defined in​ types.ts:12 ``` -------------------------------- ### Store, Retrieve, and Reset Credentials Source: https://oblador.github.io/react-native-keychain/docs/usage Use `setGenericPassword` to store credentials, `getGenericPassword` to retrieve them, and `resetGenericPassword` to clear them. Ensure you specify a `service` key for proper management. Both storage methods only support strings; stringify objects before storing and parse them after retrieval. ```javascript import * as Keychain from 'react-native-keychain'; async () => { const username = 'zuck'; const password = 'poniesRgr8'; // Store the credentials await Keychain.setGenericPassword(username, password, {service: 'service_key'}); try { // Retrieve the credentials const credentials = await Keychain.getGenericPassword({service: 'service_key'}); if (credentials) { console.log( 'Credentials successfully loaded for user ' + credentials.username ); } else { console.log('No credentials stored'); } } catch (error) { console.error("Failed to access Keychain", error); } // Reset the stored credentials await Keychain.resetGenericPassword({service: 'service_key'}); }; ``` -------------------------------- ### Mock react-native-keychain using Jest's __mocks__ Directory Source: https://oblador.github.io/react-native-keychain/docs/jest This method allows you to mock the entire `react-native-keychain` module for all your tests by placing a mock file in the `__mocks__` directory. Ensure the mock object is complete, copying all necessary enums and functions. ```javascript // index.ts or index.js inside __mocks__/react-native-keychain const keychainMock = { SECURITY_LEVEL: { SECURE_SOFTWARE: 'MOCK_SECURITY_LEVEL_SECURE_SOFTWARE', SECURE_HARDWARE: 'MOCK_SECURITY_LEVEL_SECURE_HARDWARE', ANY: 'MOCK_SECURITY_LEVEL_ANY', }, // ... rest of the keychainMock object ... // (Copy the entire keychainMock object from above) }; module.exports = keychainMock; ``` -------------------------------- ### setInternetCredentials Source: https://oblador.github.io/react-native-keychain/docs/api/functions/setInternetCredentials Saves the internet credentials for the given server. It takes the server URL, username, password, and optional keychain options as parameters. It returns a Promise that resolves to an object containing 'service' and 'storage' upon success, or 'false' if the operation fails. ```APIDOC ## Function: setInternetCredentials() > **setInternetCredentials**(`server`, `username`, `password`, `options`?): `Promise`<`false` | `Result`> Saves the internet credentials for the given server. ## Parameters​ • **server** : `string` The server URL. • **username** : `string` The username or e-mail to be saved. • **password** : `string` The password to be saved. • **options?** : `SetOptions` A keychain options object. ## Returns​ `Promise`<`false` | `Result`> Resolves to an object containing `service` and `storage` when successful, or `false` on failure. ## Example​ ```javascript await Keychain.setInternetCredentials('https://example.com', 'username', 'password'); ``` ## Defined in​ index.ts:161 ``` -------------------------------- ### getInternetCredentials Source: https://oblador.github.io/react-native-keychain/docs/api/functions/getInternetCredentials Fetches the internet credentials for the given server. It resolves to an object containing server, username, password, and storage when successful, or false on failure. ```APIDOC ## Function: getInternetCredentials() > **getInternetCredentials**(`server`, `options`?): `Promise`<`false` | `UserCredentials`> Fetches the internet credentials for the given server. ## Parameters • **server** : `string` The server URL. • **options?** : `GetOptions` A keychain options object. ## Returns `Promise`<`false` | `UserCredentials`> Resolves to an object containing `server`, `username`, `password`, and `storage` when successful, or `false` on failure. ## Example ```javascript const credentials = await Keychain.getInternetCredentials('https://example.com'); if (credentials) { console.log('Credentials loaded for user ' + credentials.username); } else { console.log('No credentials stored for server'); } ``` ## Defined in index.ts:193 ``` -------------------------------- ### Save Username and Password Source: https://oblador.github.io/react-native-keychain/docs/api/functions/setGenericPassword Use this function to save a username and password combination. It returns a promise that resolves to an object with service and storage details on success, or false on failure. ```javascript await Keychain.setGenericPassword('username', 'password'); ``` -------------------------------- ### Check Passcode Authentication Availability Source: https://oblador.github.io/react-native-keychain/docs/api/functions/isPasscodeAuthAvailable Use this function to determine if the device supports passcode authentication before attempting to use it. It returns a promise that resolves to true if available, and false otherwise. ```javascript const isAvailable = await Keychain.isPasscodeAuthAvailable(); console.log('Passcode authentication available:', isAvailable); ``` -------------------------------- ### Check Authentication Support Source: https://oblador.github.io/react-native-keychain/docs/api/functions/canImplyAuthentication Use this function to determine if the device supports the authentication policy before attempting to use it. This is particularly useful for providing a better user experience by conditionally enabling or disabling features. ```javascript const canAuthenticate = await Keychain.canImplyAuthentication(); console.log('Can imply authentication:', canAuthenticate); ``` -------------------------------- ### Fetch Generic Password Source: https://oblador.github.io/react-native-keychain/docs/api/functions/getGenericPassword Use this snippet to retrieve stored username and password credentials. It checks if credentials exist and logs a success or failure message. ```javascript const credentials = await Keychain.getGenericPassword(); if (credentials) { console.log('Credentials successfully loaded for user ' + credentials.username); } else { console.log('No credentials stored'); } ``` -------------------------------- ### BaseOptions Type Declaration Source: https://oblador.github.io/react-native-keychain/docs/api/type-aliases/BaseOptions Defines the structure for BaseOptions, which includes optional properties for configuring keychain item behavior. Use these options to specify sharing, synchronization, and server/service associations. ```typescript type BaseOptions = { accessGroup?: string cloudSync?: boolean server?: string service?: string } ``` -------------------------------- ### Default Authentication Prompt Source: https://oblador.github.io/react-native-keychain/docs/api/type-aliases/GetOptions This is the default configuration for the authentication prompt when retrieving a secret. It specifies the title displayed to the user and the text for the cancel button. ```json { "title": "Authenticate to retrieve secret", "cancel": "Cancel" } ``` -------------------------------- ### Check for Internet Credentials Source: https://oblador.github.io/react-native-keychain/docs/api/functions/hasInternetCredentials Use this snippet to check if internet credentials exist for a given server URL. The function returns a promise that resolves to true if credentials are found, and false otherwise. ```javascript const hasCredentials = await Keychain.hasInternetCredentials('https://example.com'); console.log('Internet credentials exist:', hasCredentials); ``` -------------------------------- ### Save Internet Credentials Source: https://oblador.github.io/react-native-keychain/docs/api/functions/setInternetCredentials Use this function to save internet credentials. Ensure the Keychain module is imported. ```javascript await Keychain.setInternetCredentials('https://example.com', 'username', 'password'); ``` -------------------------------- ### getGenericPassword() Source: https://oblador.github.io/react-native-keychain/docs/api/functions/getGenericPassword Fetches the username and password combination for the given service. It resolves to an object containing service, username, password, and storage when successful, or false on failure. ```APIDOC ## Function: getGenericPassword() > **getGenericPassword**(`options`?): `Promise`<`false` | `UserCredentials`> Fetches the `username` and `password` combination for the given service. ## Parameters​ • **options?** : `GetOptions` A keychain options object. ## Returns​ `Promise`<`false` | `UserCredentials`> Resolves to an object containing `service`, `username`, `password`, and `storage` when successful, or `false` on failure. ## Example​ ```javascript const credentials = await Keychain.getGenericPassword(); if (credentials) { console.log('Credentials successfully loaded for user ' + credentials.username); } else { console.log('No credentials stored'); } ``` ## Defined in​ index.ts:68 ``` -------------------------------- ### setInternetCredentials Source: https://oblador.github.io/react-native-keychain/docs/api Sets internet credentials (username and password) in the keychain for a given server. ```APIDOC ## setInternetCredentials ### Description Sets internet credentials (username and password) in the keychain for a given server. ### Method `setInternetCredentials(server: string, username: string, password: string, options?: SetOptions): Promise` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **server** (string) - Required - The server address. - **username** (string) - Required - The username. - **password** (string) - Required - The password to store. - **options** (SetOptions) - Optional - Additional options for setting the credentials. ### Response #### Success Response (200) - **void**: Indicates successful storage. ``` -------------------------------- ### Fetch Internet Credentials Source: https://oblador.github.io/react-native-keychain/docs/api/functions/getInternetCredentials Use this snippet to retrieve stored internet credentials for a server. It checks if credentials exist and logs the username or a message indicating no credentials are stored. ```javascript const credentials = await Keychain.getInternetCredentials('https://example.com'); if (credentials) { console.log('Credentials loaded for user ' + credentials.username); } else { console.log('No credentials stored for server'); } ``` -------------------------------- ### setSharedWebCredentials() Source: https://oblador.github.io/react-native-keychain/docs/api/functions/setSharedWebCredentials Sets shared web credentials for a given server, username, and optionally password. ```APIDOC ## setSharedWebCredentials() ### Description Sets shared web credentials. ### Parameters #### Path Parameters * **server** (string) - Required - The server URL. * **username** (string) - Required - The username or e-mail to be saved. * **password** (string) - Optional - The password to be saved. ### Returns `Promise` - Resolves when the operation is completed. ### Platform iOS ### Example ```javascript await Keychain.setSharedWebCredentials('https://example.com', 'username', 'password'); console.log('Shared web credentials set'); ``` ``` -------------------------------- ### hasInternetCredentials Source: https://oblador.github.io/react-native-keychain/docs/api/functions/hasInternetCredentials Checks if internet credentials exist for the given server. ```APIDOC ## hasInternetCredentials() ### Description Checks if internet credentials exist for the given server. ### Method `hasInternetCredentials(options: string | BaseOptions): Promise` ### Parameters #### Path Parameters - **options** (string | BaseOptions) - Required - A keychain options object normalizeAuthPrompt(options). ### Returns `Promise` - Resolves to `true` if internet credentials exist, otherwise `false`. ### Example ```javascript const hasCredentials = await Keychain.hasInternetCredentials('https://example.com'); console.log('Internet credentials exist:', hasCredentials); ``` ### Defined in index.ts:140 ``` -------------------------------- ### Default Service Name Source: https://oblador.github.io/react-native-keychain/docs/api/type-aliases/BaseOptions Illustrates the default value for the 'service' option, which is the application's bundle ID. This is used when no explicit service name is provided. ```typescript 'App bundle ID' ``` -------------------------------- ### Set Shared Web Credentials Source: https://oblador.github.io/react-native-keychain/docs/api/functions/setSharedWebCredentials Use this function to store web credentials. It is only available on iOS. The password parameter is optional. ```javascript await Keychain.setSharedWebCredentials('https://example.com', 'username', 'password'); console.log('Shared web credentials set'); ``` -------------------------------- ### canImplyAuthentication Source: https://oblador.github.io/react-native-keychain/docs/api Checks if the keychain can imply authentication for certain operations. ```APIDOC ## canImplyAuthentication ### Description Checks if the keychain can imply authentication for certain operations. ### Method `canImplyAuthentication()` ### Parameters None ### Response - **boolean**: Returns `true` if authentication can be implied, `false` otherwise. ``` -------------------------------- ### canImplyAuthentication Source: https://oblador.github.io/react-native-keychain/docs/api/functions/canImplyAuthentication Checks if the current device supports the specified authentication policy. This function is available on iOS. ```APIDOC ## Function: canImplyAuthentication() > **canImplyAuthentication**(`options`?): `Promise`<`boolean`> Checks if the current device supports the specified authentication policy. ### Parameters • **options?** : `AuthenticationTypeOption` A keychain options object. ### Returns `Promise`<`boolean`> Resolves to `true` when supported, otherwise `false`. ### Platform iOS ### Example ```javascript const canAuthenticate = await Keychain.canImplyAuthentication(); console.log('Can imply authentication:', canAuthenticate); ``` ### Defined in index.ts:320 ``` -------------------------------- ### UserCredentials Type Source: https://oblador.github.io/react-native-keychain/docs/api/type-aliases/UserCredentials Defines the structure for user credentials, containing a username and a password. ```APIDOC ## Type Alias: UserCredentials > **UserCredentials** : `object` User credentials returned by keychain functions. ### Type declaration #### password > **password** : `string` > The password associated with the keychain item. #### username > **username** : `string` > The username associated with the keychain item. ### Defined in types.ts:125 ``` -------------------------------- ### Request Shared Web Credentials Source: https://oblador.github.io/react-native-keychain/docs/api/functions/requestSharedWebCredentials Use this snippet to request shared web credentials. It checks if credentials were provided and logs them or a message indicating their absence. ```javascript const credentials = await Keychain.requestSharedWebCredentials(); if (credentials) { console.log('Shared credentials retrieved:', credentials); } else { console.log('No shared credentials available'); } ``` -------------------------------- ### Result Type Source: https://oblador.github.io/react-native-keychain/docs/api/type-aliases/Result The Result type is an object that contains details about the keychain item, including its service name and storage type. ```APIDOC ## Type Alias: Result > **Result** : `object` Result returned by keychain functions. ## Type declaration​ ### service​ > **service** : `string` The service name associated with the keychain item. ### storage​ > **storage** : `STORAGE_TYPE` The storage type used for the keychain item. ## Defined in​ types.ts:115 ``` -------------------------------- ### SharedWebCredentials Type Source: https://oblador.github.io/react-native-keychain/docs/api/type-aliases/SharedWebCredentials Defines the structure of shared web credentials, which includes server details. ```APIDOC ## Type Alias: SharedWebCredentials > **SharedWebCredentials** : `object` & `UserCredentials` Shared web credentials returned by keychain functions. ## Type declaration​ ### server​ > **server** : `string` The server associated with the keychain item. ## Platform​ iOS ## Defined in​ types.ts:136 ``` -------------------------------- ### Resetting Generic Passwords Source: https://oblador.github.io/react-native-keychain/docs/api/functions/resetGenericPassword Call this function to remove all generic password entries associated with the service. It returns a promise that resolves to true on success, and false otherwise. ```javascript const success = await Keychain.resetGenericPassword(); console.log('Password reset successful:', success); ``` -------------------------------- ### requestSharedWebCredentials() Source: https://oblador.github.io/react-native-keychain/docs/api/functions/requestSharedWebCredentials Requests shared web credentials. Resolves to an object containing `server`, `username`, and `password` if approved, or `false` if denied. This function is only available on iOS. ```APIDOC ## Function: requestSharedWebCredentials() > **requestSharedWebCredentials**(): `Promise`<`false` | `SharedWebCredentials`> Request shared web credentials. ## Returns​ `Promise`<`false` | `SharedWebCredentials`> Resolves to an object containing `server`, `username`, and `password` if approved, or `false` if denied. ## Platform​ iOS ## Example​ ```javascript const credentials = await Keychain.requestSharedWebCredentials(); if (credentials) { console.log('Shared credentials retrieved:', credentials); // credentials object will contain server, username, and password } else { console.log('No shared credentials available'); } ``` ## Defined in​ index.ts:256 ``` -------------------------------- ### Default Storage Type Source: https://oblador.github.io/react-native-keychain/docs/api/type-aliases/SetOptions Specifies the storage type for keychain items on Android. Defaults to the best available storage. ```javascript 'Best available storage' ``` -------------------------------- ### ACCESS_CONTROL Enumeration Members Source: https://oblador.github.io/react-native-keychain/docs/api/enumerations/ACCESS_CONTROL The ACCESS_CONTROL enumeration provides several options for specifying how keychain items should be accessed, balancing security with user convenience. ```APIDOC ## Enumeration: ACCESS_CONTROL Enum representing access control options. ### Enumeration Members #### USER_PRESENCE > **USER_PRESENCE** : `"UserPresence"` Constraint to access an item with either Touch ID or passcode. #### Defined in enums.ts:28 * * * #### BIOMETRY_ANY > **BIOMETRY_ANY** : `"BiometryAny"` Constraint to access an item with Touch ID for any enrolled fingers. #### Defined in enums.ts:30 * * * #### BIOMETRY_CURRENT_SET > **BIOMETRY_CURRENT_SET** : `"BiometryCurrentSet"` Constraint to access an item with Touch ID for currently enrolled fingers. #### Defined in enums.ts:32 * * * #### DEVICE_PASSCODE > **DEVICE_PASSCODE** : `"DevicePasscode"` Constraint to access an item with the device passcode. #### Defined in enums.ts:34 * * * #### APPLICATION_PASSWORD > **APPLICATION_PASSWORD** : `"ApplicationPassword"` Constraint to use an application-provided password for data encryption key generation. #### Defined in enums.ts:36 * * * #### BIOMETRY_ANY_OR_DEVICE_PASSCODE > **BIOMETRY_ANY_OR_DEVICE_PASSCODE** : `"BiometryAnyOrDevicePasscode"` Constraint to access an item with Touch ID for any enrolled fingers or passcode. #### Defined in enums.ts:38 * * * #### BIOMETRY_CURRENT_SET_OR_DEVICE_PASSCODE > **BIOMETRY_CURRENT_SET_OR_DEVICE_PASSCODE** : `"BiometryCurrentSetOrDevicePasscode"` Constraint to access an item with Touch ID for currently enrolled fingers or passcode. #### Defined in enums.ts:40 ``` -------------------------------- ### Create a Mock Keychain Object for Jest Source: https://oblador.github.io/react-native-keychain/docs/jest This mock object should mirror the structure of the actual react-native-keychain module, including enums and functions. Use this when you need a custom mock for specific test scenarios. ```javascript // keychainMock.ts or keychainMock.js const keychainMock = { SECURITY_LEVEL: { SECURE_SOFTWARE: 'MOCK_SECURITY_LEVEL_SECURE_SOFTWARE', SECURE_HARDWARE: 'MOCK_SECURITY_LEVEL_SECURE_HARDWARE', ANY: 'MOCK_SECURITY_LEVEL_ANY', }, ACCESSIBLE: { WHEN_UNLOCKED: 'MOCK_AccessibleWhenUnlocked', AFTER_FIRST_UNLOCK: 'MOCK_AccessibleAfterFirstUnlock', ALWAYS: 'MOCK_AccessibleAlways', WHEN_PASSCODE_SET_THIS_DEVICE_ONLY: 'MOCK_AccessibleWhenPasscodeSetThisDeviceOnly', WHEN_UNLOCKED_THIS_DEVICE_ONLY: 'MOCK_AccessibleWhenUnlockedThisDeviceOnly', AFTER_FIRST_UNLOCK_THIS_DEVICE_ONLY: 'MOCK_AccessibleAfterFirstUnlockThisDeviceOnly', }, ACCESS_CONTROL: { USER_PRESENCE: 'MOCK_UserPresence', BIOMETRY_ANY: 'MOCK_BiometryAny', BIOMETRY_CURRENT_SET: 'MOCK_BiometryCurrentSet', DEVICE_PASSCODE: 'MOCK_DevicePasscode', APPLICATION_PASSWORD: 'MOCK_ApplicationPassword', BIOMETRY_ANY_OR_DEVICE_PASSCODE: 'MOCK_BiometryAnyOrDevicePasscode', BIOMETRY_CURRENT_SET_OR_DEVICE_PASSCODE: 'MOCK_BiometryCurrentSetOrDevicePasscode', }, AUTHENTICATION_TYPE: { DEVICE_PASSCODE_OR_BIOMETRICS: 'MOCK_AuthenticationWithBiometricsDevicePasscode', BIOMETRICS: 'MOCK_AuthenticationWithBiometrics', }, STORAGE_TYPE: { FB: 'MOCK_FacebookConceal', AES: 'MOCK_KeystoreAESCBC', RSA: 'MOCK_KeystoreRSAECB', KC: 'MOCK_keychain', }, setGenericPassword: jest.fn().mockResolvedValue({ service: 'mockService', storage: 'mockStorage', }), getGenericPassword: jest.fn().mockResolvedValue({ username: 'mockUser', password: 'mockPassword', service: 'mockService', storage: 'mockStorage', }), resetGenericPassword: jest.fn().mockResolvedValue(true), hasGenericPassword: jest.fn().mockResolvedValue(true), getAllGenericPasswordServices: jest .fn() .mockResolvedValue(['mockService1', 'mockService2']), setInternetCredentials: jest.fn().mockResolvedValue({ service: 'mockService', storage: 'mockStorage', }), getInternetCredentials: jest.fn().mockResolvedValue({ username: 'mockUser', password: 'mockPassword', service: 'mockService', storage: 'mockStorage', }), resetInternetCredentials: jest.fn().mockResolvedValue(), getSupportedBiometryType: jest.fn().mockResolvedValue('MOCK_TouchID'), canImplyAuthentication: jest.fn().mockResolvedValue(true), getSecurityLevel: jest.fn().mockResolvedValue('MOCK_SECURE_SOFTWARE'), isPasscodeAuthAvailable: jest.fn().mockResolvedValue(true) }; export default keychainMock; ``` -------------------------------- ### Default ACCESSIBLE Value Source: https://oblador.github.io/react-native-keychain/docs/api/type-aliases/SetOptions Specifies when a keychain item is accessible. This is the default value for iOS and visionOS. ```javascript ACCESSIBLE.AFTER_FIRST_UNLOCK ``` -------------------------------- ### Reset Internet Credentials Source: https://oblador.github.io/react-native-keychain/docs/api/functions/resetInternetCredentials Use this function to clear all saved internet passwords for a specified server. It returns a promise that resolves when the operation is complete. ```javascript await Keychain.resetInternetCredentials('https://example.com'); console.log('Credentials reset for server'); ``` -------------------------------- ### getSecurityLevel() Source: https://oblador.github.io/react-native-keychain/docs/api/functions/getSecurityLevel Retrieves the security level supported by the library on the current device. This function is specific to Android. ```APIDOC ## Function: getSecurityLevel() > **getSecurityLevel**(`options`?): `Promise`<`null` | `SECURITY_LEVEL`> Returns the security level supported by the library on the current device. ### Parameters • **options?** : `AccessControlOption` A keychain options object. ### Returns `Promise`<`null` | `SECURITY_LEVEL`> Resolves to a `SECURITY_LEVEL` when supported, otherwise `null`. ### Platform Android ### Example ```javascript const securityLevel = await Keychain.getSecurityLevel(); console.log('Security Level:', securityLevel); ``` ### Defined in index.ts:344 ``` -------------------------------- ### isPasscodeAuthAvailable() Source: https://oblador.github.io/react-native-keychain/docs/api/functions/isPasscodeAuthAvailable Checks if passcode authentication is available on the current device. This function returns a Promise that resolves to a boolean value. ```APIDOC ## Function: isPasscodeAuthAvailable() > **isPasscodeAuthAvailable**(): `Promise`<`boolean`> Checks if passcode authentication is available on the current device. ## Returns​ `Promise`<`boolean`> Resolves to `true` if passcode authentication is available, otherwise `false`. ## Example​ ```javascript const isAvailable = await Keychain.isPasscodeAuthAvailable(); console.log('Passcode authentication available:', isAvailable); ``` ## Defined in​ index.ts:364 ``` -------------------------------- ### AUTHENTICATION_TYPE.DEVICE_PASSCODE_OR_BIOMETRICS Source: https://oblador.github.io/react-native-keychain/docs/api/enumerations/AUTHENTICATION_TYPE Represents authentication using either biometry or the device's passcode. ```APIDOC ## Enumeration Member: DEVICE_PASSCODE_OR_BIOMETRICS ### Description Device owner is going to be authenticated by biometry or device passcode. ### Value `"AuthenticationWithBiometricsDevicePasscode"` ### Defined in enums.ts:48 ``` -------------------------------- ### AuthenticationTypeOption Source: https://oblador.github.io/react-native-keychain/docs/api/type-aliases/AuthenticationTypeOption Defines the authentication type for retrieving keychain items. This option is available on iOS and visionOS. The default value is DEVICE_PASSCODE_OR_BIOMETRICS. ```APIDOC ## Type Alias: AuthenticationTypeOption > **AuthenticationTypeOption** : `object` ### Type declaration #### authenticationType? > `optional` **authenticationType** : `AUTHENTICATION_TYPE` Authentication type for retrieving keychain item. #### Platform iOS, visionOS #### Default ``` AUTHENTICATION_TYPE.DEVICE_PASSCODE_OR_BIOMETRICS ``` ## Defined in types.ts:104 ``` -------------------------------- ### STORAGE_TYPE Enumeration Members Source: https://oblador.github.io/react-native-keychain/docs/api/enumerations/STORAGE_TYPE This section details the members of the STORAGE_TYPE enumeration, including their string representation, security implications, and deprecation status. ```APIDOC ## Enumeration: STORAGE_TYPE Enum representing cryptographic storage types for sensitive data. ### Security Level Categories: 1. **High Security (Biometric Authentication Required):** * AES_GCM: For sensitive local data (passwords, personal info) * RSA: For asymmetric operations (signatures, key exchange) 2. **Medium Security (No Authentication):** * AES_GCM_NO_AUTH: For app-level secrets and cached data 3. **Legacy/Deprecated:** * AES_CBC: Outdated, use AES_GCM_NO_AUTH instead ## Platform Android ## Enumeration Members ### ~~AES_CBC~~ > **AES_CBC** : `"KeystoreAESCBC"` AES encryption in CBC (Cipher Block Chaining) mode. Provides data confidentiality without authentication. #### Deprecated Use AES_GCM_NO_AUTH instead. #### Defined in enums.ts:123 ### AES_GCM > **AES_GCM** : `"KeystoreAESGCM"` AES-GCM encryption with biometric authentication. Requires user authentication for both encryption and decryption operations. #### Defined in enums.ts:133 ### AES_GCM_NO_AUTH > **AES_GCM_NO_AUTH** : `"KeystoreAESGCM_NoAuth"` AES encryption in GCM (Galois/Counter Mode). Provides both data confidentiality and authentication. #### Defined in enums.ts:128 ### RSA > **RSA** : `"KeystoreRSAECB"` RSA encryption with biometric authentication. Uses asymmetric encryption and requires biometric authentication. #### Defined in enums.ts:138 ``` -------------------------------- ### resetInternetCredentials Source: https://oblador.github.io/react-native-keychain/docs/api/functions/resetInternetCredentials Deletes all internet password keychain entries for the given server. ```APIDOC ## resetInternetCredentials(options?) ### Description Deletes all internet password keychain entries for the given server. ### Method `resetInternetCredentials` ### Parameters #### Path Parameters - **options** (BaseOptions) - Optional - A keychain options object. ### Returns `Promise` - Resolves when the operation is completed. ### Example ```javascript await Keychain.resetInternetCredentials('https://example.com'); console.log('Credentials reset for server'); ``` ``` -------------------------------- ### setGenericPassword Source: https://oblador.github.io/react-native-keychain/docs/api/functions/setGenericPassword Saves the username and password combination for the given service. It returns a Promise that resolves to an object containing 'service' and 'storage' upon success, or 'false' if the operation fails. ```APIDOC ## Function: setGenericPassword() > **setGenericPassword**(`username`, `password`, `options`?): `Promise`<`false` | `Result`> Saves the `username` and `password` combination for the given service. ## Parameters​ • **username** : `string` The username or e-mail to be saved. • **password** : `string` The password to be saved. • **options?** : `SetOptions` A keychain options object. ## Returns​ `Promise`<`false` | `Result`> Resolves to an object containing `service` and `storage` when successful, or `false` on failure. ## Example​ ```javascript await Keychain.setGenericPassword('username', 'password'); ``` ## Defined in​ index.ts:39 ``` -------------------------------- ### resetGenericPassword() Source: https://oblador.github.io/react-native-keychain/docs/api/functions/resetGenericPassword Deletes all generic password keychain entries for the given service. It takes an optional options object and returns a promise that resolves to a boolean indicating success. ```APIDOC ## resetGenericPassword() ### Description Deletes all generic password keychain entries for the given service. ### Method `resetGenericPassword(options?: BaseOptions): Promise` ### Parameters #### Options - **options** (`BaseOptions`) - Optional - A keychain options object. ### Returns - `Promise` - Resolves to `true` when successful, otherwise `false`. ### Example ```javascript const success = await Keychain.resetGenericPassword(); console.log('Password reset successful:', success); ``` ``` -------------------------------- ### hasGenericPassword() Source: https://oblador.github.io/react-native-keychain/docs/api/functions/hasGenericPassword Checks if a generic password exists for the given service. It returns a promise that resolves to `true` if a password exists, and `false` otherwise. ```APIDOC ## Function: hasGenericPassword() > **hasGenericPassword**(`options`?): `Promise`<`boolean`> Checks if generic password exists for the given service. ### Parameters​ • **options?** : `BaseOptions` A keychain options object. ### Returns​ `Promise`<`boolean`> Resolves to `true` if a password exists, otherwise `false`. ### Example​ ```javascript const hasPassword = await Keychain.hasGenericPassword(); console.log('Password exists:', hasPassword); ``` ## Defined in​ index.ts:89 ``` -------------------------------- ### getGenericPassword Source: https://oblador.github.io/react-native-keychain/docs/api Retrieves a generic password from the keychain for a given service and username. ```APIDOC ## getGenericPassword ### Description Retrieves a generic password from the keychain for a given service and username. ### Method `getGenericPassword(service: string, username: string, options?: GetOptions): Promise` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **service** (string) - Required - The service name. - **username** (string) - Required - The username. - **options** (GetOptions) - Optional - Additional options for retrieving the password. ### Response #### Success Response (200) - **Result**: An object containing the username and password, or null if not found. - **username** (string) - **password** (string) ``` -------------------------------- ### Check for Generic Password Existence Source: https://oblador.github.io/react-native-keychain/docs/api/functions/hasGenericPassword Use this snippet to check if a generic password has been saved for the current service. The function returns a promise that resolves to true if a password exists, and false otherwise. ```javascript const hasPassword = await Keychain.hasGenericPassword(); console.log('Password exists:', hasPassword); ``` -------------------------------- ### setGenericPassword Source: https://oblador.github.io/react-native-keychain/docs/api Sets a generic password in the keychain for a given service and username. ```APIDOC ## setGenericPassword ### Description Sets a generic password in the keychain for a given service and username. ### Method `setGenericPassword(service: string, username: string, password: string, options?: SetOptions): Promise` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **service** (string) - Required - The service name. - **username** (string) - Required - The username. - **password** (string) - Required - The password to store. - **options** (SetOptions) - Optional - Additional options for setting the password. ### Response #### Success Response (200) - **void**: Indicates successful storage. ``` -------------------------------- ### Check for Stored Passwords with react-native-keychain Source: https://oblador.github.io/react-native-keychain/docs/data-persistence Use `hasGenericPassword` and `hasInternetCredentials` to determine if data is available in the keychain/keystore. Ensure the correct service or server is specified. ```javascript import Keychain from 'react-native-keychain'; const isGenericPasswordAvailable = await Keychain.hasGenericPassword({ service: 'service_key' }); const isInternetCredentialAvailable = await Keychain.hasInternetCredentials({ server: 'https://google.com' }); ``` -------------------------------- ### ACCESSIBLE Enumeration Members Source: https://oblador.github.io/react-native-keychain/docs/api/enumerations/ACCESSIBLE The ACCESSIBLE enumeration provides different levels of accessibility for keychain items, controlling when they can be accessed based on device state and security settings. ```APIDOC ## Enumeration: ACCESSIBLE Enum representing when a keychain item is accessible. ### Enumeration Members #### AFTER_FIRST_UNLOCK > **AFTER_FIRST_UNLOCK** : `"AccessibleAfterFirstUnlock"` > The data in the keychain item cannot be accessed after a restart until the device has been unlocked once by the user. > #### Defined in > enums.ts:12 #### AFTER_FIRST_UNLOCK_THIS_DEVICE_ONLY > **AFTER_FIRST_UNLOCK_THIS_DEVICE_ONLY** : `"AccessibleAfterFirstUnlockThisDeviceOnly"` > The data in the keychain item cannot be accessed after a restart until the device has been unlocked once by the user. Items with this attribute never migrate to a new device. > #### Defined in > enums.ts:20 #### ALWAYS > **ALWAYS** : `"AccessibleAlways"` > The data in the keychain item can always be accessed regardless of whether the device is locked. > #### Defined in > enums.ts:14 #### WHEN_PASSCODE_SET_THIS_DEVICE_ONLY > **WHEN_PASSCODE_SET_THIS_DEVICE_ONLY** : `"AccessibleWhenPasscodeSetThisDeviceOnly"` > The data in the keychain can only be accessed when the device is unlocked. Only available if a passcode is set on the device. Items with this attribute never migrate to a new device. > #### Defined in > enums.ts:16 #### WHEN_UNLOCKED > **WHEN_UNLOCKED** : `"AccessibleWhenUnlocked"` > The data in the keychain item can be accessed only while the device is unlocked by the user. > #### Defined in > enums.ts:10 #### WHEN_UNLOCKED_THIS_DEVICE_ONLY > **WHEN_UNLOCKED_THIS_DEVICE_ONLY** : `"AccessibleWhenUnlockedThisDeviceOnly"` > The data in the keychain item can be accessed only while the device is unlocked by the user. Items with this attribute do not migrate to a new device. > #### Defined in > enums.ts:18 ``` -------------------------------- ### requestSharedWebCredentials Source: https://oblador.github.io/react-native-keychain/docs/api Requests shared web credentials for a given URL. ```APIDOC ## requestSharedWebCredentials ### Description Requests shared web credentials for a given URL. ### Method `requestSharedWebCredentials(url: string): Promise` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **url** (string) - Required - The URL for which to request credentials. ### Response #### Success Response (200) - **SharedWebCredentials | null**: An object containing the shared web credentials, or null if not available. ``` -------------------------------- ### AUTHENTICATION_TYPE.BIOMETRICS Source: https://oblador.github.io/react-native-keychain/docs/api/enumerations/AUTHENTICATION_TYPE Represents authentication using biometric methods like Touch ID or Face ID. ```APIDOC ## Enumeration Member: BIOMETRICS ### Description Device owner is going to be authenticated using a biometric method (Touch ID or Face ID). ### Value `"AuthenticationWithBiometrics"` ### Defined in enums.ts:50 ``` -------------------------------- ### setSharedWebCredentials Source: https://oblador.github.io/react-native-keychain/docs/api Sets shared web credentials for a given URL. ```APIDOC ## setSharedWebCredentials ### Description Sets shared web credentials for a given URL. ### Method `setSharedWebCredentials(url: string, username: string, password: string): Promise` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **url** (string) - Required - The URL for which to set credentials. - **username** (string) - Required - The username. - **password** (string) - Required - The password to store. ### Response #### Success Response (200) - **void**: Indicates successful storage. ``` -------------------------------- ### isPasscodeAuthAvailable Source: https://oblador.github.io/react-native-keychain/docs/api Checks if passcode authentication is available on the device. ```APIDOC ## isPasscodeAuthAvailable ### Description Checks if passcode authentication is available on the device. ### Method `isPasscodeAuthAvailable(): Promise` ### Parameters None ### Response #### Success Response (200) - **boolean**: Returns `true` if passcode authentication is available, `false` otherwise. ``` -------------------------------- ### SECURITY_LEVEL Enumeration Source: https://oblador.github.io/react-native-keychain/docs/api/enumerations/SECURITY_LEVEL The SECURITY_LEVEL enumeration provides options for specifying the desired security level when storing credentials. Each level has different implications for how and where the credentials are stored. ```APIDOC ## Enumeration: SECURITY_LEVEL Enum representing security levels. ### Platform Android ### Enumeration Members #### ANY > **ANY** : `number` No security guarantees needed (default value). Credentials can be stored in FB Secure Storage. #### Defined in enums.ts:67 * * * ### SECURE_HARDWARE > **SECURE_HARDWARE** : `number` Requires for the key to be stored on a secure hardware (Trusted Execution Environment or Secure Environment). Read this article for more information: https://developer.android.com/privacy-and-security/keystore#ExtractionPrevention #### Defined in enums.ts:64 * * * ### SECURE_SOFTWARE > **SECURE_SOFTWARE** : `number` Requires for the key to be stored in the Android Keystore, separate from the encrypted data. #### Defined in enums.ts:59 ``` -------------------------------- ### Force Specific Encryption Level Source: https://oblador.github.io/react-native-keychain/docs/faq To force a specific encryption level when saving a secret, use the 'storage' option. If attempting to force RSA storage when biometrics are unavailable, the call will be rejected. ```javascript setGenericPassword({ ...otherProps, storage: "AES_GCM_NO_AUTH" }); ``` -------------------------------- ### hasGenericPassword Source: https://oblador.github.io/react-native-keychain/docs/api Checks if a generic password exists in the keychain for a given service and username. ```APIDOC ## hasGenericPassword ### Description Checks if a generic password exists in the keychain for a given service and username. ### Method `hasGenericPassword(service: string, username: string): Promise` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **service** (string) - Required - The service name. - **username** (string) - Required - The username. ### Response #### Success Response (200) - **boolean**: Returns `true` if a generic password exists, `false` otherwise. ```