SDK Guide
Here you can find all the information that you need to get started using SecureNative SDK:
Installation
npm install @securenative/sdk
// When using Maven, add the following dependency to your `pom.xml` file:
<dependency>
<groupId>com.securenative.java</groupId>
<artifactId>securenative-java</artifactId>
<version>LATEST</version>
</dependency>
// Gradle:
// compile group: 'com.securenative.java', name: 'sdk-base', version: 'LATEST'
pip install securenative
Install the `SecureNative.Sdk` nuget.
//Command line:
nuget install SecureNative.Sdk
//Packet Manager Console
install-package SecureNative.Sdk
//Visual Studio
1. Go to Tools -> Package Manager -> Manage NuGet Packages for Solution...
2. Click the Browse tab and search for `SecureNative.Sdk`
3. Click the `SecureNative.Sdk` package in the search results, select version and what projects to apply it to on the right side, and click Install
# Add this line to your application's Gemfile:
gem 'securenative'
# And then execute:
$ bundle install
# Or install it yourself as:
$ gem install securenative
$ composer require securenative/securenative-php
$ go get github.com/securenative/securenative-go
Initialize the SDK
Go to the settings page of your SecureNative account and find your API KEY
Initialize using API KEY
import { SecureNative, EventTypes } from "@securenative/sdk";
// or
const { SecureNative, EventTypes } = require("@securenative/sdk"); // if your using ES5
// Options 1: Use default config file path
try {
SecureNative securenative = SecureNative.init();
} catch (SecureNativeSDKException | SecureNativeConfigException e) {
e.printStackTrace();
}
// Options 2: Use specific config file path
Path path = Paths.get("/path/to/securenative.properties");
try {
SecureNative.init(path);
} catch (SecureNativeSDKException | SecureNativeConfigException e) {
System.err.printf("Could not initialize SecureNative sdk; %s%n", e);
}
// Option 3: Initialize via API Key
try {
SecureNative securenative = SecureNative.init("YOUR_API_KEY");
} catch (SecureNativeSDKException | SecureNativeConfigException e) {
e.printStackTrace();
}
from securenative.securenative import SecureNative
# Option 1: Initialize via Config file
# SecureNative can automatically load your config from securenative.properties file or from the file that is specified in your SECURENATIVE_CONFIG_FILE env variable:
secureative = SecureNative.init()
# Option 2: Initialize via API Key
securenative = SecureNative.init("YOUR_API_KEY")
using SecureNative.SDK;
# Option 1: Initialize via Config file
# SecureNative can automatically load your config from securenative.json file or from the file that is specified in your SECURENATIVE_CONFIG_FILE env variable:
var securenative = Client.Init();
# Option 2: Initialize via API Key
var securenative = Client.Init("YOUR_API_KEY");
require 'securenative'
secureative = SecureNative::Client.init
Option 2: Initialize via API Key
require 'securenative'
securenative = SecureNative::Client.init_with_api_key('YOUR_API_KEY')
require_once __DIR__ . '/vendor/autoload.php';
use SecureNative\sdk\SecureNative;
use SecureNative\sdk\SecureNativeOptions;
use SecureNative\sdk\EventTypes;
use SecureNative\sdk\SecureNativeContext;
// Option 1: Initialize via Config file
// SecureNative can automatically load your config from securenative.yml file or from the file that is specified in your SECURENATIVE_CONFIG_FILE env variable:
package main
import (
"github.com/securenative/securenative-go/sdk"
"log"
)
func main() {
sn, err := sdk.InitSDK(sdk.WithConfigFile("path/to/securenative.yml"))
if err != nil || sn == nil {
log.Fatal("Do some error handling")
}
defer sn.Stop()
}
// Option 2: Initialize via API Key
package main
import (
"github.com/securenative/securenative-go/sdk"
"log"
)
func main() {
sn, err := sdk.InitSDK(sdk.WithApiKey("YOUR_API_KEY"))
if err != nil {
log.Fatal("Do some error handling")
}
defer sn.Stop()
}
Configuration
You can pass empty SecureNativeOptions object or you can set the following:
Option | Type | Optional | Default Value | Description |
---|---|---|---|---|
apiKey | string | false | none | SecureNative API_KEY |
apiUrl | string | true | https://api.sec... | Default API base address |
autoSend | boolean | true | true | Should SDK auto send the events |
failoverStrategy | string | true | fail-open | Specify which score to return when API is unavailable. "fail-open" return { riskLevel: 'low', score: 0 } ."fail-close" return { riskLevel: 'high', score: 1 } |
disable | boolean | true | false | Should be SDK disabled, no API call would be called or executed |
interval | number | true | 1000 | Interval for SDK to try to persist events |
logLevel | string | true | fatal | From which log level should print logs debug/info/warn/error/fatal |
maxEvents | number | true | 1000 | Max in-memory events queue |
timeout | number | true | 1500 | API call timeout in ms |
// will initialize singleton instance
SecureNative.init({ apiKey: "Your API_KEY", maxEvents: 10, logLevel: "error" });
// get singleton instance
const securenative = SecureNative.getInstance();
try {
securenative = SecureNative.init(SecureNative.configBuilder()
.withApiKey("API_KEY")
.withMaxEvents(10)
.withLogLevel("error")
.build());
} catch (SecureNativeSDKException e) {
e.printStackTrace();
}
from securenative.securenative import SecureNative
from securenative.config.securenative_options import SecureNativeOptions
options = SecureNativeOptions(api_key="YOUR_API_KEY", max_events=10, log_level="ERROR")
securenative = SecureNative.init_with_options(options)
using SecureNative.SDK;
var options = ConfigurationManager.ConfigBuilder()
.WithApiKey("API_KEY"))
.WithMaxEvents(10)
.WithLogLevel("error")
.Build());
var securenative = Client.Init(options);
require 'securenative'
options = SecureNative::Config::ConfigurationBuilder.new(api_key: 'API_KEY', max_events: 10, log_level: 'ERROR')
SecureNative::Client.init_with_options(options)
$options = new SecureNativeOptions();
$options->setTimeout(3000)
->setDisable(false)
->setInterval(1000)
->setAutoSend(true)
->setMaxEvents(10)
->setLogLevel('fatal');
// Passing `$options` is optional, will use default params
SecureNative::init("[API_KEY]", $options);
package main
import (
"github.com/securenative/securenative-go/config"
"github.com/securenative/securenative-go/sdk"
"log"
)
func main() {
configBuilder := config.NewConfigurationBuilder()
sn, err := sdk.InitSDK(configBuilder.WithApiKey("API_KEY").WithMaxEvents(10).WithLogLevel("ERROR").Build())
if err != nil {
log.Fatal("Do some error handling")
}
defer sn.Stop()
}
Tracking events
Track Object Properties
Option | Type | Required | Example | Description |
---|---|---|---|---|
event | string | true | EventTypes.LOG_IN EventTypes.LOG_OUT EventTypes.LOG_IN_FAILURE | SecureNative event, read more about builtin events |
userId | string | true | 1234 name@gmail.com 08344218ffa52 | User Identifier, you can use whatever identifier you want, even user email would be great identifier, but you should be consistent with it |
userTraits | object | false | Example | Complex object that help you to identify user in your system |
context | object | false | Example | Complex object that has information about request and current user. Important Note: This prop is not requirement, however without this param we will not be able to connect between user-device fingerprint and other request details. You can use method from our SDK to extract all these properties automatically |
UserTraits Properties
Option | Type | Required | Example | Description |
---|---|---|---|---|
name | string | false | Your Name | Full user name |
string | false | name@gmail.com | User name email | |
phone | object | false | +1234567890 | User name phone |
Once the SDK has been initialized, tracking requests are sent through the SDK instance.
Tracking events with Auto Context
With Auto Context
our SDK can extract all relevant properties like IP, headers, URL etc. All you need is pass the request
object.
secureNative.track({
event: EventTypes.LOG_IN,
userId: "1234",
userTraits: {
name: "Your Name",
email: "name@gmail.com",
phone: "+1234567890",
},
context: contextFromRequest(req),
});
@RequestMapping("/track")
public void track(HttpServletRequest request, HttpServletResponse response) {
SecureNative securenative = null;
try {
securenative = SecureNative.getInstance();
} catch (SecureNativeSDKIllegalStateException e) {
System.err.printf("Could not get SecureNative instance; %s%n", e);
}
SecureNativeContext context = SecureNativeContextBuilder.fromHttpServletRequest(request).build();
EventOptions eventOptions = null;
try {
eventOptions = EventOptionsBuilder.builder(EventTypes.LOG_IN)
.userId("1234")
.userTraits("Your Name", "name@gmail.com", "+1234567890")
.context(context)
.properties(Maps.builder()
.put("prop1", "CUSTOM_PARAM_VALUE")
.put("prop2", true)
.put("prop3", 3)
.build())
.timestamp(new Date())
.build();
} catch (SecureNativeInvalidOptionsException e) {
e.printStackTrace();
}
try {
securenative.track(eventOptions);
} catch (SecureNativeInvalidOptionsException e) {
e.printStackTrace();
}
}
#if you use Flask, you can import request for AutoContext
from securenative.securenative import SecureNative
from securenative.context.securenative_context import SecureNativeContext
from securenative.models.event_options import EventOptions
from securenative.enums.event_types import EventTypes
from securenative.models.user_traits import UserTraits
def track(request):
securenative = SecureNative.get_instance()
context = SecureNativeContext.from_http_request(request)
event_options = EventOptions(event=EventTypes.LOG_IN,
user_id="1234",
user_traits=UserTraits("Your Name", "name@gmail.com", "+1234567890"),
context=context,
properties={"custom_param1": "CUSTOM_PARAM_VALUE", "custom_param2": True, "custom_param3": 3})
securenative.track(event_options)
using SecureNative.SDK;
//
// GET: /events/track
public void Track()
{
var securenative = Client.GetInstance();
var context = Client.FromHttpRequest(Request).Build();
var eventOptions = EventOptionsBuilder.Builder(EventTypes.LOG_IN)
.WithUserId("1234")
.WithUserTraits("Your Name", "name@gmail.com", "+1234567890")
.WithContext(context)
.WithProperties(new Dictionary<object, object> { { "prop1", "CUSTOM_PARAM_VALUE" }, { "prop2", true }, { "prop3", 3 } })
.WithTimestamp(new DateTime())
.Build();
securenative.Track(eventOptions);
}
require 'securenative'
def track(request)
securenative = SecureNative::Client.instance
context = securenative.from_http_request(request)
event_options = SecureNative::EventOptions.new(event: SecureNative::EventTypes::LOG_IN, user_id: '1234', context: context,
user_traits: SecureNative::UserTraits.new(name: 'Your Name', email: 'name@gmail.com', phone: '+1234567890'),
properties: { custom_param1: 'CUSTOM_PARAM_VALUE', custom_param2: true, custom_param3: 3 })
securenative.track(event_options)
@message = 'tracked'
end
SecureNative::track(array(
'event' => EventTypes::LOG_IN,
'context' => SecureNativeContext::fromRequest(),
'userId' => '1234',
'userTraits' => (object)[
'name' => 'Your Name',
'email' => 'name@gmail.com'
],
));
func Track(request *http.Request) {
sn, err := sdk.GetInstance()
if err != nil {
log.Fatal("Do some error handling")
}
contextBuilder := context.NewSecureNativeContextBuilder()
eventOptionsBuilder := events.NewEventOptionsBuilder(enums.EventTypes.LogIn)
c := contextBuilder.FromHttpRequest(request)
defer sn.Stop()
eventOptions, err := eventOptionsBuilder.
WithUserId("1234").
WithUserTraits(models.UserTraits{
Name:"Your Name",
Email:"name@gmail.com"}).
WithContext(c).
WithProperties(map[string]string{
"prop1": "CUSTOM_PARAM_VALUE",
"prop2": "true",
"prop3": "3"}).
Build()
if err != nil {
log.Fatal("Do some error handling")
}
sn.Track(eventOptions)
}
Tracking events with Custom Context
With Custom Context
you can pass all properties you want like IP, headers, URL etc. All you need is pass them to context
object.
If you don't have special properties, you can use Auto Context method to extract all properties automatically by SDK
Custom Context Properties
Name | Type | Description | Example |
---|---|---|---|
clientToken | string | either a _sn cookie or a X-SECURENATIVE header set by the SecureNative js-client | 08344218ffa521a.... |
url | string | url of incoming request | /api/v1/track |
method | string | one of HTTP request methods | GET |
ip | string | the user’s IP address | 37.142.217.18 |
remoteIp | string | the user’s remote IP address | 37.142.217.18 |
headers | object | a list of all the HTTP headers, excluding the Cookie or any sensitive authentication headers | { "cache-control": "no-cache", "accept": "*/*", "accept-encoding": "gzip,%20deflate", "accept-language": "en-US,en;q=0.9,he;q=0.8,ru;q=0.7" } |
secureNative.track({
event: EventTypes.LOG_IN,
userId: "1234",
userTraits: {
name: "Your Name",
email: "name@gmail.com",
phone: "+1234567890",
},
context: {
ip: "127.0.0.1",
clientToken: "SECURED_CLIENT_TOKEN",
headers: {
"user-agent":
'Mozilla/5.0 (iPad; U; CPU OS 3_2_1 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Mobile/7B405"',
},
},
});
@RequestMapping("/track")
public void track() {
SecureNative securenative = null;
try {
securenative = SecureNative.getInstance();
} catch (SecureNativeSDKIllegalStateException e) {
System.err.printf("Could not get SecureNative instance; %s%n", e);
}
SecureNativeContext context = SecureNative.contextBuilder()
.withIp("37.86.255.94")
.withClientToken("SECURENATIVE_CLIENT_TOKEN")
.withHeaders(Maps.defaultBuilder()
.put("user-agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.121 Safari/537.36")
.build())
.build();
EventOptions eventOptions = null;
try {
eventOptions = EventOptionsBuilder.builder(EventTypes.LOG_IN)
.userId("1234")
.userTraits("Your Name", "name@gmail.com", "+1234567890")
.context(context)
.properties(Maps.builder()
.put("prop1", "CUSTOM_PARAM_VALUE")
.put("prop2", true)
.put("prop3", 3)
.build())
.timestamp(new Date())
.build();
} catch (SecureNativeInvalidOptionsException e) {
e.printStackTrace();
}
try {
securenative.track(eventOptions);
} catch (SecureNativeInvalidOptionsException e) {
e.printStackTrace();
}
}
from securenative.securenative import SecureNative
from securenative.context.securenative_context import SecureNativeContext
from securenative.models.event_options import EventOptions
from securenative.enums.event_types import EventTypes
from securenative.models.user_traits import UserTraits
securenative = SecureNative.get_instance()
context = SecureNativeContext(client_token="SECURED_CLIENT_TOKEN",
ip="127.0.0.1",
headers={"user-agent": "Mozilla/5.0 (iPad; U; CPU OS 3_2_1 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Mobile/7B405"})
event_options = EventOptions(event=EventTypes.LOG_IN,
user_id="1234",
user_traits=UserTraits("Your Name", "name@gmail.com", "+1234567890"),
context=context,
properties={"custom_param1": "CUSTOM_PARAM_VALUE", "custom_param2": True, "custom_param3": 3})
securenative.track(event_options)
using SecureNative.SDK;
//
// GET: /events/track
public void Track()
{
var securenative = Client.GetInstance();
var context = Client.ContextBuilder()
.WithIp("127.0.0.1")
.WithClientToken("SECURENATIVE_CLIENT_TOKEN")
.WithHeaders(new Dictionary<string, string> { { "user-agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.121 Safari/537.36" } })
.Build();
var eventOptions = EventOptionsBuilder.Builder(EventTypes.LOG_IN)
.WithUserId("1234")
.WithUserTraits("Your Name", "name@gmail.com", "+1234567890")
.WithContext(context)
.WithProperties(new Dictionary<object, object> { { "prop1", "CUSTOM_PARAM_VALUE" }, { "prop2", true }, { "prop3", 3 } })
.WithTimestamp(new DateTime())
.Build();
securenative.Track(eventOptions);
}
$clientToken = "[SECURED_CLIENT_TOKEN]";
$headers = (object)["user-agent" => "Mozilla/5.0 (iPad; U; CPU OS 3_2_1 like Mac OS X; en-us"];
$ip = "79.179.88.157";
$remoteIp = null;
$url = null;
$method = null;
$body = null;
$ctx = new SecureNativeContext($clientToken, $ip, $remoteIp, $headers, $url, $method, $body);
SecureNative::track(array(
'event' => EventTypes::LOG_IN,
'context' => $ctx,
'userId' => '1234',
'userTraits' => (object)[
'name' => 'Your Name',
'email' => 'name@gmail.com'
],
// Custom properties
'properties' => (object)[
"custom_param1" => "CUSTOM_PARAM_VALUE",
"custom_param2" => true,
"custom_param3" => 3
]
));
func Track(request *http.Request) {
sn, err := sdk.GetInstance()
if err != nil {
log.Fatal("Do some error handling")
}
contextBuilder := context.NewSecureNativeContextBuilder()
eventOptionsBuilder := events.NewEventOptionsBuilder(enums.EventTypes.LogIn)
defer sn.Stop()
c := contextBuilder.
WithIp("127.0.0.1").
WithClientToken("SECURED_CLIENT_TOKEN").
WithHeaders(map[string][]string{
"user-agent": {
"Mozilla/5.0 (iPad; U; CPU OS 3_2_1 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Mobile/7B405"}
}).
Build()
eventOptions, err := eventOptionsBuilder.
WithUserId("1234").
WithUserTraits(models.UserTraits{
Name:"Your Name",
Email:"name@gmail.com"}).
WithContext(c).
WithProperties(map[string]string{
"prop1": "CUSTOM_PARAM_VALUE",
"prop2": "true",
"prop3": "3"}).
Build()
if err != nil {
log.Fatal("Do some error handling")
}
sn.Track(eventOptions)
}
curl -X POST \
https://api.securenative.com/collector/api/v1/track \
-H 'Authorization: YOUR_API_KEY' \
-H 'Content-Type: application/json' \
-d '{
"eventType": "sn.user.login",
"userId": "1234",
"userTraits" : {
"name" : "Your Name",
"email" : "name@gmail.com"
},
"request": {
"ip": "192.100.11.130",
"clientToken": "SECURED_CLIENT_TOKEN",
"headers": {
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36",
"Content-Type": "application/javascript",
"Origin": "https://securenative.com/",
"Referer": "https://securenative.com/login"
}
},
"properties": {
"prop1": "CUSTOM_PARAM_VALUE",
"prop2": true,
"prop3": 3
},
"timestamp": "2020-06-04T09:32:13.921Z"
}'
require 'securenative'
def track
securenative = SecureNative::Client.instance
context = SecureNative::Context.new(client_token: 'SECURED_CLIENT_TOKEN', ip: '127.0.0.1',
headers: { 'user-agent' => 'Mozilla: Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.3 Mozilla/5.0 (Macintosh; Intel Mac OS X x.y; rv:42.0) Gecko/20100101 Firefox/43.4' })
event_options = SecureNative::EventOptions.new(event: SecureNative::EventTypes::LOG_IN, user_id: '1234', context: context,
user_traits: SecureNative::UserTraits.new(name: 'Your Name', email: 'name@gmail.com', phone: '+1234567890'),
properties: { custom_param1: 'CUSTOM_PARAM_VALUE', custom_param2: true, custom_param3: 3 })
securenative.track(event_options)
@message = 'tracked'
end
Verify endpoint
const verifyResult = await secureNative.verify({
event: EventTypes.LOG_IN,
userId: "1234",
userTraits: {
name: "Your Name",
email: "name@gmail.com",
},
context: contextFromRequest(req),
});
console.log(res.riskLevel); // Low, Medium, High
console.log(res.score); // Risk score: 0 - 1 (0 - Very Low, 1 - Very High)
console.log(res.triggers); // ["TOR", "New IP", "New City"]
@RequestMapping("/verify")
public void verify(HttpServletRequest request, HttpServletResponse response) {
SecureNativeContext context = SecureNativeContextBuilder.fromHttpServletRequest(request).build();
EventOptions eventOptions = null;
try {
eventOptions = EventOptionsBuilder.builder(EventTypes.LOG_IN)
.userId("1234")
.userTraits("Your Name", "name@gmail.com", "+1234567890")
.context(context)
.properties(Maps.builder()
.put("prop1", "CUSTOM_PARAM_VALUE")
.put("prop2", true)
.put("prop3", 3)
.build())
.timestamp(new Date())
.build();
} catch (SecureNativeInvalidOptionsException e) {
e.printStackTrace();
}
VerifyResult verifyResult = null;
try {
verifyResult = securenative.verify(eventOptions);
} catch (SecureNativeInvalidOptionsException e) {
e.printStackTrace();
}
verifyResult.getRiskLevel(); // Low, Medium, High
verifyResult.getScore(); // Risk score: 0 -1 (0 - Very Low, 1 - Very High)
verifyResult.getTriggers(); // ["TOR", "New IP", "New City"]
}
from securenative.securenative import SecureNative
from securenative.models.event_options import EventOptions
from securenative.context.securenative_context import SecureNativeContext
from securenative.enums.event_types import EventTypes
from securenative.models.user_traits import UserTraits
def verify(request):
securenative = SecureNative.get_instance()
context = SecureNativeContext.from_http_request(request)
event_options = EventOptions(event=EventTypes.LOG_IN,
user_id="1234",
user_traits=UserTraits("Your Name", "name@gmail.com", "+1234567890"),
context=context,
properties={"custom_param1": "CUSTOM_PARAM_VALUE", "custom_param2": True, "custom_param3": 3})
verify_result = securenative.verify(event_options)
verify_result.risk_level # Low, Medium, High
verify_result.score # Risk score: 0 -1 (0 - Very Low, 1 - Very High)
verify_result.triggers # ["TOR", "New IP", "New City"]
using SecureNative.SDK;
//
// GET: /events/verify
public void Verify()
{
var securenative = Client.GetInstance();
var context = Client.FromHttpRequest(Request).Build();
var eventOptions = EventOptionsBuilder.Builder(EventTypes.LOG_IN)
.WithUserId("1234")
.WithUserTraits("Your Name", "name@gmail.com", "+1234567890")
.WithContext(context)
.WithProperties(new Dictionary<object, object> { { "prop1", "CUSTOM_PARAM_VALUE" }, { "prop2", true }, { "prop3", 3 } })
.WithTimestamp(new DateTime())
.Build();
var verifyResult = securenative.Verify(eventOptions);
verifyResult.GetRiskLevel(); // Low, Medium, High
verifyResult.GetScore(); // Risk score: 0 -1 (0 - Very Low, 1 - Very High)
verifyResult.GetTriggers(); // ["TOR", "New IP", "New City"]
}
require 'securenative'
def verify(request)
securenative = SecureNative::Client.instance
context = securenative.from_http_request(request)
event_options = SecureNative::EventOptions.new(event: SecureNative::EventTypes::LOG_IN, user_id: '1234', context: context,
user_traits: SecureNative::UserTraits.new(name: 'Your Name', email: 'name@gmail.com', phone: '+1234567890'),
properties: { custom_param1: 'CUSTOM_PARAM_VALUE', custom_param2: true, custom_param3: 3 })
verify_result = securenative.verify(event_options)
verify_result.risk_level # Low, Medium, High
verify_result.score # Risk score: 0 -1 (0 - Very Low, 1 - Very High)
verify_result.triggers # ["TOR", "New IP", "New City"]
end
$ver = SecureNative::verify(array(
'event' => EventTypes::VERIFY,
'userId' => '1234',
'context' => SecureNativeContext::fromRequest(),
'userTraits' => (object)[
'name' => 'Your Name',
'email' => 'name@gmail.com'
]
));
print_r($ver->riskLevel); // (Low, Medium, High)
print_r($ver->score); // (0 - Very Low, 1 - Very High)
print_r($ver->triggers); // (Example: ["TOR", "New IP", "New City"])
package main
import (
"github.com/securenative/securenative-go/context"
"github.com/securenative/securenative-go/enums"
"github.com/securenative/securenative-go/events"
"github.com/securenative/securenative-go/models"
"github.com/securenative/securenative-go/sdk"
"log"
)
func main() {
sn, err := sdk.GetInstance()
if err != nil {
log.Fatal("Do some error handling")
}
contextBuilder := context.NewSecureNativeContextBuilder()
eventOptionsBuilder := events.NewEventOptionsBuilder(enums.EventTypes.LogIn)
defer sn.Stop()
c := contextBuilder.WithIp("127.0.0.1").WithClientToken("SECURED_CLIENT_TOKEN").WithHeaders(map[string][]string{"user-agent": {"Mozilla/5.0 (iPad; U; CPU OS 3_2_1 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Mobile/7B405"}}).Build()
eventOptions, err := eventOptionsBuilder.WithUserId("1234").WithUserTraits(models.UserTraits{Name:"Your Name", Email:"name@gmail.com"}).WithContext(c).WithProperties(map[string]string{"prop1": "CUSTOM_PARAM_VALUE", "prop2": "true", "prop3": "3"}).Build()
if err != nil {
log.Fatal("Do some error handling")
}
verifyResult := sn.Verify(eventOptions)
verifyResult.RiskLevel // Low, Medium, High
verifyResult.Score // Risk score: 0 - 1 (0 - Very Low, 1 - Very High)
verifyResult.Triggers // ["TOR", "New IP", "New City"]
curl -X POST \
https://api.securenative.com/collector/api/v1/verify \
-H 'Authorization: YOUR_API_KEY' \
-H 'Content-Type: application/json' \
-d '{
"eventType": "sn.verify",
"userId": "1234",
"userTraits" : {
"name" : "Your Name",
"email" : "name@gmail.com",
"phone": "+12012673412"
},
"request": {
"ip": "192.100.11.130",
"clientToken": "SECURED_CLIENT_TOKEN",
"headers": {
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36"
}
},
"timestamp": "2020-06-04T09:32:13.921Z"
}'
Example Response:
{
"riskLevel" : "low",
"score" : "0.2",
"triggers" : ["NewDevice"]
}
Webhooks
Use verify Webhook middleware to ensure that webhook is coming from SecureNative
const secureNative = SecureNative.getInstance();
app.post("/securewebhook", secureNative.middleware.verifyWebhook, (req, res) => {
const {riskLevel, riskScore, triggers } = req.body;
}
@RequestMapping("/webhook")
public void webhookEndpoint(HttpServletRequest request, HttpServletResponse response) {
SecureNative securenative = null;
try {
securenative = SecureNative.getInstance();
} catch (SecureNativeSDKIllegalStateException e) {
System.err.printf("Could not get SecureNative instance; %s%n", e);
}
// Checks if request is verified
Boolean isVerified = securenative.verifyRequestPayload(request);
}
from securenative.securenative import SecureNative
def webhook_endpoint(request):
securenative = SecureNative.get_instance()
# Checks if request is verified
is_verified = securenative.verify_request_payload(request)
using SecureNative.SDK;
//
// GET: /webhook
public void WebhookEndpoint()
{
var securenative = Client.GetInstance();
// Checks if request is verified
var isVerified = securenative.VerifyRequestPayload(Request);
}
require 'securenative'
def webhook_endpoint(request)
securenative = SecureNative::Client.instance
# Checks if request is verified
is_verified = securenative.verify_request_payload(request)
end
$verified = SecureNative::getMiddleware()->verifySignature();
if ($verified) {
// Request is trusted (coming from SecureNative)
}
package demo
import (
"github.com/securenative/securenative-go/sdk"
"log"
"net/http"
)
func VerifyWebHook(request *http.Request) bool {
sn, err := sdk.GetInstance()
if err != nil {
log.Fatal("Do some error handling")
}
defer sn.Stop()
return sn.VerifyRequestPayload(request)
}
Extract proxy headers from Cloudflare
You can specify custom header keys to allow extraction of client ip from different providers. This example demonstrates the usage of proxy headers for ip extraction from Cloudflare.
Option 1: Using config file
SECURENATIVE_API_KEY: API_KEY
SECURENATIVE_PROXY_HEADERS: ["CF-Connecting-IP"]
Options 2: Using ConfigurationBuilder
require 'securenative'
options = SecureNative::Options.new(api_key: 'API_KEY', max_events: 10, log_level: 'ERROR', proxy_headers: ['CF-Connecting-IP'])
SecureNative::Client.init_with_options(options)