@innerworks-me/iw-auth-sdk
v1.2.5
Published
We host our SDK through npm, so to install it for your project simply run the following in the command line
Downloads
515
Readme
Installation
We host our SDK through npm, so to install it for your project simply run the following in the command line
npm i @innerworks-me/iw-auth-sdk --save
Setup
Communication with innerworks API requires the configuration of a project with a project ID and secret. Currently the product is still in early private beta, contact us via our website at innerworks.me for assistance with setup and to receive your project credentials.
Innerworks Auth Provider - Frontend
React Integration
First import the SDK
import { InnerworksAuth } from "@innerworks-me/iw-auth-sdk";
Then initialize it
import { InnerworksAuth } from "@innerworks-me/iw-auth-sdk";
export default function YourPage() {
let iwAuth = new InnerworksAuth("{your project id}", "{your redirect url}");
// ... rest of your page
}
You can use the useRef hook to allow the innerworks SDK to create a login button
import { InnerworksAuth } from "@innerworks-me/iw-auth-sdk";
import { useEffect, useRef } from "react";
export default function YourPage() {
let iwAuth = new InnerworksAuth("{your project id}", "{your redirect url}");
// Create a ref for the button container
const buttonRef = useRef<HTMLDivElement>(null);
useEffect(() => {
// Generate the button and append it to the buttonContainerRef
if (buttonRef.current) {
const button = iwAuth.getInnerworksSignInButton();
buttonRef.current.appendChild(button);
}
}, []);
// ... rest of your page
// ... then at some point ...
return (
// ... rest of elements
<div ref={buttonRef}/>
);
}
This will redirect the user to authentication, and redirect to the page you specified. In order to use the returned user object, include the following code in your redirect page
import InnerworksAuth from "@innerworks-me/iw-auth-sdk";
export default function YourRedirectPage() {
let iwAuth = new InnerworksAuth("{your project id}", "{your redirect url}");
function onAuthSuccess(userObject: any) {
// your callback function here
}
useEffect(() => {
iwAuth.setCallback(onAuthSuccess);
}, [])
// ... rest of your page
}
Innerworks NonAuth Provider - Frontend
If you prefer to retain your existing authentication provider, the Innerworks Fraud Detection Suite can be installed and sit invisibly in the background to perform bot detection and user coherence without replacing your authentication system.
React Integration
First, in your frontend page, import the InnerworksMetrics object to collect metrics.
import { InnerworksMetrics, UserMetricsType } from "@innerworks/iw-auth-sdk";
Initialise the InnerworksMetrics object in your page as follows
const [iwMetrics, setIwMetrics] = useState<any>();
useEffect(() => {
setIwMetrics(new InnerworksMetrics(<yourAppID>));
});
reccomended: if you want to collect button UI metrics, pass a css selector to collect metrics on the already exiting button that is meant to trigger Innerworksʼ fraud detection (css selector accepted are ID, Class, Tag, Attribute, pseudo-class, etc).
new UserMetrics(<yourAppID>, "#claim");
Send Metrics On Submittion
In the webpage, where the user submits a form, signs in or submits a tx, call send(userId)
on the iwMetrics
object, where userId
is an unique identifier for the user (i.e. email, username or wallet address)
i.e:
const handleSubmit = async (e: FormEvent<HTMLFormElement>) => {
e.preventDefault();
iwMetrics.send(userId, projectId)
}
Overall the integration code would look like:
import { InnerworksMetrics } from "@innerworks-me/iw-auth-sdk";
import { useEffect } from "react";
export default function YourPage() {
const [iwMetrics, setIwMetrics] = useState<any>();
useEffect(() => {
setIwMetrics(new InnerworksMetrics(<yourAppId>, "#signInButton"));
}, []);
const triggerIwFraudDetection = async (event: Event) => {
event.preventDefault();
await iwMetrics.send(<userName>);
};
return (
// ... rest of elements
<Button onClick={triggerIwFraudDetection}>Claim</Button>
)
}
Innerworks NonAuth Provider Bakend Integration
If you are interested on integrating Innerworks' metric collection into your technology stack, without any third party data flows and calls from your frontend application, this involves two key steps.
- First, use our frontend SDK to collect user metrics during your own sign in process and send these to your own backend API.
- Second, use our network flow extractor package to extract network flow features, these along with the user metrics can be passed to our backend for processing. We also require a unique identifier for the user to be passed at this point, so metrics can be related across different login sessions.
In your frontend Login page, import the UserMetrics object to collect metrics.
import { UserMetrics, UserMetricsType } from "@innerworks/iw-auth-sdk";
Initialise the UserMetrics object in your SignIn page as follows
let iwMetrics: UserMetricsType;
useEffect(() => {
iwMetrics = new UserMetrics();
});
(recomended) if you want to collect login button UI metrics, pass a css selector to collect metrics on your already exiting sign in button
(css selector accpted are ID, Class, Tag, Attribute, pseudo-calss, etc)
let iwMetrics = new UserMetrics(true, "#signIn");
From here you have two options depending on how you want this flow to interact with your existing authentication.
Option 1: Separate Endpoint
Here you perform your authentication, get a user id, and pass this along with the collected metrics to a dedicated separate endpoint to your backend
const handleSubmit = async (e: FormEvent<HTMLFormElement>) => {
e.preventDefault();
// ... your authentication here ...
const userId: string = yourAuthenticationProcess();
// then pass metrics along with unique id
const metrics: UserMetricsType = iwMetrics.getAllMetrics();
const requestBody = {
"id": userId,
"metrics": metrics
}
await fetch("{yourBackendApi}/innerworks/metrics", {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(requestBody);
Backend Flow Integration Docs 1
});
}
Option 2: Part of Authentication
Alternatively, you can pass the user metrics alongside your authentication request to your backend.
const handleSubmit = async (e: FormEvent<HTMLFormElement>) => {
e.preventDefault();
const metrics: UserMetricsType = iwMetrics.getAllMetrics();
// pass metrics in authentication request here...
// e.g. add to the body of your current auth request
}
Backend Integration Step
Our NetworkFlowExtractor SDK is written in JavaScript and so can be used in any node backend framework. The example we give here is for a NestJS API but the logic is agnostic to framework.
First install the flow extractor SDK, and optionally the auth SDK (for the UserMetricsType object). See the Flow Extractor package documentation at @innerworks/flow-extractor-node for more details on how it works and its prerequistes.
npm i --save @innerworks/flow-extractor-node
npm i --save @innerworks/iw-auth-sdk
There are then two possible configurations depending on your choice of having a separate endpoint for user metrics or not.
Option 1: Separate Endpoint Set up a POST /innerworks/metrics endpoint so that the user metrics can be passed to your backend, for example:
// app.controller.ts
import { UserMetricsType } from '@innerworks-me/iw-auth-sdk';
@Controller()
export class AppController {
constructor(private readonly appService: AppService) {}
@Post()
@HttpCode(HttpStatus.NO_CONTENT)
async postMetrics(
@Req() req,
@Body() body : { id: string, metrics: UserMetricsType}
) : Promise<void> {
await this.appService.getFlowFeaturesAndSendProfile(body.metrics, body.id, req);
}
}
Then write the logic to get the flow features using our flow extractor package, combine them with the metrics, and send to our backend along with your project details and the user id.
// app.service.ts
import NetworkFlowExtractor from '@innerworks-me/flow-extractor-node'
import { UserMetricsType } from '@innerworks-me/iw-auth-sdk';
@Injectable()
export class AppService {
private flowExtractor: NetworkFlowExtractor;
private PROJECT_ID = 'xxxx-xxxx-xxxx-xxxx';
private PROJECT_SECRET = 'xxxx-xxxx-xxxx-xxxx'; // we recommend using a secret manager
constructor() {
this.flowExtractor = new NetworkFlowExtractor();
}
async getFlowFeaturesAndSendProfile(
metrics: UserMetricsType,
userId: string,
@Req() req
) {
const flowFeatures = await this.flowExtractor.getFlowFeaturesWhenReady(
req.socket.remoteAddress,
req.socket.remotePort
);
const body = {
"projectId": this.PROJECT_ID,
"projectSecret": this.PROJECT_SECRET,
"user_id": userId,
"metrics": metrics,
"flow_features": flowFeatures
};
await fetch(
'https://api.prod.innerworks.me/api/v1/innerworks/behavioural-profile',
{
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(body)
}
);
}
}
Option 2: Part of Authentication
In order to do this you need to configure your authentication endpoint to receive user metrics, then once you have authenticated the user you can pass the metrics to the innerworks backend
async yourAuthenticationServiceMethod(
metrics: UserMetricsType,
@Req() req,
...yourAuthParams
) {
// perform your authentication as normal
const userId: string = yourAuthenticationProcess();
// then pass metrics to innerworks backend
const flowFeatures = await this.flowExtractor.getFlowFeaturesWhenReady(
req.socket.remoteAddress,
req.socket.remotePort
);
const body = {
"projectId": this.PROJECT_ID,
"projectSecret": this.PROJECT_SECRET,
"user_id": userId,
"metrics": metrics,
"flow_features": flowFeatures
};
await fetch(
'https://api.prod.innerworks.me/api/v1/innerworks/behavioural-profile',
{
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(body)
});
}
Validation: You may choose to add validation pipes to verify the metrics passed in the request body, and this is something we hope to help facilitate through our SDK in the future. For now however, if you choose to do this then you will need to look at the UserMetricsType for the object model and create the DTO yourself. We do perform validation on our backend when the request is made to /innerworks/behavioural-profile and so this is not compulsory.