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

# Assess risk and verify location

> Assess device and network risk at login, registration, redemption, or payment, require a verified location check when the risk is elevated, and verify that a user is at a place or an address.

By the end of this guide, your app will run a device and network risk assessment at sensitive actions: a login, a registration, a promotion redemption, a payment, or a cashout. The assessment needs no location permission. Your backend will verify the signed result and read the risk level. When the level is anything other than `none` or `low`, or no assessment is available, your backend will require a verified location check before it authorizes the action.

To require a particular store, workplace, or address, see [Verify that the user is at a place or an address](#verify-that-the-user-is-at-a-place-or-an-address). If an action always requires the user to be in an allowed jurisdiction, as a wager does, see [Verify location for compliance](https://docs.radar.com/geo-compliance/verify-location.md).

## Complete example

This is the whole client flow for one withdrawal. `api` is your own backend client, which calls back on the main thread, and the `show` functions are your UI.

```swift Swift theme={null}
import CoreLocation
import RadarSDK

// At app launch
Radar.initialize(publishableKey: "prj_test_pk_...")

final class WithdrawalFlow: NSObject, CLLocationManagerDelegate {
  private var locationManager: CLLocationManager?
  private var transactionId = ""

  func withdraw(userId: String, amount: Int) {
    Radar.setUserId(userId)
    api.createWithdrawal(amount: amount) { transactionId in
      self.transactionId = transactionId

      Radar.revealRisk { status, risk in
        // A nil token tells your backend that the risk is unknown.
        let riskToken = status == .success ? risk?.token : nil
        api.sendRiskToken(riskToken, transactionId: transactionId) { result in
          if result.authorized { showDone() } else { self.requestLocation() }
        }
      }
    }
  }

  // Elevated or unknown risk: your backend asks for a verified location check.
  private func requestLocation() {
    // A new manager reports the current status to locationManagerDidChangeAuthorization.
    locationManager = CLLocationManager()
    locationManager?.delegate = self
  }

  func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) {
    switch manager.authorizationStatus {
    case .notDetermined: manager.requestWhenInUseAuthorization()
    case .authorizedWhenInUse, .authorizedAlways: verifyLocation()
    default: showLocationNeeded()
    }
  }

  private func verifyLocation() {
    locationManager = nil
    Radar.trackVerified(
      beacons: false,
      desiredAccuracy: .medium,
      reason: "withdrawal",
      transactionId: transactionId
    ) { status, token in
      guard status == .success, let jwt = token?.token else {
        // The check didn't complete. No token was issued.
        showTryAgain(status)
        return
      }
      api.sendGeolocationToken(jwt, transactionId: self.transactionId) { result in
        if result.authorized { showDone() } else { showFailed(result.failureReasons) }
      }
    }
  }
}
```

```kotlin Kotlin theme={null}
import android.Manifest
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import io.radar.sdk.Radar
import io.radar.sdk.RadarInitializeOptions
import io.radar.sdk.RadarTrackingOptions

// In Application.onCreate()
Radar.initialize(
  context = this,
  publishableKey = "prj_test_pk_...",
  options = RadarInitializeOptions(fraud = true)
)

class WithdrawalActivity : AppCompatActivity() {
  private var transactionId = ""

  private val locationPermission = registerForActivityResult(
    ActivityResultContracts.RequestMultiplePermissions()
  ) { grants ->
    if (grants.values.any { it }) verifyLocation() else showLocationNeeded()
  }

  fun withdraw(userId: String, amount: Int) {
    Radar.setUserId(userId)
    api.createWithdrawal(amount) { id ->
      transactionId = id

      Radar.revealRisk { status, risk ->
        // A null token tells your backend that the risk is unknown.
        val riskToken = if (status == Radar.RadarStatus.SUCCESS) risk?.token else null
        api.sendRiskToken(id, riskToken) { result ->
          if (result.authorized) showDone() else requestLocation()
        }
      }
    }
  }

  // Elevated or unknown risk: your backend asks for a verified location check.
  private fun requestLocation() {
    locationPermission.launch(
      arrayOf(
        Manifest.permission.ACCESS_FINE_LOCATION,
        Manifest.permission.ACCESS_COARSE_LOCATION
      )
    )
  }

  private fun verifyLocation() {
    Radar.trackVerified(
      beacons = false,
      desiredAccuracy = RadarTrackingOptions.RadarTrackingOptionsDesiredAccuracy.MEDIUM,
      reason = "withdrawal",
      transactionId = transactionId
    ) { status, token ->
      if (status != Radar.RadarStatus.SUCCESS || token == null) {
        // The check didn't complete. No token was issued.
        showTryAgain(status)
        return@trackVerified
      }
      api.sendGeolocationToken(transactionId, token.token) { result ->
        if (result.authorized) showDone() else showFailed(result.failureReasons)
      }
    }
  }
}
```

```javascript JavaScript theme={null}
import Radar from 'radar-sdk-js';
import { createFraudPlugin } from '@radarlabs/plugin-fraud';

// When the page loads
Radar.registerPlugin(createFraudPlugin());
Radar.initialize('prj_test_pk_...');

export async function withdraw(userId, amount) {
  Radar.setUserId(userId);
  const { transactionId } = await api.createWithdrawal(amount);

  let riskToken = null;
  try {
    riskToken = (await Radar.fraud.revealRisk()).token ?? null;
  } catch (err) {
    // The assessment didn't complete. Your backend treats the risk as unknown.
  }

  let result = await api.sendRiskToken(transactionId, riskToken);
  if (result.authorized) return showDone();

  // Elevated or unknown risk: your backend asks for a verified location check.
  // The browser shows its location prompt when the check runs.
  let geolocationToken;
  try {
    const check = await Radar.fraud.trackVerified({
      skipVerifyApp: true,
      reason: 'withdrawal',
      transactionId,
    });
    geolocationToken = check.token;
  } catch (err) {
    // The check didn't complete. No token was issued.
    return err.status === 'ERROR_PERMISSIONS' ? showLocationNeeded() : showTryAgain(err.status);
  }

  result = await api.sendGeolocationToken(transactionId, geolocationToken);
  return result.authorized ? showDone() : showFailed(result.failureReasons);
}
```

```javascript React Native theme={null}
import Radar from 'react-native-radar';

// At app launch. The second argument turns on fraud detection.
Radar.initialize('prj_test_pk_...', true);

export async function withdraw(userId, amount) {
  Radar.setUserId(userId);
  const { transactionId } = await api.createWithdrawal(amount);

  let riskToken = null;
  try {
    riskToken = (await Radar.revealRisk()).token?.token ?? null;
  } catch (err) {
    // The assessment didn't complete. Your backend treats the risk as unknown.
  }

  let result = await api.sendRiskToken(transactionId, riskToken);
  if (result.authorized) return showDone();

  // Elevated or unknown risk: your backend asks for a verified location check.
  const permission = await Radar.requestPermissions(false);
  if (permission !== 'GRANTED_FOREGROUND' && permission !== 'GRANTED_BACKGROUND') {
    return showLocationNeeded();
  }

  let geolocationToken;
  try {
    const check = await Radar.trackVerified({ reason: 'withdrawal', transactionId });
    geolocationToken = check.token?.token;
  } catch (err) {
    // The check didn't complete. No token was issued.
    return showTryAgain(err);
  }
  if (!geolocationToken) return showTryAgain(null);

  result = await api.sendGeolocationToken(transactionId, geolocationToken);
  return result.authorized ? showDone() : showFailed(result.failureReasons);
}
```

Your backend creates the transaction, verifies both tokens with your project's JWT secret key, and authorizes the withdrawal. `requireSession`, `transactions`, and `releaseWithdrawal` are your own session middleware, store, and downstream call.

```javascript Node.js theme={null}
import { randomUUID } from 'node:crypto';
import express from 'express';
import { jwtVerify } from 'jose';

const app = express();
app.use(express.json());

const secret = new TextEncoder().encode(process.env.RADAR_JWT_SECRET_KEY);

// Checks the signature and the expiry, and accepts HS256 only.
async function verifyRadarToken(token) {
  const { payload } = await jwtVerify(token ?? '', secret, { algorithms: ['HS256'] });
  return payload;
}

app.post('/api/withdrawals', requireSession, async (req, res) => {
  const transaction = await transactions.create({
    id: `txn-${randomUUID()}`,
    userId: req.session.userId,
    amount: req.body.amount,
    status: 'awaiting_risk',
    expiresAt: Date.now() + 10 * 60 * 1000,
  });
  res.status(201).json({ transactionId: transaction.id });
});

app.post('/api/withdrawals/:id/risk', requireSession, async (req, res) => {
  const transaction = await transactions.getOpen(req.params.id, req.session.userId, 'awaiting_risk');
  if (!transaction) return res.status(409).json({ authorized: false });

  let risk = null;
  try {
    const assessment = await verifyRadarToken(req.body.riskToken);
    // The token has no user ID. Record its jti against this transaction, once.
    if (await transactions.recordRiskAssessment(transaction.id, assessment.jti)) {
      risk = assessment.risk;
    }
  } catch (err) {
    // Missing, changed, or expired. The risk stays unknown.
  }

  if (risk?.level === 'none' || risk?.level === 'low') {
    if (await transactions.transition(transaction.id, 'awaiting_risk', 'authorized')) {
      await releaseWithdrawal(transaction.id);
    }
    return res.json({ authorized: true });
  }

  // Medium, high, or unknown risk: ask for a verified location check.
  await transactions.transition(transaction.id, 'awaiting_risk', 'awaiting_location');
  res.json({ authorized: false, locationRequired: true });
});

app.post('/api/withdrawals/:id/location', requireSession, async (req, res) => {
  const transaction = await transactions.getOpen(req.params.id, req.session.userId, 'awaiting_location');
  if (!transaction) return res.status(409).json({ authorized: false });

  let check;
  try {
    check = await verifyRadarToken(req.body.geolocationToken);
  } catch (err) {
    return res.status(400).json({ authorized: false, error: 'token_invalid' });
  }

  // The check must be for this user, this transaction, and this environment.
  const live = process.env.NODE_ENV !== 'production' || check.user?.live === true;
  if (check.user?.userId !== req.session.userId || check.transactionId !== transaction.id || !live) {
    return res.status(400).json({ authorized: false, error: 'token_mismatch' });
  }

  if (check.passed !== true) {
    return res.status(403).json({
      authorized: false,
      passed: false,
      failureReasons: check.failureReasons ?? [],
    });
  }

  if (await transactions.transition(transaction.id, 'awaiting_location', 'authorized')) {
    await releaseWithdrawal(transaction.id);
  }
  res.json({ authorized: true });
});
```

## Prerequisites

* The device and network risk assessment must be enabled for your project. Contact your Radar account team.
* The Radar SDK and fraud plugin for your platform. See [Fraud plugin setup](https://docs.radar.com/sdk/fraud.md). `Radar.revealRisk()` requires iOS SDK 3.38.0 or later, Android SDK 3.35.0 or later, `@radarlabs/plugin-fraud` 1.4.0 or later, or React Native SDK 4.36.0 or later.
* A Test publishable key in your app, and the project's JWT secret key on your backend only. See [Choose the right API key](https://docs.radar.com/fundamentals/authentication-and-access.md#choose-the-right-api-key).
* A stable, opaque ID for each account in your own system. Don't use an email address or a phone number.

## Create the transaction on your backend

For an action that your backend authorizes, such as a payment or a cashout, create the transaction before any Radar call, on an authenticated request, as the `POST /api/withdrawals` route does. Generate the transaction ID on your backend so your app can't choose it, and give the transaction a time limit that fits the action, 10 minutes in the example.

The transaction waits for a risk result (`awaiting_risk`), then either becomes `authorized` or waits for a location check (`awaiting_location`). The `transition` operation of your store must be a compare-and-set, so two concurrent requests can't both authorize.

A login, a registration, or a redemption has no transaction. Send the risk token with that request instead, as the [quickstart](https://docs.radar.com/fraud/overview.md#quickstart-assess-device-and-network-risk) does.

## Assess risk on the client

Call `Radar.revealRisk()` at the moment you want to assess, and send the signed `token` to your backend. The call doesn't request location permission and doesn't need a user ID, so it works before an account exists.

The token is optional in every SDK model. When the call fails or returns no token, still call your backend without one, so your backend records the risk as unknown.

Call `Radar.setUserId()` with your account ID after you authenticate the user, or as soon as your backend creates the account, and always before a verified location check. The `userId` is nullable. See [Handle login, logout, and user switching](https://docs.radar.com/fundamentals/authentication-and-access.md#handle-login-logout-and-user-switching).

## Verify the token and read the result on your backend

The risk token is a JSON Web Token signed with `HS256` and your project's JWT secret key. Verify the signature and the expiry before you read any field, and accept `HS256` only, as `verifyRadarToken` does.

> [!WARNING]
>
> Never act on a risk level or a `passed` value that your app sends outside a verified token. Never put a secret key in an app or web page.

The token carries no user ID. It is tied to the user and the transaction only because your backend received it on that user's authenticated request and recorded its `jti` claim, which equals the assessment `_id`, once. At registration, accept the token with the registration request, and store the assessment ID and `device.deviceId` with the account you create.

Then read `risk.level`, which is one of `none`, `low`, `medium`, or `high`, and `risk.reasons`, which lists the signals found. For every field, see [Read the result](https://docs.radar.com/fraud/overview.md#read-the-result).

The `/risk` route has the only branch in this guide: `none` or `low` authorizes the action, and anything else requires the verified location check. Unknown risk, from a missing, invalid, expired, or reused token, takes the location path, because unknown risk isn't low risk.

A risk level isn't a probability of fraud, and which levels need the location check is your choice for each action. See [Understand risk scores and decisions](https://docs.radar.com/fraud/overview.md#understand-risk-scores-and-decisions).

## Read the fields for your scenario

Each scenario runs the same assessment at a different moment.

| Scenario | When to call | What to read |
| - | - | - |
| Login (account takeover) | After you verify credentials. | `risk.level`, `risk.reasons`, `network.privacy`, and whether `device.deviceId` is one you stored for this user. |
| Sensitive account action | Before a change of email, password, phone number, or payout details. | `risk.level`, `risk.reasons`, and the `device.deviceId` values you stored for this user. |
| Registration (new account fraud and multi-accounting) | When the user submits the registration form, before you create the account. | `risk.level`, `risk.reasons`, `network.privacy`, and `device.deviceId` against your earlier registrations. |
| Promotion redemption (promo abuse) | Before your backend grants the promotion. | `risk.level`, `risk.reasons`, and `device.deviceId` against earlier redemptions of the same promotion. |
| Payment or cashout | After your backend creates the transaction and before it authorizes the action. | `risk.level`. |

On `medium` or `high`, an app typically asks for another authentication factor at login, asks for phone or document verification at registration, or holds a redemption for review.

A new device, several users on one device, or a shared network is context, not proof, so don't block on one of these alone.

Compare `device.deviceId` values only with other values from risk assessments. Signals that depend on the user ID or on location, such as `user.fraud.usersForThisDevice` and `user.fraud.mocked`, come only from a verified location check. When an outcome is confirmed, record it as a label with the [Labels API](https://docs.radar.com/api/labels.md).

## Request the verified location check

Ask for location permission only at this step. Tell the user why you need their location for this action, then request foreground location permission, as each tab of the complete example does. See [Understand foreground and background location permissions](https://docs.radar.com/fundamentals/location-permissions.md). Granting permission isn't verification.

Call `Radar.trackVerified()` with the transaction ID from your backend as `transactionId`, and a `reason` from a small, fixed set, such as `withdrawal`. Radar returns both in the token and shows the reason in the Radar dashboard. Keep the same `transactionId` for every retry of the same transaction. On the web, pass `skipVerifyApp: true`, which runs the check in the browser without the Radar Verify companion app.

The check returns a signed geolocation token whether it passed or failed. Send it to your backend either way. When the check returns an error status, there is no token, and nothing was verified.

## Validate the token and authorize once

The geolocation token is signed with the same key as the risk token. The `/location` route verifies its signature, algorithm, and expiry, and then checks, in order:

1. `user.userId` is the session user, and `transactionId` is this transaction.
2. In production, `user.live` is `true`.
3. `passed` is `true`. Otherwise it responds with `failureReasons` and leaves the transaction in `awaiting_location`.

Only then does it move the transaction to `authorized`, with a compare-and-set, and call your downstream system. For the full procedure, see [Validate a token](https://docs.radar.com/api/geolocation-tokens.md#validate-a-token). If your project uses [encrypted responses](https://docs.radar.com/api/geolocation-tokens.md#encrypted-responses), decrypt the token before you verify it.

## Verify that the user is at a place or an address

`passed` covers the fraud checks and your allowed countries and states. It doesn't say the user is at a particular store, workplace, or address. For an action tied to a location, such as a clock-in, an in-store redemption, or a delivery handoff, your backend reads `passed` first, then checks the place or the address in the verified payload. The required location comes from your own records, never from the request body.

* **A place**: Create one geofence for each store, workplace, or service location, each with an `externalId` that matches the ID in your own system, such as `store-42`. See [Detect geofence events and place visits](https://docs.radar.com/geofencing/geofences-and-places.md). A geofence doesn't change `passed`. Radar reports the geofences the user is in as `user.geofences`. Location accuracy indoors varies, so a boundary drawn tightly around a building can exclude users who are inside it.
* **An address**: Call `Radar.setExpectedAddress()` with the address from your backend's records before the check. Radar geocodes the address and returns the comparison in `user.expectedAddress`: `atAddress` is `true` when the location is within the distance threshold of the address, 60 meters by default, and `confidence` is `high`, `medium`, `low`, or `unknown`. When the user isn't at the address, the token carries the warning `address_not_expected`, and `passed` can still be `true`. See [Expected address fields](https://docs.radar.com/api/geolocation-tokens.md#expected-address-fields).

> [!NOTE]
>
> Address verification must be enabled for your project. Contact your Radar account team.

```swift Swift theme={null}
Radar.setExpectedAddress("123 Example St, New York, NY 10001")
```

```kotlin Kotlin theme={null}
Radar.setExpectedAddress("123 Example St, New York, NY 10001")
```

```javascript JavaScript theme={null}
Radar.fraud.setExpectedAddress('123 Example St, New York, NY 10001');
```

The SDK sends the address with each later check until you clear it. Pass `nil` in Swift or `null` in Kotlin, or call `Radar.fraud.setExpectedAddress()` with no argument on web, when the workflow ends.

After your backend reads `passed`, these functions check each condition against the verified payload:

```javascript Node.js theme={null}
function isInsideGeofence(payload, externalId) {
  const geofences = payload.user.geofences ?? [];
  return geofences.some((geofence) => geofence.externalId === externalId);
}

function isAtExpectedAddress(payload, addressOnFile) {
  const result = payload.user.expectedAddress;
  // The check must have compared against the address in your records.
  if (!result || result.expectedAddress !== addressOnFile) return false;
  // Choose which confidence levels your workflow accepts.
  const confident = result.confidence === 'high' || result.confidence === 'medium';
  return result.atAddress === true && confident;
}
```

A user who is outside the store still gets a token with `passed` set to `true` when nothing is wrong with the device or the region, so a backend that reads only `passed` would accept the action. Reject the action, and tell the user where they need to be.

## Handle results and errors

No row authorizes the action on the client.

| Result or error | What it means | What to do |
| - | - | - |
| `risk.level` is `none` or `low` | Radar found no signals, or weak ones. | Continue. |
| `risk.level` is `medium` or `high` | Radar found more, or stronger, signals. `risk.reasons` says which. | Require the verified location check, or the follow-up you chose for this scenario. |
| No valid risk token | The assessment failed, or the token is invalid, expired, or already used. | Require the verified location check. |
| Permission denied | The user declined the prompt, or the check returned `ERROR_PERMISSIONS`. | Explain why location is needed and how to turn it on in settings. |
| Location unavailable or technical error | The check returned `ERROR_LOCATION`, `ERROR_NETWORK`, `ERROR_SERVER`, or another error status, and no token. It isn't a failed check. | Ask the user to turn on location services and Wi-Fi, check the connection, and try again. |
| Token expired, or for another user or transaction | `exp` has passed, or `user.userId` or `transactionId` doesn't match. | Respond with `400`. Your app sets the correct user ID and runs a new check. |
| Failed check | A verified token with `passed` set to `false`. | Respond with `403` and `failureReasons`. Let the user fix the cause, such as disconnecting a VPN, before a new check. |
| A reason you don't recognize | Some reasons aren't published. | Record it without failing. |

## Test the integration

Run these in the Test environment with a Test publishable key.

* **Passing case**: Run the flow on a device with location permission granted. Confirm that your backend responds with `authorized` set to `true`. Send the same passing token again, and confirm a `409`.
* **Failing case**: Call the risk route with no token, and confirm that `locationRequired` is `true`. Then block your test user with a block rule and run the check. Confirm a `403` with `passed` set to `false` and `fraud_blocked_user_id` in `failureReasons`.

To create and remove the block rule, see [Force a pass or a fail](https://docs.radar.com/fundamentals/testing-and-launch.md#force-a-pass-or-a-fail).

## Production checklist

* [ ] Your backend creates the transaction ID.
* [ ] Both tokens are verified on your backend with the JWT secret key and an explicit `HS256` allowlist.
* [ ] A missing, invalid, or expired risk token leads to the verified location check, not to direct authorization.
* [ ] The risk token's `jti` is recorded once, and the geolocation token is bound to the authenticated user and to the transaction ID.
* [ ] The transaction is authorized at most once, with an atomic state change, and never from a client-side value.
* [ ] Production builds use a Live publishable key, and your backend rejects tokens with `user.live` set to `false`.

## Build with an agent

Copy this prompt into a coding agent that has access to your repository.

```text theme={null}
Add a Radar risk assessment and a risk-triggered verified location check to one
sensitive action in this repository. Ask me which action if it isn't obvious.
Read https://docs.radar.com/fraud/assess-risk.md, then
https://docs.radar.com/sdk/fraud.md and
https://docs.radar.com/api/geolocation-tokens.md.
Client: call Radar.revealRisk() and send the token, or no token on failure.
Backend: create the transaction, verify the risk token (HS256 only, project JWT
secret key, expiry), record its jti once, and authorize on risk.level none or
low. Otherwise require a geolocation token for this user and transactionId with
passed true. Authorize only on the backend, at most once. No secrets in clients.
Add backend tests: low risk authorizes, high or missing risk requires location,
a failed check and a token for another user or transaction don't authorize.
```

## See also

* [Fraud overview and quickstart](https://docs.radar.com/fraud/overview.md)
* [Fraud plugin setup](https://docs.radar.com/sdk/fraud.md)
* [Geolocation token schema](https://docs.radar.com/api/geolocation-tokens.md)
* [Fraud API](https://docs.radar.com/api/fraud.md)
* [Verify location for compliance](https://docs.radar.com/geo-compliance/verify-location.md)
* [Test, troubleshoot, and go live](https://docs.radar.com/fundamentals/testing-and-launch.md)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.