Skip to content

castle/castle-dotnet

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

65 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

.NET SDK for Castle

Build status NuGet Coverage Status

Supporting .NET 8.0 and .NET Standard 2.1. Refer to Microsoft's documentation for compatibility information.

Castle analyzes user behavior in web and mobile apps to stop fraud before it happens.

Usage

See the documentation for how to use this SDK with the Castle APIs.

Installation

Install the Castle.Sdk NuGet package.

.NET CLI

dotnet add package Castle.Sdk

Package Manager Console

Install-Package Castle.Sdk

Visual Studio

  1. Go to Tools -> Package Manager -> Manage NuGet Packages for Solution...
  2. Click the Browse tab and search for Castle.Sdk
  3. Click the Castle.Sdk package in the search results, select version and what projects to apply it to on the right side, and click Install

Configuration

Go to the settings page of your Castle account and find your API Secret. Use it to create a new instance of the CastleClient class.

var client = new CastleClient(new CastleConfiguration("YOUR SECRET"));

It's a good idea to set up your CastleClient instance using an IoC container.

ASP.NET Core

public void ConfigureServices(IServiceCollection services)
{
    services.AddSingleton(new CastleClient(new CastleConfiguration("YOUR SECRET")));
}

The CastleConfiguration object has a number of properties that control the SDK.

Property Default Description
ApiSecret Secret used to authenticate with the Castle Api. Required
FailOverStrategy Allow The response action to return in case of a failover in an Authenticate request.
Timeout 1000 Timeout for requests, in milliseconds.
BaseUrl https://api.castle.io Base Castle Api url.
LogLevel Error The log level applied by the injected ICastleLogger implementation.
AllowList List of headers that should be passed intact to the API. A list of recommended headers can be retrieved from the static property Castle.Headers.AllowList in the SDK.
DenyList List of headers that should not be passed intact to the API.
DoNotTrack false If true, no requests are actually sent to the Castle Api, and Authenticate returns a failover response.
Logger Your own logger implementation.
IpHeaders IP Headers to look for a client IP address.
TrustedProxies Trusted public proxies list.
TrustedProxyDepth 0 Number of trusted proxies used in the chain.
TrustProxyChain false Is trusting all of the proxy IPs in X-Forwarded-For enabled.

API Actions

All API action methods accept an ActionRequest object and are async.

Risk

var response = await client.Risk(new ActionRequest()
{
    Event = "$login",
    Status = "$succeeded",
    UserId = "user-123",
    RequestToken = "token-from-castle-js",
    Context = Castle.Context.FromHttpRequest(Request)
});

// response.Risk       - risk score (float)
// response.Policy     - policy evaluation result
// response.Signals    - signal details
// response.Device     - device information

Filter

var response = await client.Filter(new ActionRequest()
{
    Event = "$registration",
    Status = "$attempted",
    UserId = "user-123",
    RequestToken = "token-from-castle-js",
    Context = Castle.Context.FromHttpRequest(Request)
});

Log

await client.Log(new ActionRequest()
{
    Event = "$profile_update",
    UserId = "user-123",
    Context = Castle.Context.FromHttpRequest(Request)
});

Advanced: Build and Send

Each action supports a two-step pattern where you build the JSON request, optionally modify it, and then send it separately.

var jsonRequest = client.BuildRiskRequest(new ActionRequest()
{
    Event = "$login",
    UserId = "user-123",
    Context = Castle.Context.FromHttpRequest(Request)
});

// Inspect or modify jsonRequest (JObject) if needed

var response = await client.SendRiskRequest(jsonRequest);

This pattern is available for all actions: BuildRiskRequest / SendRiskRequest, BuildFilterRequest / SendFilterRequest, BuildLogRequest / SendLogRequest.

Request Context

Use Castle.Context.FromHttpRequest() to extract client context (IP, headers, client ID) from the current HTTP request.

ASP.NET Core

public class IndexModel : PageModel
{
    public void OnGet()
    {
        var actionRequest = new ActionRequest()
        {
            Context = Castle.Context.FromHttpRequest(Request),
            Event = "$login",
            UserId = "user-123"
        };
    }
}

Logging

The SDK allows customized logging by way of implementing the ICastleLogger interface and passing in an instance as part of the CastleConfiguration. Exactly what gets logged can be controlled by setting the LogLevel property of CastleConfiguration.

var client = new CastleClient(new CastleConfiguration("secret") {
    Logger = new MyLogger()
});

Logger example

public class DebugLogger : ICastleLogger
{
    public void Info(string message)
    {
        Debug.WriteLine($"INFO: {message}");
    }

    public void Warn(string message)
    {
        Debug.WriteLine($"WARNING: {message}");
    }

    public void Error(string message)
    {
        Debug.WriteLine($"ERROR: {message}");
    }
}

Demo application

There is a sample application using ASP.NET Core Razor Pages and this SDK here.

About

C# / .NET bindings for Castle

Topics

Resources

License

Stars

Watchers

Forks

Packages

 
 
 

Contributors