SecureAuth Documentation

Comprehensive guide for implementing passwordless authentication with AI-powered risk scoring.

Quick Start

Get up and running with SecureAuth in minutes. This guide will walk you through the basic setup and your first authentication flow.

Installation

NPM Package

npm install @secureauth/sdk

CDN Script

<script src="https://cdn.secureauth.dev/sdk/v1/secureauth.min.js"></script>

Basic Configuration

import SecureAuth from '@secureauth/sdk';
const auth = new SecureAuth({
apiUrl: 'https://api.secureauth.dev/v1',
clientId: 'your-client-id',
domain: 'your-domain.com',
webAuthn: {
rpId: 'your-domain.com',
rpName: 'Your App Name',
userVerification: 'preferred'
}
});

Authentication Flow

Understanding the complete passwordless authentication process with risk assessment.

Registration Flow

1
User initiates registration
2
Device fingerprinting
3
WebAuthn credential creation
4
Credential verification

Authentication Flow

1
Risk assessment
2
WebAuthn challenge
3
Biometric verification
4
Session establishment

User Management

Comprehensive API endpoints and tools for managing user accounts, roles, and permissions.

User Operations

Create User

POST /users
{
"email": "user@example.com",
"displayName": "John Smith",
"role": "user",
"metadata": {
"department": "Sales",
"location": "New York"
},
"preferences": {
"language": "en",
"timezone": "America/New_York"
}
}

Update User

PATCH /users/{userId}
{
"displayName": "John A. Smith",
"metadata": {
"department": "Marketing",
"title": "Senior Manager"
}
}

Role Management

Available Roles

Administrator Full system access
Manager Team management
User Standard access

Assign Role

POST /users/{userId}/roles
{
"role": "manager",
"scope": ["team_management", "report_access"],
"expiresAt": "2025-12-31T23:59:59Z"
}

Device Management

Device Last Active Status Actions
MacBook Pro (Sarah's) 2 minutes ago Active
iPhone 15 Pro 1 hour ago Active
Windows Laptop 30 days ago Inactive

Risk Scoring

Advanced AI-powered risk assessment system for detecting and preventing unauthorized access attempts.

Risk Factors

Location Analysis
25%
Device Fingerprint
30%
Behavioral Patterns
25%
Network Security
20%

Risk Thresholds

Low Risk (0-30) Allow Access
Medium Risk (31-70) Additional Verification
High Risk (71-100) Block Access

Risk Assessment API

Request Risk Score

POST /risk/assess
{
"userId": "user_123",
"deviceInfo": {
"fingerprint": "fp_abc123",
"userAgent": "Mozilla/5.0...",
"platform": "MacIntel"
},
"location": {
"ip": "192.168.1.1",
"coordinates": {
"latitude": 40.7128,
"longitude": -74.0060
}
},
"behaviorMetrics": {
"loginTime": "2025-09-05T14:30:00Z",
"typingPattern": "pattern_xyz",
"mouseMovement": "movement_data"
}
}

Response

{
"riskScore": 45.7,
"riskLevel": "medium",
"factors": {
"location": {
"score": 20.5,
"reason": "New location detected"
},
"device": {
"score": 15.2,
"reason": "Known device"
},
"behavior": {
"score": 10.0,
"reason": "Normal pattern"
}
},
"recommendedAction": "require_2fa",
"expiresAt": "2025-09-05T15:30:00Z"
}

Authentication API

RESTful API endpoints for managing authentication, user registration, and risk assessment.

POST /auth/register

Register a new user with WebAuthn credentials.

Request Body

{
"email": "user@example.com",
"displayName": "John Doe",
"deviceInfo": {
"userAgent": "Mozilla/5.0...",
"platform": "MacIntel",
"language": "en-US"
}
}

Response

{
"challengeId": "ch_1234567890",
"publicKeyCredentialCreationOptions": {
"challenge": "base64-challenge",
"rp": {
"name": "SecureAuth",
"id": "example.com"
},
"user": {
"id": "base64-user-id",
"name": "user@example.com",
"displayName": "John Doe"
}
}
}

POST /auth/authenticate

Authenticate user with WebAuthn and risk assessment.

Request Body

{
"email": "user@example.com",
"riskContext": {
"ipAddress": "192.168.1.1",
"location": {
"latitude": 37.7749,
"longitude": -122.4194
},
"deviceFingerprint": "fp_abc123",
"timestamp": "2024-01-15T10:30:00Z"
}
}

Response

{
"challengeId": "ch_9876543210",
"riskScore": 0.25,
"requireMFA": false,
"publicKeyCredentialRequestOptions": {
"challenge": "base64-challenge",
"allowCredentials": [{
"id": "base64-credential-id",
"type": "public-key"
}],
"userVerification": "preferred"
}
}

Passkey Registration

Implement WebAuthn passkey registration with platform authenticators and security keys.

Client-Side Implementation

async function registerPasskey(email, displayName) {
try {
// Get registration options from server
const response = await fetch('/auth/register', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ email, displayName })
});
const { challengeId, publicKeyCredentialCreationOptions } = await response.json();
// Convert base64 strings to ArrayBuffers
const options = {
...publicKeyCredentialCreationOptions,
challenge: base64ToArrayBuffer(publicKeyCredentialCreationOptions.challenge),
user: {
...publicKeyCredentialCreationOptions.user,
id: base64ToArrayBuffer(publicKeyCredentialCreationOptions.user.id)
}
};
// Create credential
const credential = await navigator.credentials.create({
publicKey: options
});
// Send credential to server for verification
const verifyResponse = await fetch('/auth/verify-registration', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
challengeId,
credential: {
id: credential.id,
rawId: arrayBufferToBase64(credential.rawId),
response: {
clientDataJSON: arrayBufferToBase64(credential.response.clientDataJSON),
attestationObject: arrayBufferToBase64(credential.response.attestationObject)
},
type: credential.type
}
})
});
return await verifyResponse.json();
} catch (error) {
console.error('Registration failed:', error);
throw error;
}
}

