### Enable installation message signing with ApproovDefaultMessageSigning (Kotlin) Source: https://github.com/approov/approov-service-okhttp/blob/main/REFERENCE.md Provide an ApproovDefaultMessageSigning object instantiated as shown to enable installation message signing. This default setup provides a basic signature mechanism that is not specific to the requests that are issued by an app. The default signature parameter factory can be customized by calling further methods. ```kotlin ApproovService.setApproovInterceptorExtensions( ApproovDefaultMessageSigning().setDefaultFactory( ApproovDefaultMessageSigning.generateDefaultSignatureParametersFactory())) ``` -------------------------------- ### Usage example for ApproovDefaultMessageSigning Source: https://github.com/approov/approov-service-okhttp/blob/main/_autodocs/api-reference/approov-default-message-signing.md Initializes ApproovService, sets the default factory, and installs the signing mutator so every Approov-protected OkHttp request gets Signature / Signature-Input headers. ```java ApproovService.initialize(getApplicationContext(), config); ApproovDefaultMessageSigning signing = new ApproovDefaultMessageSigning(); signing.setDefaultFactory(ApproovDefaultMessageSigning.generateDefaultSignatureParametersFactory()); ApproovService.setServiceMutator(signing); // Now every Approov-protected OkHttp request gets Signature / Signature-Input headers. OkHttpClient client = ApproovService.getOkHttpClient(); ``` -------------------------------- ### Enable installation message signing with ApproovDefaultMessageSigning (Java) Source: https://github.com/approov/approov-service-okhttp/blob/main/REFERENCE.md Provide an ApproovDefaultMessageSigning object instantiated as shown to enable installation message signing. This default setup provides a basic signature mechanism that is not specific to the requests that are issued by an app. The default signature parameter factory can be customized by calling further methods. ```java ApproovService.setApproovInterceptorExtensions( new ApproovDefaultMessageSigning().setDefaultFactory( ApproovDefaultMessageSigning.generateDefaultSignatureParametersFactory())); ``` -------------------------------- ### Usage example for OkHttp client management Source: https://github.com/approov/approov-service-okhttp/blob/main/_autodocs/api-reference/approovservice.md Shows one-time registration of a customized builder and per-call client acquisition. ```java // one-time registration of a customized builder ApproovService.setOkHttpClientBuilder(new OkHttpClient.Builder().connectTimeout(5, TimeUnit.SECONDS)); ApproovService.setOkHttpClientBuilder("short-timeout", new OkHttpClient.Builder().readTimeout(2, TimeUnit.SECONDS)); // per-call client acquisition OkHttpClient client = ApproovService.getOkHttpClient("short-timeout"); client.newCall(new Request.Builder().url("https://api.example.com/").build()).enqueue(callback); ``` -------------------------------- ### Create Custom OkHttpClient in Java Source: https://github.com/approov/approov-service-okhttp/blob/main/README.md Shows how to create a customized OkHttpClient with a 5-second connect timeout, which can be passed to ApproovService. ```java OkHttpClient client = new OkHttpClient.Builder().connectTimeout(5, TimeUnit.SECONDS).build(); ``` -------------------------------- ### Create Custom OkHttpClient in Kotlin Source: https://github.com/approov/approov-service-okhttp/blob/main/README.md Shows how to create a customized OkHttpClient with a 5-second connect timeout, which can be passed to ApproovService. ```kotlin val client = OkHttpClient.Builder().connectTimeout(5, TimeUnit.SECONDS).build() ``` -------------------------------- ### Get Named OkHttpClient in Kotlin Source: https://github.com/approov/approov-service-okhttp/blob/main/README.md Retrieves the OkHttpClient associated with the named builder 'short-timeout'. ```kotlin val client = ApproovService.getOkHttpClient("short-timeout") ``` -------------------------------- ### Get Named OkHttpClient in Java Source: https://github.com/approov/approov-service-okhttp/blob/main/README.md Retrieves the OkHttpClient associated with the named builder 'short-timeout'. ```java OkHttpClient client = ApproovService.getOkHttpClient("short-timeout"); ``` -------------------------------- ### setInstallAttrsInToken(String attrs) Source: https://github.com/approov/approov-service-okhttp/blob/main/_autodocs/api-reference/approovservice.md Sets a signed JWT of install attributes to associate with the app installation; the next token fetch bypasses the cache. Throws ApproovException for invalid attrs or uninitialized SDK. ```APIDOC ## setInstallAttrsInToken(String attrs) ### Description Sets a signed JWT of install attributes to associate with the app installation; the next token fetch bypasses the cache. Throws ApproovException for invalid attrs or uninitialized SDK. ### Method setInstallAttrsInToken ### Parameters - `attrs` (String) - Required - The install attributes to set. ### Response No return value. ### Exceptions Throws ApproovException if the attributes are invalid or the SDK is uninitialized. ``` -------------------------------- ### Usage example for SignatureBaseBuilder Source: https://github.com/approov/approov-service-okhttp/blob/main/_autodocs/api-reference/util-sig.md Shows how to build a signature base using SignatureParameters and a ComponentProvider, then sign it with the account key. Missing component values throw a RuntimeException. The base contains the Approov token when covered — never log it. ```java SignatureParameters params = new SignatureParameters() .addComponentIdentifier(ComponentProvider.DC_METHOD) .addComponentIdentifier(ComponentProvider.DC_TARGET_URI) .setAlg(ApproovDefaultMessageSigning.ALG_HS256) .setCreated(System.currentTimeMillis() / 1000) .setExpires(System.currentTimeMillis() / 1000 + 15); ComponentProvider ctx = /* your ComponentProvider implementation */; String base = new SignatureBaseBuilder(params, ctx).createSignatureBase(); String sig = ApproovService.getAccountMessageSignature(base); // sign with account key ``` -------------------------------- ### setInstallAttrsInToken(String) method signature Source: https://github.com/approov/approov-service-okhttp/blob/main/_autodocs/api-reference/approovservice.md Sets a signed JWT of install attributes to associate with the app installation; the next token fetch bypasses the cache. Throws ApproovException for invalid attrs or uninitialized SDK. ```java public static void setInstallAttrsInToken(String attrs) throws ApproovException ``` -------------------------------- ### ApproovService.getOkHttpClient(String) Source: https://github.com/approov/approov-service-okhttp/blob/main/README.md Returns an OkHttpClient built from the named builder previously set with setOkHttpClientBuilder(String, OkHttpClient.Builder). ```APIDOC ## ApproovService.getOkHttpClient(String) ### Description Returns an OkHttpClient built from the named builder previously set with setOkHttpClientBuilder(String, OkHttpClient.Builder). ### Method `getOkHttpClient(String name)` ### Parameters - **name** (String) - Required - The name of the builder to use. ### Returns - **OkHttpClient** - A client configured with the specified builder. ### Example ```java OkHttpClient client = ApproovService.getOkHttpClient("short-timeout"); ``` ```kotlin val client = ApproovService.getOkHttpClient("short-timeout") ``` ``` -------------------------------- ### getTag() / setTag(String tag) Source: https://github.com/approov/approov-service-okhttp/blob/main/_autodocs/api-reference/util-sig.md Gets or sets the application tag. ```APIDOC ## getTag() / setTag(String tag) ### Description Gets or sets the application tag. ### Method Method ### Signatures ```java public String getTag() public SignatureParameters setTag(String tag) ``` ### Parameters (setTag) - **tag** (String) - Required - The application tag. ### Returns - **getTag**: String - The current tag. - **setTag**: SignatureParameters - This instance for chaining. ``` -------------------------------- ### Initialize ApproovService in Kotlin (onCreate) Source: https://github.com/approov/approov-service-okhttp/blob/main/README.md Kotlin equivalent of the Java initialization. Uses applicationContext and logs the device ID and correlation ID. On failure, re-initializes with an empty config to continue unprotected. ```Kotlin import android.util.Log import io.approov.service.okhttp.ApproovService import java.util.UUID class YourApp : Application() { override fun onCreate() { super.onCreate() // App-generated id to correlate this install/session across your own logs and // backend. Use a UUID, or any session/user identifier you have — NOT an Approov secret. val correlationId = UUID.randomUUID().toString() try { ApproovService.initialize(applicationContext, "") if (ApproovService.isApproovEnabled()) { Log.i("YourApp", "Approov initialized; deviceID=${ApproovService.getDeviceID()} session=$correlationId") } } catch (e: Exception) { // Initialization failed — log and continue UNPROTECTED so the app still works. Log.e("YourApp", "Approov init failed (session=$correlationId); continuing unprotected", e) ApproovService.initialize(applicationContext, "") // empty config = bypass mode } } } ``` -------------------------------- ### Initialize ApproovService in Java (onCreate) Source: https://github.com/approov/approov-service-okhttp/blob/main/README.md Initializes ApproovService in the Application's onCreate method. On success, logs the device ID and a correlation ID. On failure, re-initializes with an empty config to continue unprotected. ```Java import android.util.Log; import io.approov.service.okhttp.ApproovService; import java.util.UUID; public class YourApp extends Application { private static final String TAG = "YourApp"; @Override public void onCreate() { super.onCreate(); // App-generated id to correlate this install/session across your own logs and // backend. Use a UUID, or any session/user identifier you have — NOT an Approov secret. String correlationId = UUID.randomUUID().toString(); try { ApproovService.initialize(getApplicationContext(), ""); if (ApproovService.isApproovEnabled()) { Log.i(TAG, "Approov initialized; deviceID=" + ApproovService.getDeviceID() + " session=" + correlationId); } } catch (Exception e) { // Initialization failed — log and continue UNPROTECTED so the app still works. Log.e(TAG, "Approov init failed (session=" + correlationId + "); continuing unprotected", e); ApproovService.initialize(getApplicationContext(), ""); // empty config = bypass mode } } } ``` -------------------------------- ### getInstallMessageSignature Source: https://github.com/approov/approov-service-okhttp/blob/main/REFERENCE.md Gets the install message signature for the given message, returned as the base64 encoding of the signature in ASN.1 DER format. Uses an app install specific signing key generated on first launch. ```APIDOC ## getInstallMessageSignature ### Description Gets the install message signature for the given message, returned as the base64 encoding of the signature in ASN.1 DER format. Uses an app install specific signing key generated on first launch. ### Method Java/Kotlin static method ### Signature - Java: `public static String getInstallMessageSignature(String message) throws ApproovException` - Kotlin: `@Throws(ApproovException::class) fun getInstallMessageSignature(message: String): String` ### Parameters - **message** (String) - Required - The message to sign. ### Throws - `ApproovException` - If no signature is available because there has been no prior fetch or the feature is not enabled. ``` -------------------------------- ### Usage example: fetchToken and fetchSecureString with error handling Source: https://github.com/approov/approov-service-okhttp/blob/main/_autodocs/api-reference/approovservice.md Shows how to fetch an Approov token and a secure string, handling ApproovRejectionException and ApproovFetchStatusException. The token and secure string must never be cached. ```java try { String token = ApproovService.fetchToken("https://api.example.com/v1/data"); // use token, never cache it String key = ApproovService.fetchSecureString("stripe-key", null); } catch (ApproovRejectionException e) { Log.e(TAG, "Device rejected, ARC=" + e.getARC() + " reasons=" + e.getRejectionReasons()); } catch (ApproovFetchStatusException e) { Log.e(TAG, "Fetch failed: " + e.getTokenFetchStatus()); } ``` -------------------------------- ### Get OkHttpClient in Java Source: https://github.com/approov/approov-service-okhttp/blob/main/README.md Retrieves the cached OkHttpClient from ApproovService for protected API calls. The client includes an interceptor for channel integrity and may add Approov-Token or substitute app secrets. ```java OkHttpClient client = ApproovService.getOkHttpClient(); ``` -------------------------------- ### Get OkHttpClient in Kotlin Source: https://github.com/approov/approov-service-okhttp/blob/main/README.md Retrieves the cached OkHttpClient from ApproovService for protected API calls. The client includes an interceptor for channel integrity and may add Approov-Token or substitute app secrets. ```kotlin val client = ApproovService.getOkHttpClient() ``` -------------------------------- ### Set OkHttpClient Builder in Java Source: https://github.com/approov/approov-service-okhttp/blob/main/README.md Registers a custom OkHttpClient.Builder with ApproovService. This call only needs to be made once; subsequent getOkHttpClient() calls will use the builder values. ```java ApproovService.setOkHttpClientBuilder(new OkHttpClient.Builder().connectTimeout(5, TimeUnit.SECONDS)); ``` -------------------------------- ### handlePinningShouldProcessRequest(Request) Source: https://github.com/approov/approov-service-okhttp/blob/main/_autodocs/api-reference/approovservice-mutator.md Called at the start of ApproovPinningInterceptor processing. Returns true to apply certificate pinning, false to skip it for this request. ```APIDOC ## handlePinningShouldProcessRequest(Request) ### Description Called at the start of `ApproovPinningInterceptor` processing. Returns `true` to apply certificate pinning, `false` to skip it for this request. ### Method `handlePinningShouldProcessRequest` ### Signature ```java default boolean handlePinningShouldProcessRequest(Request request) { // By default do not skip pinning for any requests return true; } ``` ### Parameters - **request** (Request) - The request being processed ### Returns - **boolean** - `true` to apply certificate pinning, `false` to skip it ``` -------------------------------- ### getSubstitutionQueryParams Source: https://github.com/approov/approov-service-okhttp/blob/main/REFERENCE.md Gets the map of query parameter keys to compiled regex patterns currently subject to secure string substitution. Throws IllegalStateException if ApproovService is not initialized. ```APIDOC ## getSubstitutionQueryParams ### Description Gets the map of query parameter keys to compiled regex patterns currently subject to secure string substitution. This throws `IllegalStateException` if `ApproovService` is not initialized. ### Method N/A (SDK method) ### Endpoint N/A (SDK method) ### Parameters #### Method Parameters None. ### Request Example N/A ### Response #### Success Response - **Map** - A map of query parameter keys to compiled regex patterns. #### Response Example N/A ### Language Bindings **Java:** ```java Map getSubstitutionQueryParams() ``` **Kotlin:** ```kotlin fun getSubstitutionQueryParams(): Map ``` ``` -------------------------------- ### Set OkHttpClient Builder in Kotlin Source: https://github.com/approov/approov-service-okhttp/blob/main/README.md Registers a custom OkHttpClient.Builder with ApproovService. This call only needs to be made once; subsequent getOkHttpClient() calls will use the builder values. ```kotlin ApproovService.setOkHttpClientBuilder(OkHttpClient.Builder().connectTimeout(5, TimeUnit.SECONDS)) ``` -------------------------------- ### ApproovService.setOkHttpClientBuilder(OkHttpClient.Builder) Source: https://github.com/approov/approov-service-okhttp/blob/main/README.md Sets a custom OkHttpClient.Builder to be used for all subsequent calls to getOkHttpClient(). This call only needs to be made once; subsequent calls will use the builder values. ```APIDOC ## ApproovService.setOkHttpClientBuilder(OkHttpClient.Builder) ### Description Sets a custom OkHttpClient.Builder to be used for all subsequent calls to getOkHttpClient(). This call only needs to be made once; subsequent calls will use the builder values. ### Method `setOkHttpClientBuilder(OkHttpClient.Builder builder)` ### Parameters - **builder** (OkHttpClient.Builder) - Required - The custom builder to use. ### Example ```java ApproovService.setOkHttpClientBuilder(new OkHttpClient.Builder().connectTimeout(5, TimeUnit.SECONDS)); ``` ```kotlin ApproovService.setOkHttpClientBuilder(OkHttpClient.Builder().connectTimeout(5, TimeUnit.SECONDS)) ``` ``` -------------------------------- ### Usage example: building Signature header and item parameters Source: https://github.com/approov/approov-service-okhttp/blob/main/_autodocs/api-reference/util-sfv-types.md Shows how to build an RFC 9421 Signature header value using Dictionary and ByteSequenceItem, and how to add parameters to a StringItem using Parameters. ```java // Build the RFC 9421 "Signature" header value String signatureHeader = Dictionary.valueOf(Collections.singletonMap( "install", ByteSequenceItem.valueOf(signatureBytes))).serialize(); // e.g. install=:: // Parameters on an item StringItem component = StringItem.valueOf("host").withParams( Parameters.valueOf(Collections.singletonMap("name", "example.com"))); ``` -------------------------------- ### SignatureParametersFactory.setUseInstallMessageSigning() Source: https://github.com/approov/approov-service-okhttp/blob/main/_autodocs/api-reference/approov-default-message-signing.md Configures the factory to sign with the install key (`ALG_ES256`). This is the default signing method. ```APIDOC ## SignatureParametersFactory.setUseInstallMessageSigning() ### Description Configures the factory to sign with the install key (`ALG_ES256`). This is the default signing method. ### Method Fluent setter ### Returns `SignatureParametersFactory` - this factory for chaining ### Usage Example ```java SignatureParametersFactory factory = new SignatureParametersFactory().setUseInstallMessageSigning(); ``` ``` -------------------------------- ### getKeyid() / setKeyid(String keyid) Source: https://github.com/approov/approov-service-okhttp/blob/main/_autodocs/api-reference/util-sig.md Gets or sets the key identifier. ```APIDOC ## getKeyid() / setKeyid(String keyid) ### Description Gets or sets the key identifier. ### Method Method ### Signatures ```java public String getKeyid() public SignatureParameters setKeyid(String keyid) ``` ### Parameters (setKeyid) - **keyid** (String) - Required - The key identifier. ### Returns - **getKeyid**: String - The current key identifier. - **setKeyid**: SignatureParameters - This instance for chaining. ``` -------------------------------- ### Round-trip usage example with serialization Source: https://github.com/approov/approov-service-okhttp/blob/main/_autodocs/api-reference/util-sfv-parser.md Demonstrates parsing a dictionary, serializing it, and parsing a string item. The serialized output is shown in a comment as "a=1, b=\"two\", c". ```java Dictionary dict = Parser.parseDictionary("a=1, b=\"two\", c=?1"); String serialized = dict.serialize(); // "a=1, b=\"two\", c" StringItem s = Parser.parseString("\"hello\""); ``` -------------------------------- ### getSubstitutionHeaders Source: https://github.com/approov/approov-service-okhttp/blob/main/REFERENCE.md Gets the map of headers currently subject to secure string substitution, mapped to their required prefixes. Throws IllegalStateException if ApproovService is not initialized. ```APIDOC ## getSubstitutionHeaders ### Description Gets the map of headers currently subject to secure string substitution, mapped to their required prefixes. Throws IllegalStateException if ApproovService is not initialized. ### Method N/A (SDK method) ### Endpoint N/A (SDK method) ### Parameters None ### Request Example N/A ### Response - Returns `Map` - A map of header names to their required prefixes. ### Error Handling - Throws `IllegalStateException` if `ApproovService` is not initialized. ``` -------------------------------- ### Set Named OkHttpClient Builder in Java Source: https://github.com/approov/approov-service-okhttp/blob/main/README.md Registers a named OkHttpClient.Builder with ApproovService for use with multiple different builders. The name 'short-timeout' is used to retrieve the client later. ```java ApproovService.setOkHttpClientBuilder("short-timeout", new OkHttpClient.Builder().connectTimeout(5, TimeUnit.SECONDS)); ``` -------------------------------- ### Add Approov Android SDK dependency Source: https://github.com/approov/approov-service-okhttp/blob/main/README.md Add the closed-source Approov Android SDK dependency to avoid build errors. This is a further dependency of the service.okhttp wrapper and may be required in some cases. ```groovy implementation("io.approov:approov-android-sdk:3.5.3") ``` -------------------------------- ### getAlg() / setAlg(String alg) Source: https://github.com/approov/approov-service-okhttp/blob/main/_autodocs/api-reference/util-sig.md Gets or sets the signing algorithm, e.g. ecdsa-p256-sha256 or hmac-sha256. ```APIDOC ## getAlg() / setAlg(String alg) ### Description Gets or sets the signing algorithm, e.g. ecdsa-p256-sha256 or hmac-sha256. ### Method Method ### Signatures ```java public String getAlg() public SignatureParameters setAlg(String alg) ``` ### Parameters (setAlg) - **alg** (String) - Required - The signing algorithm. ### Returns - **getAlg**: String - The current algorithm. - **setAlg**: SignatureParameters - This instance for chaining. ``` -------------------------------- ### Set Named OkHttpClient Builder in Kotlin Source: https://github.com/approov/approov-service-okhttp/blob/main/README.md Registers a named OkHttpClient.Builder with ApproovService for use with multiple different builders. The name 'short-timeout' is used to retrieve the client later. ```kotlin ApproovService.setOkHttpClientBuilder("short-timeout", OkHttpClient.Builder().connectTimeout(5, TimeUnit.SECONDS)) ``` -------------------------------- ### handlePinningShouldProcessRequest default method Source: https://github.com/approov/approov-service-okhttp/blob/main/_autodocs/api-reference/approovservice-mutator.md Called at the start of ApproovPinningInterceptor processing. Returns true to apply certificate pinning, false to skip it for this request. ```java default boolean handlePinningShouldProcessRequest(Request request) { // By default do not skip pinning for any requests return true; } ``` -------------------------------- ### Add Approov OkHttp service dependency Source: https://github.com/approov/approov-service-okhttp/blob/main/README.md Add the Approov service wrapper for OkHttp to your Gradle build file. Requires a trial or paid Approov account and an Android project with minSdk 23. After adding, perform a Gradle sync. ```groovy implementation("io.approov:service.okhttp:3.5.8") ``` -------------------------------- ### ApproovService.setOkHttpClientBuilder(String, OkHttpClient.Builder) Source: https://github.com/approov/approov-service-okhttp/blob/main/README.md Sets a named OkHttpClient.Builder for use with a specific client name. This allows multiple different builders with different configurations. ```APIDOC ## ApproovService.setOkHttpClientBuilder(String, OkHttpClient.Builder) ### Description Sets a named OkHttpClient.Builder for use with a specific client name. This allows multiple different builders with different configurations. ### Method `setOkHttpClientBuilder(String name, OkHttpClient.Builder builder)` ### Parameters - **name** (String) - Required - The name of the builder. - **builder** (OkHttpClient.Builder) - Required - The custom builder to use. ### Example ```java ApproovService.setOkHttpClientBuilder("short-timeout", new OkHttpClient.Builder().connectTimeout(5, TimeUnit.SECONDS)); ``` ```kotlin ApproovService.setOkHttpClientBuilder("short-timeout", OkHttpClient.Builder().connectTimeout(5, TimeUnit.SECONDS)) ``` ``` -------------------------------- ### setOkHttpClientBuilder(String name, OkHttpClient.Builder) Source: https://github.com/approov/approov-service-okhttp/blob/main/_autodocs/configuration.md Sets the OkHttp client builder for a given client name. Unknown names get a fresh builder; cached clients are evicted when the builder changes. ```APIDOC ## setOkHttpClientBuilder(String name, OkHttpClient.Builder) ### Description Sets the OkHttp client builder for a given client name. Unknown names get a fresh builder; cached clients are evicted when the builder changes. ### Method setOkHttpClientBuilder ### Parameters - **name** (String) - Required - Client name. - **builder** (OkHttpClient.Builder) - Required - OkHttp client builder. ### Response No return value. ``` -------------------------------- ### getOkHttpClient() Source: https://github.com/approov/approov-service-okhttp/blob/main/REFERENCE.md Gets the default OkHttpClient that enables the Approov service. This adds the Approov token in a header to requests, performs header or query parameter substitutions, and pins connections. The client is constructed lazily on demand but cached if there are no changes. ```APIDOC ## getOkHttpClient() ### Description Gets the default `OkHttpClient` that enables the Approov service. This adds the Approov token in a header to requests, performs header or query parameter substitutions, and pins connections. The client is constructed lazily on demand but cached if there are no changes. ### Method GET ### Endpoint `getOkHttpClient()` ### Parameters None ### Request Example None ### Response #### Success Response - **OkHttpClient** - The configured OkHttpClient instance. #### Response Example ```java OkHttpClient client = approovService.getOkHttpClient(); ``` ``` -------------------------------- ### ApproovService.getOkHttpClient() Source: https://github.com/approov/approov-service-okhttp/blob/main/README.md Returns a cached OkHttpClient configured with an interceptor that protects channel integrity and may add Approov-Token or substitute app secrets. Use this client for all API calls you wish to protect. ```APIDOC ## ApproovService.getOkHttpClient() ### Description Returns a cached OkHttpClient configured with an interceptor that protects channel integrity (with pinning or managed trust roots) and may add Approov-Token or substitute app secrets. Use this client for all API calls you wish to protect. ### Method `getOkHttpClient()` ### Parameters None. ### Returns - **OkHttpClient** - A client configured with the Approov interceptor. ### Example ```java OkHttpClient client = ApproovService.getOkHttpClient(); ``` ```kotlin val client = ApproovService.getOkHttpClient() ``` ``` -------------------------------- ### Customize Approov message signing behavior Source: https://github.com/approov/approov-service-okhttp/blob/main/USAGE.md Overrides the default signature factory to use account message signing and a custom expiry lifetime. Always start from the safe default factory; a bare factory produces a security-worthless signature. ```kotlin import io.approov.service.okhttp.ApproovDefaultMessageSigning.SignatureParametersFactory // Always start from the safe default factory and override what you need. // Using a bare SignatureParametersFactory() produces a signature that // covers no request components and is therefore security-worthless. val factory = ApproovDefaultMessageSigning.generateDefaultSignatureParametersFactory() .setUseAccountMessageSigning() // switch from install (default) to account signing .setExpiresLifetime(60) // override the default 15s expiry val signer = ApproovDefaultMessageSigning() .setDefaultFactory(factory) .putHostFactory("api.example.com", factory) ApproovService.setServiceMutator(signer) ``` -------------------------------- ### Default factory configuration Source: https://github.com/approov/approov-service-okhttp/blob/main/_autodocs/api-reference/approov-default-message-signing.md Configures the factory with base parameters, install message signing, created timestamp, expires lifetime of 15 seconds, Approov token and TraceID headers, optional headers, and SHA-256 body digest. ```java return new SignatureParametersFactory() .setBaseParameters(baseParameters) .setUseInstallMessageSigning() .setAddCreated(true) .setExpiresLifetime(defaultExpiresLifetime) // 15 .setAddApproovTokenHeader(true) .setAddApproovTraceIDHeader(true) .addOptionalHeaders("Authorization", "Content-Length", "Content-Type") .setBodyDigestConfig(DIGEST_SHA256, false); ``` -------------------------------- ### initialize(Context, String, String) Source: https://github.com/approov/approov-service-okhttp/blob/main/_autodocs/configuration.md Initializes the Approov service with the account configuration string and an optional comment. Must be called once, typically in Application.onCreate. ```APIDOC ## initialize(Context, String, String) ### Description Initializes the Approov service with the account configuration string and an optional comment. Must be called once, typically in Application.onCreate. ### Method initialize ### Parameters - **context** (Context) - Required - The application context. - **config** (String) - Required - Account configuration string; empty string enables bypass mode. - **comment** (String) - Optional - Comment for the configuration; null allowed. ### Response No return value. ``` -------------------------------- ### setApproovInterceptorExtensions(ApproovServiceMutator) Source: https://github.com/approov/approov-service-okhttp/blob/main/REFERENCE.md OBSOLETED: Use `setServiceMutator` instead. Sets the interceptor extensions callback handler. This facility supports message signing that is independent from the rest of the attestation flow. The default ApproovService layer issues no callbacks. Provide a non-null handler to add functionality to the attestation flow. The configuration used to control installation message signing is passed in the `mutator` parameter. The behavior of the provided configuration must remain constant while in use by the ApproovService. Passing `null` to this method will disable message signing. ```APIDOC ## setApproovInterceptorExtensions(ApproovServiceMutator) ### Description OBSOLETED: Use `setServiceMutator` instead. Sets the interceptor extensions callback handler. This facility supports message signing that is independent from the rest of the attestation flow. The default ApproovService layer issues no callbacks. Provide a non-null handler to add functionality to the attestation flow. The configuration used to control installation message signing is passed in the `mutator` parameter. The behavior of the provided configuration must remain constant while in use by the ApproovService. Passing `null` to this method will disable message signing. ### Method setApproovInterceptorExtensions ### Endpoint N/A (SDK method) ### Parameters - **mutator** (ApproovServiceMutator) - Required - The interceptor extensions callback handler. Passing `null` disables message signing. ### Usage This is a deprecated alias for `setServiceMutator`; the parameter is an `ApproovServiceMutator` (the legacy `ApproovInterceptorExtensions` interface is a deprecated subtype of it). ### Example **Java:** ```java ApproovService.setApproovInterceptorExtensions( new ApproovDefaultMessageSigning().setDefaultFactory( ApproovDefaultMessageSigning.generateDefaultSignatureParametersFactory())); ``` **Kotlin:** ```kotlin ApproovService.setApproovInterceptorExtensions( ApproovDefaultMessageSigning().setDefaultFactory( ApproovDefaultMessageSigning.generateDefaultSignatureParametersFactory())) ``` ``` -------------------------------- ### initialize(Context, String, String) Source: https://github.com/approov/approov-service-okhttp/blob/main/REFERENCE.md Initializes the Approov SDK with the provided configuration and a comment passed directly to the native SDK. The comment can be used to pass startup options or trigger re-initialization flows. ```APIDOC ## initialize(Context, String, String) ### Description Initializes the Approov SDK with the provided configuration and a comment passed directly to the native SDK. The comment can be used to pass startup options or trigger re-initialization flows. ### Method initialize ### Parameters - **context** (Context) - Required - The application context. - **config** (String) - Required - The configuration string provided during onboarding or obtained via the Approov CLI. - **comment** (String?) - Optional - Passed directly to the native SDK. Use strings starting with `options:` for custom startup options, `reinit` to trigger native re-initialization, or `null` when no comment is needed. ### Exceptions - **ApproovException** - Thrown if there is a problem during initialization. - **ApproovNetworkException** - Subclass of ApproovException; indicates a networking issue; user-initiated retry should be allowed. - **ApproovRejectionException** - Subclass of ApproovException; indicates attestation failure; provides getARC() and getRejectionReasons(). ### Notes - Refer to the Approov SDK documentation for full details on supported comment values. ``` -------------------------------- ### Implement ApproovServiceMutator and install it Source: https://github.com/approov/approov-service-okhttp/blob/main/_autodocs/api-reference/approovservice-mutator.md Defines a custom mutator that throws an ApproovException when token fetch fails and supports protection refresh. Install it once with ApproovService.setServiceMutator(). ```java public class MyMutator implements ApproovServiceMutator { @Override public boolean handleInterceptorFetchTokenResult(Approov.TokenFetchResult results, String url) throws ApproovException { // fail the request loudly if there is no token if (results.getStatus() != Approov.TokenFetchStatus.SUCCESS) { throw new ApproovException("no token for " + url); } return true; } @Override public boolean supportsProtectionRefresh() { // our processedRequest callback only adds headers, safe to re-invoke return true; } } // install once ApproovService.setServiceMutator(new MyMutator()); ``` -------------------------------- ### initialize(Context, String) Source: https://github.com/approov/approov-service-okhttp/blob/main/_autodocs/api-reference/approovservice.md Two-argument overload of initialize that delegates to the three-argument form with a null comment. ```APIDOC ## initialize(Context, String) ### Description Two-argument overload delegating to the three-argument form with a `null` comment. ### Method initialize ### Signature public static void initialize(Context context, String config) ### Parameters - **context** (android.content.Context) - Required - Application context; must be an `Application` context. - **config** (String) - Required - Approov account configuration string. Empty string `""` runs in **bypass mode** (no SDK initialization, no protection). Null throws `IllegalArgumentException`. ### Request Example ```java ApproovService.initialize(getApplicationContext(), "your-approov-config-string"); ``` ``` -------------------------------- ### initialize(Context, String) Source: https://github.com/approov/approov-service-okhttp/blob/main/REFERENCE.md Initializes the Approov SDK with the provided configuration. This enables Approov features such as token injection, message signing, secure strings, and pinning. Passing an empty config string bypasses SDK initialization, allowing a later call with a valid config. ```APIDOC ## initialize(Context, String) ### Description Initializes the Approov SDK with the provided configuration. This enables Approov features such as token injection, message signing, secure strings, and pinning. Passing an empty config string bypasses SDK initialization, allowing a later call with a valid config. ### Method initialize ### Parameters - **context** (Context) - Required - The application context. - **config** (String) - Required - The configuration string provided during onboarding or obtained via the Approov CLI. ### Exceptions - **ApproovException** - Thrown if there is a problem during initialization. - **ApproovNetworkException** - Subclass of ApproovException; indicates a networking issue; user-initiated retry should be allowed. - **ApproovRejectionException** - Subclass of ApproovException; indicates attestation failure; provides getARC() and getRejectionReasons(). ### Notes - The `comment` parameter defaults to `null` when not supplied. - Reinitializing with a different non-empty config string is rejected by the platform SDK. ``` -------------------------------- ### Initialize ApproovService in Java (2-arg form) Source: https://github.com/approov/approov-service-okhttp/blob/main/REFERENCE.md Standard initialization of the Approov SDK with context and config. The comment parameter defaults to null. Passing an empty config bypasses SDK initialization, making OkHttpClient behave as plain. Reinitializing with a different non-empty config is rejected. ```Java void initialize(Context context, String config) ``` -------------------------------- ### getNonce() / setNonce(String nonce) Source: https://github.com/approov/approov-service-okhttp/blob/main/_autodocs/api-reference/util-sig.md Gets or sets the nonce value. ```APIDOC ## getNonce() / setNonce(String nonce) ### Description Gets or sets the nonce value. ### Method Method ### Signatures ```java public String getNonce() public SignatureParameters setNonce(String nonce) ``` ### Parameters (setNonce) - **nonce** (String) - Required - The nonce value. ### Returns - **getNonce**: String - The current nonce. - **setNonce**: SignatureParameters - This instance for chaining. ``` -------------------------------- ### getExpires() / setExpires(Long expires) Source: https://github.com/approov/approov-service-okhttp/blob/main/_autodocs/api-reference/util-sig.md Gets or sets the expiration timestamp (epoch seconds). ```APIDOC ## getExpires() / setExpires(Long expires) ### Description Gets or sets the expiration timestamp (epoch seconds). ### Method Method ### Signatures ```java public Long getExpires() public SignatureParameters setExpires(Long expires) ``` ### Parameters (setExpires) - **expires** (Long) - Required - The expiration timestamp in epoch seconds. ### Returns - **getExpires**: Long - The current expiration timestamp. - **setExpires**: SignatureParameters - This instance for chaining. ``` -------------------------------- ### Initialize ApproovService in Java (3-arg form) Source: https://github.com/approov/approov-service-okhttp/blob/main/REFERENCE.md Extended initialization with a comment parameter passed directly to the native SDK. Use for options: startup flags or reinit flows. Pass null or use the 2-arg form when no comment is needed. ```Java void initialize(Context context, String config, String comment) ``` -------------------------------- ### Initialize ApproovService in Kotlin (2-arg form) Source: https://github.com/approov/approov-service-okhttp/blob/main/REFERENCE.md Standard initialization of the Approov SDK with context and config. The comment parameter defaults to null. Passing an empty config bypasses SDK initialization, making OkHttpClient behave as plain. Reinitializing with a different non-empty config is rejected. ```Kotlin fun initialize(context: Context, config: String) ``` -------------------------------- ### getCreated() / setCreated(Long created) Source: https://github.com/approov/approov-service-okhttp/blob/main/_autodocs/api-reference/util-sig.md Gets or sets the creation timestamp (epoch seconds). ```APIDOC ## getCreated() / setCreated(Long created) ### Description Gets or sets the creation timestamp (epoch seconds). ### Method Method ### Signatures ```java public Long getCreated() public SignatureParameters setCreated(Long created) ``` ### Parameters (setCreated) - **created** (Long) - Required - The creation timestamp in epoch seconds. ### Returns - **getCreated**: Long - The current creation timestamp. - **setCreated**: SignatureParameters - This instance for chaining. ``` -------------------------------- ### initialize(Context, String) method signature Source: https://github.com/approov/approov-service-okhttp/blob/main/_autodocs/api-reference/approovservice.md Two-argument overload that delegates to the three-argument form with a null comment. ```java public static void initialize(Context context, String config) { // default uses null comment initialize(context, config, null); } ``` -------------------------------- ### addComponentIdentifier(String identifier) Source: https://github.com/approov/approov-service-okhttp/blob/main/_autodocs/api-reference/util-sig.md Adds a component; identifiers not starting with @ are lowercased (Locale.US) before being wrapped in a StringItem; derived identifiers (@...) are kept as-is. ```APIDOC ## addComponentIdentifier(String identifier) ### Description Adds a component; identifiers not starting with @ are lowercased (Locale.US) before being wrapped in a StringItem; derived identifiers (@...) are kept as-is. ### Method Method ### Signature ```java public SignatureParameters addComponentIdentifier(String identifier) ``` ### Parameters - **identifier** (String) - Required - The component identifier. ### Returns - **SignatureParameters** - This instance for chaining. ``` -------------------------------- ### initialize(Context, String, String) method signature Source: https://github.com/approov/approov-service-okhttp/blob/main/_autodocs/api-reference/approovservice.md Declares the three-argument overload of ApproovService.initialize. The context must be an Application context; an empty config string runs in bypass mode, and a null config throws IllegalArgumentException. ```java public static synchronized void initialize(Context context, String config, String comment) ``` -------------------------------- ### addComponentIdentifier(String identifier) Source: https://github.com/approov/approov-service-okhttp/blob/main/_autodocs/api-reference/util-sig.md Adds a component; identifiers not starting with @ are lowercased (Locale.US) before being wrapped in a StringItem; derived identifiers (@...) are kept as-is. ```java public SignatureParameters addComponentIdentifier(String identifier) ``` -------------------------------- ### getOkHttpClient() Source: https://github.com/approov/approov-service-okhttp/blob/main/_autodocs/configuration.md Returns the default OkHttp client with the Approov interceptor stack. ```APIDOC ## getOkHttpClient() ### Description Returns the default OkHttp client with the Approov interceptor stack. ### Method getOkHttpClient ### Parameters None. ### Response Returns an OkHttpClient instance. ``` -------------------------------- ### createSignatureBase() Source: https://github.com/approov/approov-service-okhttp/blob/main/_autodocs/api-reference/util-sig.md Builds the RFC 9421 signature base string by appending each component identifier and value in order, followed by the @signature-params line. Throws RuntimeException if a required component value is missing. ```APIDOC ## createSignatureBase() ### Description Builds the RFC 9421 signature base string by appending each component identifier and value in order, followed by the @signature-params line. Throws RuntimeException if a required component value is missing. ### Method Method ### Signature ```java public String createSignatureBase() ``` ### Returns - **String** - The signature base string. ### Exceptions - **RuntimeException** - If a required component value is missing. Message: "Couldn't find a value for required parameter: " ### Usage Example ```java SignatureBaseBuilder builder = new SignatureBaseBuilder(params, ctx); String base = builder.createSignatureBase(); String sig = ApproovService.getAccountMessageSignature(base); // sign with account key ``` ### Security Note The base contains the Approov token (when covered) — **never log it**. ``` -------------------------------- ### getOkHttpClient(String builderName) Source: https://github.com/approov/approov-service-okhttp/blob/main/REFERENCE.md Gets an OkHttpClient using a specific named builder. This allows using multiple different builders in the application. ```APIDOC ## getOkHttpClient(String builderName) ### Description Gets an `OkHttpClient` using a specific named builder. This allows using multiple different builders in the application. ### Method GET ### Endpoint `getOkHttpClient(String builderName)` ### Parameters #### Path Parameters - **builderName** (String) - Required - The name of the builder to use. ### Request Example ```java OkHttpClient client = approovService.getOkHttpClient("myBuilder"); ``` ### Response #### Success Response - **OkHttpClient** - The configured OkHttpClient instance. #### Response Example ```java OkHttpClient client = approovService.getOkHttpClient("myBuilder"); ``` ``` -------------------------------- ### Initialize ApproovService in Kotlin (3-arg form) Source: https://github.com/approov/approov-service-okhttp/blob/main/REFERENCE.md Extended initialization with a comment parameter passed directly to the native SDK. Use for options: startup flags or reinit flows. Pass null or use the 2-arg form when no comment is needed. ```Kotlin fun initialize(context: Context, config: String, comment: String?) ``` -------------------------------- ### NumberItem interface Source: https://github.com/approov/approov-service-okhttp/blob/main/_autodocs/types.md Represents numeric items (Integer or Decimal). Provides methods to get the value as a long and the divisor. ```APIDOC ## NumberItem interface ### Description Represents numeric items (Integer or Decimal). Provides methods to get the value as a long and the divisor. ### Methods - `getAsLong()` returns `Long` - Returns the value as a long. - `getDivisor()` - Returns the divisor for decimal values. ``` -------------------------------- ### initialize(Context, String, String) Source: https://github.com/approov/approov-service-okhttp/blob/main/_autodocs/api-reference/approovservice.md Initializes the Approov service layer with the given application context, configuration string, and optional comment. Resets all configuration state to defaults and creates the pinning interceptor when Approov is enabled. ```APIDOC ## initialize(Context, String, String) ### Description Initializes the service layer and resets all configuration state to defaults. If the layer is already enabled and the new config is empty, the call is ignored. On success, the service-layer state is rebuilt, the pinning interceptor is created when Approov is enabled, and the runtime version is recorded. ### Method initialize ### Signature public static synchronized void initialize(Context context, String config, String comment) ### Parameters - **context** (android.content.Context) - Required - Application context; must be an `Application` context (the method calls `context.getApplicationContext()`). - **config** (String) - Required - Approov account configuration string. Empty string `""` runs in **bypass mode** (no SDK initialization, no protection). Null throws `IllegalArgumentException("config must not be null; pass \"\" for bypass mode")`. - **comment** (String) - Optional - Comment string passed through to `Approov.initialize(context, config, "auto", comment)`. Default is `null`. ### Request Example ```java ApproovService.initialize(getApplicationContext(), "your-approov-config-string"); ``` ### Error Handling If `Approov.initialize` throws `IllegalArgumentException` or `IllegalStateException`, it is rethrown and service-layer state is preserved. For bypass fallback: ```java try { ApproovService.initialize(getApplicationContext(), config); } catch (Exception e) { // continue UNPROTECTED so the app still works ApproovService.initialize(getApplicationContext(), ""); } ``` ``` -------------------------------- ### Initialize ApproovService with empty config Source: https://github.com/approov/approov-service-okhttp/blob/main/USAGE.md Use an empty configuration string to operate as a standard OkHttpClient without Approov protection. This is useful for selective activation or during backend maintenance. Later, call initialize with a valid config to enable full protection. ```java // Initialize with an empty string to operate as a standard OkHttpClient ApproovService.initialize(context, ""); ``` -------------------------------- ### setServiceMutator(ApproovServiceMutator) Source: https://github.com/approov/approov-service-okhttp/blob/main/_autodocs/api-reference/approovservice.md Installs the callback handler that customizes behavior at key points in the configuration and attestation flows. Passing `null` reinstates `ApproovServiceMutator.DEFAULT`. ```APIDOC ## setServiceMutator(ApproovServiceMutator) ### Description Installs the callback handler that customizes behavior at key points in the configuration and attestation flows (see [ApproovServiceMutator](approovservice-mutator.md)). Passing `null` reinstates `ApproovServiceMutator.DEFAULT`. ### Method setServiceMutator ### Parameters - **mutator** (ApproovServiceMutator) - Required - The mutator to install, or `null` to reinstate the default. ``` -------------------------------- ### NumberItem Interface Source: https://github.com/approov/approov-service-okhttp/blob/main/_autodocs/api-reference/util-sfv-types.md Common interface for IntegerItem and DecimalItem. Provides methods to get the value as a long and the scaling divisor. ```APIDOC ## NumberItem Interface ### Description Common interface for IntegerItem and DecimalItem. Provides methods to get the value as a long and the scaling divisor. ### Methods - **long getAsLong()** - Returns the numeric value as a long. For IntegerItem, this is the integer value; for DecimalItem, it is the scaled value (e.g., 1.23 becomes 1230). - **int getDivisor()** - Returns 1 for IntegerItem and 1000 for DecimalItem, indicating the scaling factor of getAsLong(). - **NumberItem withParams(Parameters params)** - Returns a new NumberItem with the given parameters. ### Usage Use `getAsLong` to obtain a long representation of the number, and `getDivisor` to interpret the scaling. ``` -------------------------------- ### Custom mutator using ApproovRequestMutations Source: https://github.com/approov/approov-service-okhttp/blob/main/_autodocs/api-reference/approov-request-mutations.md Example of a custom mutator that checks if an Approov token was added and, if so, copies it to a new header 'X-Signed-Token' for message signing. ```java public class MyMutator implements ApproovServiceMutator { @Override public Request handleInterceptorProcessedRequest(Request request, ApproovRequestMutations changes) throws ApproovException { if (changes == null || changes.getTokenHeaderKey() == null) { // no Approov token was added to this request — nothing to do return request; } return request.newBuilder() .header("X-Signed-Token", request.header(changes.getTokenHeaderKey())) .build(); } } ``` -------------------------------- ### precheck() Source: https://github.com/approov/approov-service-okhttp/blob/main/_autodocs/api-reference/approovservice.md Fetches the dummy secure string "precheck-dummy-key" to determine whether the app passes attestation, then delegates the result to getServiceMutator().handlePrecheckResult(approovResults). Requires secure strings enabled on the account. ```APIDOC ## precheck() ### Description Fetches the dummy secure string "precheck-dummy-key" to determine whether the app passes attestation, then delegates the result to getServiceMutator().handlePrecheckResult(approovResults). Requires secure strings enabled on the account. ### Method precheck ### Parameters None. ### Response No return value. ### Exceptions Throws ApproovException if the fetch fails. ``` -------------------------------- ### handleInterceptorShouldProcessRequest(Request) Source: https://github.com/approov/approov-service-okhttp/blob/main/_autodocs/api-reference/approovservice-mutator.md Callback invoked at the start of ApproovTokenInterceptor processing to determine whether the request should be processed with Approov. Default behavior returns false for excluded URLs, true otherwise. ```APIDOC ## handleInterceptorShouldProcessRequest(Request) ### Description Called at the start of `ApproovTokenInterceptor` processing. Default behavior throws `ApproovException` if `request` is null, otherwise returns `false` when the request URL matches one of the exclusion regexes registered via `ApproovService.addExclusionURLRegex(...)`, else `true`. ### Method Callback method ### Signature ```java default boolean handleInterceptorShouldProcessRequest(Request request) throws ApproovException ``` ### Parameters - **request** (Request) - Required - The HTTP request being processed. ### Returns - `true` to process the request with Approov, `false` to pass it through unchanged. ``` -------------------------------- ### Initialize ApproovService with config string Source: https://github.com/approov/approov-service-okhttp/blob/main/_autodocs/api-reference/approovservice.md Initializes the service layer with an Approov account configuration string. Use an Application context; an empty string enables bypass mode. ```java ApproovService.initialize(getApplicationContext(), "your-approov-config-string"); ```