Show / Hide Table of Contents

    How to write and apply MFA (2-factor) authentication policy script

    Introduction

    This page describes how to write a custom C# two-factor policy script to force or ignore two-factor authentication. The samples will address some use cases that our customers usually ask for: whether client IP is or is not within a specific range, whether a specific claim exists, or whether the logged in user comes from a specific service provider.

    Where to write the script

    A policy script is set up for each authentication connection configuration. You need to navigate to the applicable connection setting and write the C# script.

    MFA (2-factor) authentication policy script

    Or in the Safewhere Admin:

    MFA (2-factor) authentication policy script

    You can find all syntax and built-in functions here

    The order of rules is important. If one rule is not satisfied or returns false, all later rules are ignored. If the second-factor policy script is empty, the second-factor authentication will be used.

    Common use cases

    1. Force second-factor for IP Addresses from 192.168.1.15 to 192.168.1.20 and ignore second-factor for IP Addresses from 192.168.1.0 to 192.168.1.14.
    Rules
    	.ApplyIPAddressRange("192.168.1.1 - 192.168.1.20")
    	.NotApplyIPAddressRange("192.168.1.17 - 192.168.1.18");
    
    1. Force second-factor authentication for users that have a specific claim.
    Rules
    	.ApplyExpression((RuleContext) => {
    		return RuleContext.FirstFactorPrincipal.HasClaim("urn:identify:rest-api:role", "Administrator");
    		});
    
    1. Enable second factor authentication for users coming from a specific service provider.
    Rules.ApplyExpression((RuleContext) => {
    	return RuleContext.ProtocolConnectionEntityId == "ServiceProvider1";
    	});
    
    1. Examining HttpContext:
    Rules.ApplyExpression((RuleContext) => {
    	if (HttpContext.Current.Request.Cookies["AlwaysNeedSecondFactor"].Value == "false") // Note: please don't do this in reality. Your users can edit cookies easily.
    	{
    	    (RuleContext.FirstFactorPrincipal.Identity as ClaimIdentity).AddClaim(new Claim("skippingSecondFactorClaimType", "true"));
    		return false;
    	}
    });
    
    Back to top Generated by DocFX