Skip to content

Integrate Castle

Add bot detection and fraud prevention to your app in 8 steps.

Add Castle to your registration and login flows. By the end, you’ll block bots and suspicious users automatically.

Before you start#

Integrating Castle with your app consists of a few steps, but before you start make sure you have:

Your app is a “frontend” and a “backend”

In this guide you can see terms “frontend” and “backend” that describe the two parts of your app:

  1. “frontend” is the user-facing part, for example: a React or a Vue app, an iOS or an Android app, or just a regular view from your framework of choice,
  2. “backend” is the API, for example: a controller in your framework of choice, or a data API you use to power your mobile app.

To fully complete this quickstart guide you need to integrate both: the frontend and the backend. It is the best to have both running locally on your machine, but you can also split the work between two teams that take care of those parts of your business.

How Castle fits into your app#

Castle adds two things to your existing flows:

  1. Frontend: Collect a device fingerprint (request token)
  2. Backend: Call Castle’s API before processing the action

Castle returns allow, challenge, or deny based on your Policies. You decide what happens.

Account creation flow. In blue - Castle integration
Account creation flow with Castle integration (blue)

Which API should I use?

  • Filter API → Anonymous users (before login/registration succeeds)
  • Risk API → Authenticated users (after login succeeds)

Integration steps#

Tip:

Create a feature flag so you can gradually roll out Castle to your users.

Step 1: Get your API keys#

Go to Environment Settings → API Keys in the Castle Dashboard.

You’ll find your Publishable API Key and API Secret there. You will need both in the next steps.

Step 2: Integrate frontend SDK#

Do you want to integrate a mobile app?

This guide covers using the Browser SDK. If you are interested in integrating your mobile app please take a look at Mobile SDKs page for integration instructions and come back for the backend integration step.

2.1: Install the Browser SDK#

Open Getting started → Full integration in the Castle Dashboard and follow the steps there to install the Browser SDK.

2.2: Configure it#

JavaScript
import Castle from '@castleio/castle-js'

const castle = Castle.configure({ pk: '<YOUR_PUBLISHABLE_API_KEY>' });

Initialize the SDK everywhere, as early as possible

The browser SDK should be initialized immediately at page load, and we recommend that you put it on all your pages. Thanks to that enough behavioral metrics can be collected - they improve accuracy, especially for bot detection.

Step 3: Integrate backend SDK#

3.1: Install the SDK#

gem install 'castle-rb'

3.2: Configure it#

  1. Export your API Secret in CASTLE_API_SECRET environment variable.
  2. Configure the SDK:
# config/castle.rb
require 'castle'

Castle.configure do |config|
  config.api_secret = ENV.fetch('CASTLE_API_SECRET')
end

Server SDKs configuration options

Here’s a list of all supported server SDKs along with their configuration options: Server SDKs

Step 4: Handle the registration flow#

Now comes an actual integration of a real flow in your app: the registration.

4.1: Update your registration form#

  1. Add a hidden field that will store a request token:
HTML
<form id="registration-form" action="/register" method="post">
  <input type="hidden" name="castle_request_token" id="castle-request-token" />
  <!-- Your other fields like username and password -->
</form>

What is a request token?

The request token that is generated by Castle’s frontend SDK is an anonymous device fingerprint used to properly understand your users’ behaviors. The token also contains required meta-data that allow you to understand and block bad behavior.

  1. Intercept the submit event and generate the request token:
JavaScript
const form = document.getElementById('registration-form');
const castleField = document.getElementById('castle-request-token');

form.addEventListener('submit', function (event) {
  event.preventDefault();
  castle.createRequestToken().then(function (token) {
    castleField.value = token;
    form.submit();
  });

  return false;
});

Request token value has to be generated for each request to your backend

Each request token expires after 120 seconds and should only be used during a single request to your backend. Castle.js continuously monitors behavior of the user, thus the data need to be refreshed every time you call your backend to get the most accurate predictions.

4.2: Call Castle Filter API in the backend#

Before you proceed with creating an account or even checking for its existence you need to call Castle’s Filter API to process the request and receive a recommended action to perform:

# app.rb
require 'sinatra'
require_relative 'config/castle.rb'

castle = ::Castle::Client.new

post '/register' do
  begin
    result = castle.filter(
      request_token: request.params['castle_request_token'],
      context: ::Castle::Context::Prepare.call(request),
      type: '$registration',
      status: '$attempted',
      params: {
        email: request.params['email'], # This is optional, but will highly improve accuracy
      }
    )
    
    # Handle "deny" actions
    if result[:policy][:action] == 'deny'
      return [400, 'Cannot create an account right now, please try again later']
    end
  rescue ::Castle::InvalidRequestTokenError
    # Invalid request token is very likely a bad actor bypassing fingerprinting
    return [400, 'Cannot create an account right now, please try again later']
  rescue ::Castle::Error => e
    # Allow the attempt - most likely a server or timeout error
  end
  
  # Your code: check for existence and create user profile
  user = create_user(request)
  return [200, 'Welcome to the app! You can log in now.']