AWS Cognito Setup

Configure AWS Cognito User Pool for passwordless authentication with custom Lambda triggers.

User Pool Configuration

{
"PoolName": "SecureAuth-UserPool",
"Policies": {
"PasswordPolicy": {
"MinimumLength": 8,
"RequireUppercase": false,
"RequireLowercase": false,
"RequireNumbers": false,
"RequireSymbols": false
}
},
"UsernameAttributes": ["email"],
"AutoVerifiedAttributes": ["email"],
"MfaConfiguration": "OPTIONAL",
"EnabledMfas": ["SOFTWARE_TOKEN_MFA"],
"LambdaConfig": {
"PreAuthentication": "arn:aws:lambda:region:account:function:PreAuthTrigger",
"PostAuthentication": "arn:aws:lambda:region:account:function:PostAuthTrigger",
"DefineAuthChallenge": "arn:aws:lambda:region:account:function:DefineAuthChallenge",
"CreateAuthChallenge": "arn:aws:lambda:region:account:function:CreateAuthChallenge",
"VerifyAuthChallengeResponse": "arn:aws:lambda:region:account:function:VerifyAuthChallenge"
}
}

Lambda Trigger Functions

Define Auth Challenge

exports.handler = async (event) => {
const { request, response } = event;
if (request.session.length === 0) {
// First challenge - WebAuthn
response.challengeName = 'CUSTOM_CHALLENGE';
response.issueTokens = false;
} else if (request.session.length === 1 && request.session[0].challengeResult === true) {
// WebAuthn succeeded
response.issueTokens = true;
} else {
// Challenge failed
response.issueTokens = false;
}
return event;
};

JavaScript SDK

Complete JavaScript SDK for integrating SecureAuth into web applications.

SDK Initialization

import SecureAuth from '@secureauth/sdk';
const auth = new SecureAuth({
apiUrl: 'https://api.secureauth.dev/v1',
clientId: 'sa_client_abc123',
domain: 'myapp.com',
webAuthn: {
rpId: 'myapp.com',
rpName: 'My Application',
userVerification: 'preferred',
authenticatorSelection: {
authenticatorAttachment: 'platform',
userVerification: 'preferred',
requireResidentKey: true
}
},
riskAssessment: {
enabled: true,
collectDeviceInfo: true,
collectBehaviorMetrics: true
}
});
// Initialize the SDK
await auth.initialize();

