> ## Documentation Index
> Fetch the complete documentation index at: https://docs.ownid.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Security

> Review our guidelines to safeguard your applications and integrations.

## Validating Signatures

Requests from the OwnID server include two headers that can be used to ensure the request has not been tampered with. The first one, `ownid-signature`, is a hash value that the OwnID server generates from a timestamp and the body of the request. The second one, `ownid-timestamp` can be used by your backend to calculate the signature that is based on the timestamp and request body, and then compare the result to the value of `ownid-signature`. If both signatures do not match, the request has been altered.

Because the signatures are generated using an HMAC with the SHA256 hash function, the OwnID server and your backend must use the same cryptographic key when calculating the hash value. You can obtain this key from the OwnID Console, and then add the code generates a hash and compares it to the signature in your backend.

**Obtaining the HMAC Key**

Before the backend can generate the HMACSHA256 value, you must obtain the secret cryptographic key used in the calculation. Simply open your OwnID application in the [OwnID Console](https://console.ownid.com/) and copy the value from **MyApp > Shared Secret**.

**Request Verification**

Now that you have the cryptographic key, the backend can verify requests by generating each request's expected signature and compare it to the one generated by the OwnID server. The backend code must:

* **Step 1:** Extract the `ownid-signature` and `ownid-timestamp` headers from the request. These headers provide the HMAC code generated by the OwnID server and the timestamp it used to generate it.

* **Step 2:** Validate the `ownid-timestamp` for expiration.
  To prevent replay attacks, check whether the provided timestamp is within an acceptable time window. Define a preferred expiration time, such as 1 minute, and validate against the current time. Requests with a timestamp older than this period should be rejected.

* **Step 3:** Create the data string that will be used as an input to the hash function. To create it you need to concatenate:
  * The request body (in a JSON string format)
  * The character `.`
  * The timestamp (from the `ownid-timestamp` header)

* **Step 4:** Use HMAC with SHA256 to calculate a hashed value from the body-timestamp data string. The cryptographic key used in the calculation is the shared secret for your OwnID application.

* **Step 5:** Compare the hash value generated by your backend with the signature extracted from the `ownid-signature` header.

The following code snippets show how the backend might accomplish these steps:

<CodeGroup>
  ```javascript nodeJS theme={null}
  const crypto = require('crypto');

  // Step 1: Extract values from headers and request body
  let key = "<your-shared-secret>"; // This is the shared secret from OwnID Console
  let keyBuffer = Buffer.from(key, 'base64');
  let body = JSON.stringify(req.body);
  let ownIdSignature = req.headers['ownid-signature'];
  let ownIdTimestamp = req.headers['ownid-timestamp'];
  let dataToSign = `${body}.${ownIdTimestamp}`;

  // Step 2: Validate the `ownid-timestamp` for expiration
  const expirationTimeInMilliseconds = 60 * 1000; 
  const currentTime = Date.now(); /
  const ownIdTimestampMs = parseInt(ownIdTimestamp);

  if (Math.abs(currentTime - ownIdTimestampMs) > expirationTimeInMilliseconds) {
      // The timestamp has expired
      throw new Error("Request rejected: Signature has expired.");
  }

  // Step 3: Generate HMAC signature
  const hmac = crypto.createHmac('sha256', keyBuffer);
  hmac.update(dataToSign);
  let signature = hmac.digest('base64');

  // Step 4: Compare the generated signature with the one from the header
  if (signature !== ownIdSignature) {
      // The request has been tampered with
      throw new Error("Request rejected: Invalid signature.");
  }
  ```

  ```python python theme={null}
  import hmac
  import hashlib
  import base64
  import json
  from datetime import datetime, timedelta

  # Step 1: Extract shared secret, headers, and request body
  key = "<your-shared-secret>"  # This is the shared secret from OwnID Console
  key_buffer = base64.b64decode(key)
  data = json.dumps(request.get_json(), separators=(',', ':'))
  own_id_signature = request.headers.get('ownid-signature')
  own_id_timestamp = request.headers.get('ownid-timestamp')
  data_to_sign = f'{data}.{own_id_timestamp}'.encode('utf-8')

  # Step 2: Validate the `ownid-timestamp` for expiration
  expiration_time = timedelta(minutes=1) # Example expiration period of 1 minute
  current_time = datetime.now()  # Current time in seconds since epoch
  # OwnID returns timestamp with miliseconds, remove them.
  own_id_datetime = datetime.fromtimestamp(int(own_id_timestamp) / 1000.0)

  if current_time - own_id_datetime > expiration_time:
      # The timestamp has expired
      raise Exception("Request rejected: Signature has expired.")

  # Step 3: Generate HMAC signature
  signature = hmac.new(key_buffer, data_to_sign, hashlib.sha256).digest()
  signature = base64.b64encode(signature).decode('utf-8')

  # Step 4: Compare the generated signature with the one from the header
  if not signature == own_id_signature:
      # The request body or timestamp has been tampered with
      raise Exception("Request rejected: Invalid signature.")
  ```

  ```csharp csharp theme={null}
  using System;
  using System.Linq;
  using System.Security.Cryptography;
  using System.Text;
  using System.Text.Encodings.Web;
  using System.Text.Json;

  // Step 1: Extract shared secret, headers, and request body
  string key = "<your-shared-secret>"; // This is the shared secret from OwnID Console
  byte[] keyBuffer = Convert.FromBase64String(key);
  var serializerOptions = new JsonSerializerOptions { Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping };
  string body = JsonSerializer.Serialize(ownIdRequest.Content, serializerOptions);
  string ownIdSignature = ownIdRequest.Headers.GetValues("OwnID-Signature").FirstOrDefault();
  string ownIdTimestamp = ownIdRequest.Headers.GetValues("OwnID-Timestamp").FirstOrDefault();
  string dataToSign = $"{body}.{ownIdTimestamp}";

  // Step 2: Validate the `OwnID-Timestamp` for expiration
  int expirationTimeInSeconds = 60; // Example expiration period of 1 minute
  long currentTimeInSeconds = DateTimeOffset.UtcNow.ToUnixTimeSeconds(); // Current time in seconds since epoch
  long timestamp = long.Parse(ownIdTimestamp);

  if (Math.Abs(currentTimeInSeconds - timestamp) > expirationTimeInSeconds)
  {
      // The timestamp has expired
      throw new SecurityException("Request rejected: Signature has expired.");
  }

  // Step 3: Generate HMAC signature
  byte[] dataToSignBytes = Encoding.UTF8.GetBytes(dataToSign);
  string signature;
  using (HMACSHA256 hmac = new HMACSHA256(keyBuffer))
  {
      signature = Convert.ToBase64String(hmac.ComputeHash(dataToSignBytes));
  }

  // Step 4: Compare the generated signature with the one from the header
  if (signature != ownIdSignature)
  {
      // The request has been tampered with
      throw new SecurityException("Request rejected: Invalid signature.");
  }
  ```

  ```java java theme={null}
  import javax.crypto.Mac;
  import javax.crypto.spec.SecretKeySpec;
  import javax.persistence.EntityNotFoundException;
  import javax.persistence.NoResultException;
  import java.nio.charset.StandardCharsets;
  import java.security.Key;
  import java.util.Base64;
  import java.util.Map;

  // Step 1: Extract shared secret, headers, and request body
  String key = "<your-shared-secret>"; // This is the shared secret from OwnID Console
  byte[] keyBuffer = Base64.getDecoder().decode(key);
  Key hashKey = new SecretKeySpec(keyBuffer, "HmacSHA256");
  String ownIdSignature = headers.get("ownid-signature");
  String ownIdTimestamp = headers.get("ownid-timestamp");
  String dataToSign = String.format("%s.%s", bodyJson, ownIdTimestamp);

  // Step 2: Validate the `ownid-timestamp` for expiration
  long expirationTimeInSeconds = 60; // Example expiration period of 1 minute
  long currentTimeInSeconds = System.currentTimeMillis() / 1000L; // Current time in seconds since epoch
  long timestamp = Long.parseLong(ownIdTimestamp);

  if (Math.abs(currentTimeInSeconds - timestamp) > expirationTimeInSeconds) {
      // The timestamp has expired
      throw new SecurityException("Request rejected: Signature has expired.");
  }

  // Step 3: Generate HMAC signature
  byte[] dataToSignBytes = dataToSign.getBytes(StandardCharsets.UTF_8);
  Mac mac = Mac.getInstance("HmacSHA256");
  mac.init(hashKey);
  byte[] signatureBytes = mac.doFinal(dataToSignBytes);
  String signature = Base64.getEncoder().encodeToString(signatureBytes);

  // Step 4: Compare the generated signature with the one from the header
  if (!signature.contentEquals(ownIdSignature)) {
      // The request has been tampered with
      throw new SecurityException("Request rejected: Invalid signature.");
  }
  ```
</CodeGroup>

## IP allowlisting

OwnID enforces IP allowlisting to make server-to-server calls to your servers. In order to allowlist OwnID calls, please consider the following IP addresses:

* 18.213.107.140
* 35.175.77.229

## Using Content-Security-Policy

When implementing [Content-Security-Policy](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy) response headers in your site, you must be sure to include `*.ownid.com` in the rule definitions for specific policies for them to function properly.

An example rule set would look similar to the following:

```html theme={null}
<meta http-equiv="content-security-policy" content="script-src 'unsafe-eval' 'self' *.ownid.com;">
```

## Important Next Steps

<Card title="Custom Domain" href="/explore/custom-domain">
  Unify the login experience with your own domain.
</Card>