end

The Filter API

The Filter API is meant for checking the behavior of anonymous users when they act in your app. For example: they attempt a registration, they try to log in, or send a contact form message to you.

On every call to the Filter API Castle does a full behavioral check: inspect signals, calculate custom metrics and run your policies to return you a recommended action along with the scores for account abuse, account takeover, and bot detection.

Step 5: Create a policy for registration#

By default all calls to Castle API’s returns an “allow” action to avoid any disruptions to your business. To start blocking bots you need to create a policy that will return a deny action:

  1. Go to the Castle Dashboard, open Policies page, and click Create new policy button:
Policies view
Policies view
  1. Fill in the policy details:
New policy against bots
New policy against bots registering new accounts

Recommended bot score

As an initial policy we recommend using 90+ bot score as a good balance to block bots, but allow legitimate users create an account. You can easily tweak it later as you see real behavior in your dashboard.

Risk scoring

Castle uses machine learning models to calculate risk scores as measures of how likely a user action will result in abuse. Castle’s APIs return a numerical risk score between 0.0 and 1.0, represented as 0–100 in the dashboard. Low-risk events are scored at or near zero, and high-risk events are scored at or near one.

Castle calculates risk scores for three types of abuse, designed to cover most fraud and abuse problems when used in combination with business-specific policies:

  • Account Abuse Score - is the probability of a user trying to abuse your service, for example: fake accounts, multi-accounting, or account sharing.
  • Account Takeover Score - the risk that an account is accessed through stolen credentials, for example: through human account takeovers or automated credential stuffing attacks.
  • Bot Score - a request performed by an automated script in order to spam or consume resources.

You can learn more about risk scoring in the Risk scoring docs page.

Learn more about policies

Check out Castle’s policies guide to learn more how you can leverage policies, for example:

Step 6: Handle the login flow#

Let’s handle another important flow in your app: the login process.

6.1: Update your login form#

  1. Add a hidden field that will store a request token:
HTML
<form id="login-form" action="/login" method="post">
  <input type="hidden" name="castle_request_token" id="castle-request-token" />
  <!-- Your other fields like username and password -->
</form>
  1. Intercept the submit event and generate the request token:
JavaScript
const form = document.getElementById('login-form');
const castleField = document.getElementById('castle-request-token');

form.addEventListener('submit', function (event) {
  event.preventDefault();
  castle.createRequestToken().then(function (token) {
    castleField.value = token;
    form.submit();
  });

  return false;
});

Generating request tokens

As you see, generating request tokens is the same for both register and login actions. You can reuse the same pattern in other forms and actions you want to secure, for example when you are protecting transactions.

6.2: Call Castle’s Risk API upon successful login#

# app.rb
require 'sinatra'
require_relative 'config/castle.rb'

castle = ::Castle::Client.new

post '/login' do
  # Your code: check for existence and login the user
  user = login_user(request)
  
  # Successful login: Castle Risk API call
  begin
    result = castle.risk(
      request_token: request.params['castle_request_token'],
      context: ::Castle::Context::Prepare.call(request),
      type: '$login',
      status: '$succeeded',
      user: {
        id: user.id.to_s,
      }
    )
    
    # Handle "deny" responses
    if result[:policy][:action] == 'deny'
      return [400, 'Invalid username and/or password']
    end
  rescue ::Castle::InvalidRequestTokenError
    # Invalid request token is very likely a bad actor bypassing fingerprinting
    return [400, 'Invalid username and/or password']
  rescue ::Castle::Error => e
    # Allow the attempt - most likely a server or timeout error
  end
  
  return [200, { 'Set-Cookie': user.cookie }, 'Welcome to the app!']
end

The Risk API

The Risk API is meant for checking an authenticated user’s activity. For example: they logged in successfully (as in this guide), they updated their profile, or they act on your business action.

The biggest difference between the Risk API and the Filter API is the former is used for checking a user that has successfully logged in (so you measure risk of their actions in your app), whereas the latter is used to check visitors, before they log in (so you filter out abusive behavior).

6.3: Call Castle’s Filter API upon failed login#

# app.rb
require 'sinatra'
require_relative 'config/castle.rb'

castle = ::Castle::Client.new

post '/login' do
  # Your code: check for existence and login the user
  user = login_user(request)
  
  # Successful login: Castle Risk API call
  begin
    # ... clipped for brevity ...
  end
  
  return [200, { 'Set-Cookie': user.cookie }, 'Welcome to the app!']
rescue InvalidPasswordError
  # Invalid login: call Castle Filter API to help prevent Account Takeover
  begin
    castle.filter(
      request_token: request.params['castle_request_token'],
      context: ::Castle::Context::Prepare.call(request),
      type: '$login',
      status: '$failed',
      params: {
        email: request.params['email'], # This is optional, but will highly improve accuracy
      }
    )
  rescue ::Castle::Error
    # Catch all Castle errors here: the user used invalid password, so block them anyway
  end
  
  return [400, 'Invalid username and/or password']