Authentication Methods

Register User

// Register new user
const result = await auth.register({
email: 'user@example.com',
displayName: 'John Doe',
metadata: {
department: 'Engineering',
role: 'Developer'
}
});
if (result.success) {
console.log('User registered:', result.user);
} else {
console.error('Registration failed:', result.error);
}

Authenticate User

// Authenticate user
const result = await auth.authenticate({
email: 'user@example.com'
});
if (result.success) {
console.log('Authentication successful');
console.log('Access token:', result.tokens.accessToken);
console.log('Risk score:', result.riskScore);
} else {
console.error('Authentication failed:', result.error);
}

Authentication Ceremony

Understanding the WebAuthn authentication ceremony flow and implementation.

Authentication Flow

async function authenticateUser(email) {
try {
// 1. Get authentication options from server
const response = await fetch('/auth/authenticate', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ email })
});
const { challengeId, publicKeyCredentialRequestOptions } = await response.json();
// 2. Convert challenge to ArrayBuffer
const options = {
...publicKeyCredentialRequestOptions,
challenge: base64ToArrayBuffer(publicKeyCredentialRequestOptions.challenge),
allowCredentials: publicKeyCredentialRequestOptions.allowCredentials.map(cred => ({
...cred,
id: base64ToArrayBuffer(cred.id)
}))
};
// 3. Request credential from authenticator
const credential = await navigator.credentials.get({
publicKey: options
});
// 4. Send assertion to server for verification
const verifyResponse = await fetch('/auth/verify-assertion', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
challengeId,
credential: {
id: credential.id,
rawId: arrayBufferToBase64(credential.rawId),
response: {
clientDataJSON: arrayBufferToBase64(credential.response.clientDataJSON),
authenticatorData: arrayBufferToBase64(credential.response.authenticatorData),
signature: arrayBufferToBase64(credential.response.signature),
userHandle: arrayBufferToBase64(credential.response.userHandle)
},
type: credential.type
}
})
});
return await verifyResponse.json();
} catch (error) {
console.error('Authentication failed:', error);
throw error;
}
}

Browser Support

WebAuthn browser compatibility and platform authenticator support.

Desktop Browsers

Chrome
v67+
Firefox
v60+
Safari
v13+
Edge
v79+

Mobile Support

Android
v7+
iOS
v14.5+

Feature Detection

async function checkWebAuthnSupport() {
if (!window.PublicKeyCredential) {
return {
supported: false,
reason: 'WebAuthn API not available'
};
}
const platformAuthenticator = await PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable();
const conditionalUI = await PublicKeyCredential.isConditionalMediationAvailable?.() || false;
return {
supported: true,
platformAuthenticator,
conditionalUI,
credentialManagement: !!navigator.credentials?.store,
authenticatorSelection: {
residentKey: true,
userVerification: true,
attestation: true
}
};
}

IAM Permissions

AWS IAM roles and policies required for SecureAuth integration.

Lambda Function Role

{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"cognito-idp:AdminInitiateAuth",
"cognito-idp:AdminRespondToAuthChallenge",
"cognito-idp:AdminCreateUser",
"cognito-idp:AdminSetUserPassword",
"cognito-idp:AdminUpdateUserAttributes",
"cognito-idp:AdminDeleteUser"
],
"Resource": "arn:aws:cognito-idp:region:account:userpool/*"
},
{
"Effect": "Allow",
"Action": [
"dynamodb:PutItem",
"dynamodb:GetItem",
"dynamodb:UpdateItem",
"dynamodb:DeleteItem",
"dynamodb:Query"
],
"Resource": [
"arn:aws:dynamodb:region:account:table/credentials",
"arn:aws:dynamodb:region:account:table/sessions"
]
},
{
"Effect": "Allow",
"Action": [
"kms:Decrypt",
"kms:GenerateDataKey"
],
"Resource": "arn:aws:kms:region:account:key/*"
}
]
}

