Comprehensive guide for implementing passwordless authentication with AI-powered risk scoring.
Get up and running with SecureAuth in minutes. This guide will walk you through the basic setup and your first authentication flow.
npm install @secureauth/sdk
<script src="https://cdn.secureauth.dev/sdk/v1/secureauth.min.js"></script>
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'
}
});
Understanding the complete passwordless authentication process with risk assessment.
Comprehensive API endpoints and tools for managing user accounts, roles, and permissions.
POST /users
{
"email": "user@example.com",
"displayName": "John Smith",
"role": "user",
"metadata": {
"department": "Sales",
"location": "New York"
},
"preferences": {
"language": "en",
"timezone": "America/New_York"
}
}
PATCH /users/{userId}
{
"displayName": "John A. Smith",
"metadata": {
"department": "Marketing",
"title": "Senior Manager"
}
}
POST /users/{userId}/roles
{
"role": "manager",
"scope": ["team_management", "report_access"],
"expiresAt": "2025-12-31T23:59:59Z"
}
| 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 |
Advanced AI-powered risk assessment system for detecting and preventing unauthorized access attempts.
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"
}
}
{
"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"
}
RESTful API endpoints for managing authentication, user registration, and risk assessment.
Register a new user with WebAuthn credentials.
{
"email": "user@example.com",
"displayName": "John Doe",
"deviceInfo": {
"userAgent": "Mozilla/5.0...",
"platform": "MacIntel",
"language": "en-US"
}
}
{
"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"
}
}
}
Authenticate user with WebAuthn and risk assessment.
{
"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"
}
}
{
"challengeId": "ch_9876543210",
"riskScore": 0.25,
"requireMFA": false,
"publicKeyCredentialRequestOptions": {
"challenge": "base64-challenge",
"allowCredentials": [{
"id": "base64-credential-id",
"type": "public-key"
}],
"userVerification": "preferred"
}
}
Implement WebAuthn passkey registration with platform authenticators and security keys.
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;
}
}
Configure AWS Cognito User Pool for passwordless authentication with custom Lambda triggers.
{
"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"
}
}
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;
};
Complete JavaScript SDK for integrating SecureAuth into web applications.
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();
// 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
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);
}
Understanding the WebAuthn authentication ceremony flow and implementation.
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;
}
}
WebAuthn browser compatibility and platform authenticator support.
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
}
};
}
AWS IAM roles and policies required for SecureAuth integration.
{
"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/*"
}
]
}
{
"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-*"
]
}
]
}
Server-side integration using the Python SDK for SecureAuth.
# 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"]
}
)
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
}
Ready-to-use React components for implementing SecureAuth authentication flows.
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 && (
)}
);
}
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 (
);
}
Troubleshooting guide for common integration problems and their solutions.
Browser doesn't support WebAuthn API or user agent lacks platform authenticator.
// 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
}
Legitimate users being blocked due to high risk scores from new devices or locations.
// 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
}
};