end

Making multiple calls to Castle APIs

You should reuse the request token for multiple calls to Castle APIs within a single call to your backend. It must represent a single action in your app though.

For example: call Filter API with $login $attempted to get initial scoring (to filter out abusive IPs from even trying to log in), then call Risk API with $login $succeeded (to assess risk of account takeover) using the same request token.

Step 7: Create a policy for logging in#

7.1: Block bots logging in#

  1. Go to the policies page in Castle’s Dashboard and click Create new policy button.
  2. Fill in the policy details:
New policy against bots logging in
New policy against bots logging in

7.2: Challenge suspicious users (optional)#

When to challenge your users?

Asking users to prove they have legitimate interest in your business is, well, challenging. Sometimes their behavior on your page look very similar to bots (they try to imitate human behavior as much as they can). As a result Castle returns a higher risk score for bots, where a good option might be to present an additional challenge to the user, for example: a 2FA requirement, or an email sent with verification code.

  1. Handle the challenge response in your backend:
# app.rb
require 'sinatra'
require_relative 'config/castle.rb'

castle = ::Castle::Client.new

post '/login' do
  # Your code: check for existence and login the user
  user = login_user(request)
  
  # Successful login: Castle Risk API call
  begin
    result = castle.risk(
      request_token: request.params['castle_request_token'],
      context: ::Castle::Context::Prepare.call(request),
      type: '$login',
      status: '$succeeded',
      user: {
        id: user.id.to_s,
      }
    )
    
    # Handle "deny" responses
    if result[:policy][:action] == 'deny'
      return [400, 'Invalid username and/or password']
    # Handle "challenge" responses
    elsif result[:policy][:action] == 'challenge'
      # Tell your frontend to handle a challenge before you actually log in the user
      return [200, 'challenge']
    end
  rescue ::Castle::InvalidRequestTokenError
    # Invalid request token is very likely a bad actor bypassing fingerprinting
    return [400, 'Invalid username and/or password']
  rescue ::Castle::Error => e
    # Allow the attempt - most likely a server or timeout error
  end
  
  return [200, { 'Set-Cookie': user.cookie }, 'Welcome to the app!']
rescue InvalidPasswordError
  # ... clipped for brevity ...
end
  1. Update handling of your login requests and challenge the user:
JavaScript
const form = document.getElementById('login-form');

// Call /login handler asynchronously using Fetch API
form.addEventListener('submit', function (event) {
  event.preventDefault();
  const data = new FormData(event.currentTarget);
  
  const submit = async () => {
    const token = await castle.createRequestToken();
    data.set('castle_request_token', token);
    
    const response = await fetch(form.getAttr('action'), {
      method: form.getAttr('method'),
      body: data,
    });
    const result = await response.text();
  
    if (result === 'challenge') {
      // A simplified challenge as an example, do NOT use in production
      if (!confirm('Are you a bot?')) {
        // The challenge succeeded
        data.set('challenge', 'true');
        submit();
        return;
      }
      
      alert('You are denied the access');
    }
    
    alert('You are logged in!');
  };
  
  submit();
  
  return false;
});
  1. Go to the policies page in Castle’s Dashboard and click Create new policy button.
  2. Fill in the policy details:
New policy challenging suspicious users
New policy challenging suspicious users

What is a good challenge?

It is important to properly design your challenges: they should be easy for a human, but hard for bots. How can you achieve such balance? It is best to tap into different accounts a user might have, for example:

  • Send a code to their email address (assuming their email account hasn’t been breached),
  • Ask for a phone number and send an SMS code (in most countries a number is registered to a real person),
  • Ask to confirm logging in with an additional social account login.

We recommend thinking on a challenge that is very natural for your customers, but is hard to do for an automated attack you want to prevent.

Step 8: Test, then activate your policies#

As you went through the whole integration process you might have noticed that policies you created are disabled by default. It is a deliberate behavior as it allows you to integrate your app with Castle, but keep learning as the first phase.

After a few days you should open the Dashboard and check how the policies you defined would have acted on your customers. The easiest way to do this is:

  1. Open the policies page in Castle’s Dashboard.
  2. Click a search icon near the policy you are interested in:
Policies view with disabled policies
Policies view with disabled policies
  1. Check events and users that you sent to Castle that would have been blocked or challenged (depending on the policy action you selected):
Policy events view
Policy events view
  1. When you feel that your policies are good - enable them:
Policies view with enabled and disabled items in the list
Policies view with enabled and disabled items in the list
  1. You might start seeing “Deny” responses in your Explore view:

What’s next#

You’re integrated! Events should appear in your Castle Dashboard within seconds.

Next steps:

  • Roll out gradually using your feature flag
  • Monitor the Dashboard to see blocked bots and suspicious behavior
  • Adjust policy thresholds based on real data
  • Learn to explore your data to fine-tune policies