API Gateway Role

{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"lambda:InvokeFunction"
],
"Resource": [
"arn:aws:lambda:region:account:function:auth-*",
"arn:aws:lambda:region:account:function:risk-*"
]
}
]
}

Python SDK

Server-side integration using the Python SDK for SecureAuth.

Installation and Setup

# Install using pip
pip install secureauth-sdk
# Basic configuration
from secureauth import SecureAuth
auth = SecureAuth(
api_key="your-api-key",
api_secret="your-api-secret",
domain="your-domain.com",
risk_assessment={
"enabled": True,
"threshold": 0.7,
"factors": ["location", "device", "behavior"]
}
)

Usage Examples

from secureauth import WebAuthnManager, RiskAssessor
from secureauth.models import User, Credential
async def register_user(email: str, display_name: str):
# Create user
user = await auth.users.create(
email=email,
display_name=display_name
)
# Generate registration options
webauthn = WebAuthnManager(auth)
options = await webauthn.generate_registration_options(user)
return {
"user_id": user.id,
"options": options
}
async def verify_registration(user_id: str, credential: dict):
try:
# Verify and store credential
webauthn = WebAuthnManager(auth)
result = await webauthn.verify_registration(
user_id=user_id,
credential=credential
)
return {"success": True, "credential_id": result.credential_id}
except Exception as e:
return {"success": False, "error": str(e)}
async def authenticate_user(email: str, risk_context: dict):
# Assess risk
risk = RiskAssessor(auth)
score = await risk.evaluate(
email=email,
context=risk_context
)
if score > auth.config.risk_threshold:
return {"success": False, "reason": "high_risk"}
# Generate authentication options
webauthn = WebAuthnManager(auth)
options = await webauthn.generate_authentication_options(email)
return {
"options": options,
"risk_score": score
}

React Components

Ready-to-use React components for implementing SecureAuth authentication flows.

Authentication Components

import { useSecureAuth, WebAuthnButton, AuthProvider } from '@secureauth/react';
function App() {
return (



);
}
function Authentication() {
const { register, authenticate, user, loading, error } = useSecureAuth();
const handleRegister = async () => {
try {
await register({
email: 'user@example.com',
displayName: 'John Doe'
});
} catch (err) {
console.error('Registration failed:', err);
}
};
return (
{!user ? ( <> Register with Passkey authenticate()} loading={loading} > Sign in with Passkey ) : ( )} {error && ( )}
); }

Custom Hook Usage

import { useSecureAuth, useRiskAssessment } from '@secureauth/react';
function LoginForm() {
const { authenticate, loading } = useSecureAuth();
const { assessRisk } = useRiskAssessment();
const handleSubmit = async (e) => {
e.preventDefault();
const riskScore = await assessRisk({
email: 'user@example.com',
deviceInfo: navigator.userAgent,
location: await getCurrentLocation()
});
if (riskScore.level === 'low') {
await authenticate({
email: 'user@example.com',
riskContext: riskScore.context
});
} else {
// Handle high risk scenario
requestAdditionalVerification();
}
};
return (
); }

Common Issues

Troubleshooting guide for common integration problems and their solutions.

WebAuthn Not Supported

Problem

Browser doesn't support WebAuthn API or user agent lacks platform authenticator.

Solution

// Check WebAuthn support
if (!window.PublicKeyCredential) {
console.error('WebAuthn not supported');
// Fallback to traditional authentication
return;
}
// Check platform authenticator availability
const available = await PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable();
if (!available) {
console.warn('Platform authenticator not available');
// Offer security key option or fallback
}

High Risk Score Blocking Access

Problem

Legitimate users being blocked due to high risk scores from new devices or locations.

Solution

// Implement progressive risk assessment
const riskConfig = {
thresholds: {
low: 0.3,
medium: 0.6,
high: 0.8
},
actions: {
low: 'allow',
medium: 'require_mfa',
high: 'require_admin_approval'
},
deviceTrust: {
newDeviceGracePeriod: 24 * 60 * 60 * 1000, // 24 hours
trustedDeviceBonus: -0.2 // Reduce risk score
}
};