Skip to content

Authentication Methods

HomeDocumentationFeatures → Authentication


Overview

Cesivi Server supports multiple authentication methods to accommodate different client scenarios, from development/testing environments to production-like setups with real credential validation.

Supported Methods: - ✅ Generic Authentication (Accept All Credentials) - For testing - ✅ Basic Authentication - Simple username/password - ✅ NTLM Authentication - Windows integrated auth - ✅ Bearer Token (JWT) - Modern OAuth-style auth - ✅ Forms Authentication - Cookie-based auth - ✅ Anonymous Access - No credentials required


Configuration

Server Configuration (appsettings.json)

{
  "Cesivi": {
    "Authentication": {
      "AcceptAllCredentials": true,
      "AllowAnonymous": true,
      "EnableNTLM": true,
      "EnableJWT": true,
      "EnableBasic": true
    }
  }
}

Configuration Options:

Setting Default Description
AcceptAllCredentials true Accept any username/password (testing mode)
AllowAnonymous true Allow requests without credentials
EnableNTLM true Enable Windows NTLM authentication
EnableJWT true Enable Bearer token (JWT) authentication
EnableBasic true Enable Basic authentication

Security Note: For production-like testing, set AcceptAllCredentials: false and AllowAnonymous: false.


Generic Authentication (Testing Mode)

When AcceptAllCredentials: true, the server accepts any credentials without validation. This is ideal for development and testing environments.

C# CSOM Example

using Microsoft.SharePoint.Client;

// Any username/password will work
var ctx = new ClientContext("http://localhost:5000");
ctx.Credentials = new System.Net.NetworkCredential("testuser", "password");

ctx.Load(ctx.Web);
ctx.ExecuteQuery();
Console.WriteLine($"Connected to: {ctx.Web.Title}");

PowerShell PnP Example

# Any credentials work
$creds = New-Object PSCredential("testuser", (ConvertTo-SecureString "password" -AsPlainText -Force))
Connect-PnPOnline -Url "http://localhost:5000" -Credentials $creds

$web = Get-PnPWeb
Write-Host "Connected to: $($web.Title)"

REST API Example (Basic Auth Header)

# Base64 encode "username:password"
curl -X GET "http://localhost:5000/_api/web" \
  -H "Authorization: Basic dGVzdHVzZXI6cGFzc3dvcmQ=" \
  -H "Accept: application/json"
// JavaScript/TypeScript
const headers = {
  'Authorization': 'Basic ' + btoa('testuser:password'),
  'Accept': 'application/json'
};

fetch('http://localhost:5000/_api/web', { headers })
  .then(r => r.json())
  .then(data => console.log('Web Title:', data.d.Title));

Basic Authentication

Standard HTTP Basic Authentication with username and password.

Configuration

{
  "Cesivi": {
    "Authentication": {
      "AcceptAllCredentials": false,
      "EnableBasic": true
    }
  }
}

C# CSOM Example

using Microsoft.SharePoint.Client;

var ctx = new ClientContext("http://localhost:5000");
ctx.Credentials = new System.Net.NetworkCredential("jdoe", "SecurePassword123");

ctx.Load(ctx.Web);
ctx.ExecuteQuery();

C# REST API Example

using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;

var client = new HttpClient();
var credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes("jdoe:SecurePassword123"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", credentials);

var response = await client.GetAsync("http://localhost:5000/_api/web");
var json = await response.Content.ReadAsStringAsync();

PowerShell Example

# Using PnP
$creds = Get-Credential  # Enter username/password
Connect-PnPOnline -Url "http://localhost:5000" -Credentials $creds

# Using REST directly
$user = "jdoe"
$pass = "SecurePassword123"
$pair = "$($user):$($pass)"
$bytes = [System.Text.Encoding]::ASCII.GetBytes($pair)
$base64 = [System.Convert]::ToBase64String($bytes)
$headers = @{
    Authorization = "Basic $base64"
}
Invoke-RestMethod -Uri "http://localhost:5000/_api/web" -Headers $headers

NTLM Authentication (Windows Integrated)

Windows NTLM authentication for domain-joined environments.

Configuration

{
  "Cesivi": {
    "Authentication": {
      "AcceptAllCredentials": false,
      "EnableNTLM": true
    }
  }
}

C# CSOM Example

using Microsoft.SharePoint.Client;

var ctx = new ClientContext("http://localhost:5000");

// Use current Windows credentials
ctx.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;

// OR specify domain credentials
ctx.Credentials = new System.Net.NetworkCredential("jdoe", "password", "CONTOSO");

ctx.Load(ctx.Web);
ctx.ExecuteQuery();

C# REST API Example

using System.Net;
using System.Net.Http;

var handler = new HttpClientHandler
{
    Credentials = CredentialCache.DefaultNetworkCredentials,
    PreAuthenticate = true
};

var client = new HttpClient(handler);
var response = await client.GetAsync("http://localhost:5000/_api/web");
var json = await response.Content.ReadAsStringAsync();

PowerShell Example

# Using current Windows credentials
Connect-PnPOnline -Url "http://localhost:5000" -CurrentCredentials

# Using specific domain credentials
$creds = Get-Credential -Message "Enter domain credentials"
Connect-PnPOnline -Url "http://localhost:5000" -Credentials $creds

Bearer Token (JWT) Authentication

Modern OAuth-style authentication using Bearer tokens.

Configuration

{
  "Cesivi": {
    "Authentication": {
      "AcceptAllCredentials": false,
      "EnableJWT": true
    }
  }
}

C# REST API Example

using System.Net.Http;
using System.Net.Http.Headers;

var client = new HttpClient();
var token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...";  // Your JWT token
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);

var response = await client.GetAsync("http://localhost:5000/_api/web");
var json = await response.Content.ReadAsStringAsync();

JavaScript/TypeScript Example

const token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...';

const headers = {
  'Authorization': `Bearer ${token}`,
  'Accept': 'application/json'
};

fetch('http://localhost:5000/_api/web', { headers })
  .then(r => r.json())
  .then(data => console.log('Web Title:', data.d.Title));

PowerShell Example

$token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
$headers = @{
    Authorization = "Bearer $token"
    Accept = "application/json"
}

Invoke-RestMethod -Uri "http://localhost:5000/_api/web" -Headers $headers

Cookie-based authentication similar to SharePoint Online.

Configuration

{
  "Cesivi": {
    "Authentication": {
      "AcceptAllCredentials": false,
      "EnableBasic": true
    }
  }
}

C# CSOM Example

using Microsoft.SharePoint.Client;

var ctx = new ClientContext("http://localhost:5000");

// Forms-based authentication (cookie)
var authCookie = new System.Net.Cookie("FedAuth", "cookie-value", "/", "localhost");
ctx.Credentials = new System.Net.CookieContainer();
((System.Net.CookieContainer)ctx.Credentials).Add(authCookie);

ctx.Load(ctx.Web);
ctx.ExecuteQuery();

JavaScript Example (Browser)

// After successful login, cookie is automatically included
fetch('http://localhost:5000/_api/web', {
  credentials: 'include',  // Include cookies
  headers: {
    'Accept': 'application/json'
  }
})
.then(r => r.json())
.then(data => console.log('Web Title:', data.d.Title));

Anonymous Access

Allow requests without any credentials (for testing only).

Configuration

{
  "Cesivi": {
    "Authentication": {
      "AllowAnonymous": true
    }
  }
}

C# REST API Example

using System.Net.Http;

var client = new HttpClient();
// No credentials needed
var response = await client.GetAsync("http://localhost:5000/_api/web");
var json = await response.Content.ReadAsStringAsync();

JavaScript Example

// No authentication headers needed
fetch('http://localhost:5000/_api/web')
  .then(r => r.json())
  .then(data => console.log('Web Title:', data.d.Title));

Security Warning: Only use anonymous access in development environments. Disable for production-like testing.


User Context Resolution

When authentication is successful, the server resolves the user context from credentials.

How User Context Works

  1. Extract Username: From credentials (Basic, NTLM, JWT)
  2. Resolve Identity: Check Active Directory mock data, then SharePoint users
  3. Set Current User: Associate request with resolved user identity
  4. Apply Permissions: Use ACL service to check effective permissions

Example User Resolution

// Client authenticates with username "jdoe"
ctx.Credentials = new System.Net.NetworkCredential("jdoe", "password");

// Server resolves user context:
// 1. Checks AD mock storage for "jdoe" (sAMAccountName, UPN, DN)
// 2. If found in AD, maps to SharePoint user
// 3. If not in AD, checks SharePoint users directly
// 4. Sets ctx.Web.CurrentUser to resolved user

Accessing Current User

// C# CSOM
ctx.Load(ctx.Web.CurrentUser);
ctx.ExecuteQuery();
Console.WriteLine($"Current User: {ctx.Web.CurrentUser.Title}");
Console.WriteLine($"Email: {ctx.Web.CurrentUser.Email}");
# PowerShell PnP
$currentUser = Get-PnPWeb | Select-Object -ExpandProperty CurrentUser
Write-Host "Current User: $($currentUser.Title)"
# REST API
curl -X GET "http://localhost:5000/_api/web/currentuser" \
  -H "Authorization: Basic dGVzdHVzZXI6cGFzc3dvcmQ=" \
  -H "Accept: application/json"

Active Directory Integration

The server can resolve users and groups from Active Directory mock data.

AD Configuration File

Create or modify MockData/ActiveDirectory/identities.json:

{
  "Users": [
    {
      "DistinguishedName": "CN=John Doe,OU=Users,DC=contoso,DC=com",
      "SamAccountName": "jdoe",
      "UserPrincipalName": "jdoe@contoso.com",
      "DisplayName": "John Doe",
      "Email": "jdoe@contoso.com",
      "Department": "IT",
      "MemberOf": [
        "CN=IT Admins,OU=Groups,DC=contoso,DC=com"
      ]
    }
  ],
  "Groups": [
    {
      "DistinguishedName": "CN=IT Admins,OU=Groups,DC=contoso,DC=com",
      "SamAccountName": "IT Admins",
      "DisplayName": "IT Administrators",
      "Members": [
        "CN=John Doe,OU=Users,DC=contoso,DC=com"
      ]
    }
  ]
}

Authentication with AD Users

// Authenticate as AD user
ctx.Credentials = new System.Net.NetworkCredential("jdoe", "password");

// OR use UPN
ctx.Credentials = new System.Net.NetworkCredential("jdoe@contoso.com", "password");

// OR use DN
ctx.Credentials = new System.Net.NetworkCredential("CN=John Doe,OU=Users,DC=contoso,DC=com", "password");

// Server resolves "jdoe" to AD user, maps to SharePoint user
ctx.Load(ctx.Web.CurrentUser);
ctx.ExecuteQuery();
Console.WriteLine($"Current User: {ctx.Web.CurrentUser.Title}");  // "John Doe"

See Permissions Guide for complete AD integration details.


Security Considerations

Development vs. Production

Development/Testing: - ✅ Use AcceptAllCredentials: true - ✅ Use AllowAnonymous: true - ✅ No SSL/TLS required - ✅ Any credentials work

Production-Like Testing: - ⚠️ Set AcceptAllCredentials: false - ⚠️ Set AllowAnonymous: false - ⚠️ Enable HTTPS (UseHttps: true) - ⚠️ Use real AD users or valid test accounts - ⚠️ Configure certificate validation

HTTPS Configuration

{
  "Cesivi": {
    "UseHttps": true,
    "HttpsPort": 5001
  },
  "Kestrel": {
    "Certificate": {
      "Path": "certificate.pfx",
      "Password": "YourPassword",
      "AllowInvalid": false
    }
  }
}

Certificate Validation Bypass (Development Only)

// C# - Bypass certificate validation for self-signed certs (DEV ONLY)
ServicePointManager.ServerCertificateValidationCallback =
    (sender, cert, chain, sslPolicyErrors) => true;

var ctx = new ClientContext("https://localhost:5001");
ctx.Credentials = new System.Net.NetworkCredential("testuser", "password");
# PowerShell - Skip certificate checks (DEV ONLY)
[Net.ServicePointManager]::ServerCertificateValidationCallback = {$true}

Connect-PnPOnline -Url "https://localhost:5001" -Credentials (Get-Credential)

Warning: Never disable certificate validation in production environments.


Troubleshooting

Error: 401 Unauthorized

Symptom:

The remote server returned an error: (401) Unauthorized

Solutions: 1. Verify AcceptAllCredentials: true in appsettings.json 2. Check username/password are provided 3. Verify authentication method is enabled (EnableBasic, EnableNTLM, etc.) 4. Check server logs for authentication errors

# Check server logs
tail -f MockData/Logs/Server/cesivi-*.log | grep -i auth

Error: Cannot contact site

Symptom:

Cannot contact site at the specified URL http://localhost:5000

Solutions: 1. Wait 5-10 seconds after server startup 2. Verify server is running: curl http://localhost:5000/health 3. Check firewall settings 4. Verify URL and port are correct

Error: 403 Forbidden

Symptom:

The remote server returned an error: (403) Forbidden

Solutions: 1. User authenticated but lacks permissions 2. Check user's group memberships 3. Verify permission assignments on resource 4. Enable AllowAnonymous: true for testing

NTLM Authentication Not Working

Symptom:

NTLM authentication failed

Solutions: 1. Verify EnableNTLM: true in appsettings.json 2. Use domain credentials: new NetworkCredential("user", "pass", "DOMAIN") 3. Set PreAuthenticate: true on HttpClientHandler 4. Check CSOM client has NTLM support enabled

// Enable NTLM in CSOM client
var ctx = new ClientContext("http://localhost:5000");
ctx.Credentials = new System.Net.NetworkCredential("user", "pass", "DOMAIN");
ctx.ExecutingWebRequest += (sender, e) =>
{
    e.WebRequestExecutor.RequestHeaders["X-FORMS_BASED_AUTH_ACCEPTED"] = "f";
};

Complete Authentication Examples

Multi-Method Authentication (C#)

using Microsoft.SharePoint.Client;
using System;
using System.Net;

public class SharePointAuthExample
{
    private static ClientContext GetContext(string url, AuthMethod method)
    {
        var ctx = new ClientContext(url);

        switch (method)
        {
            case AuthMethod.Generic:
                // Any credentials work (testing mode)
                ctx.Credentials = new NetworkCredential("testuser", "password");
                break;

            case AuthMethod.Basic:
                // Username/password
                ctx.Credentials = new NetworkCredential("jdoe", "SecurePassword123");
                break;

            case AuthMethod.NTLM:
                // Windows integrated auth
                ctx.Credentials = CredentialCache.DefaultNetworkCredentials;
                // OR domain credentials:
                // ctx.Credentials = new NetworkCredential("jdoe", "password", "CONTOSO");
                break;

            case AuthMethod.Anonymous:
                // No credentials
                ctx.Credentials = null;
                break;
        }

        return ctx;
    }

    public static void Main()
    {
        var ctx = GetContext("http://localhost:5000", AuthMethod.Generic);

        ctx.Load(ctx.Web);
        ctx.Load(ctx.Web.CurrentUser);
        ctx.ExecuteQuery();

        Console.WriteLine($"Web Title: {ctx.Web.Title}");
        Console.WriteLine($"Current User: {ctx.Web.CurrentUser.Title}");
    }
}

public enum AuthMethod
{
    Generic,
    Basic,
    NTLM,
    Anonymous
}

PowerShell Authentication Script

# Function to connect with different auth methods
function Connect-Cesivi {
    param(
        [Parameter(Mandatory=$true)]
        [string]$Url,

        [Parameter(Mandatory=$true)]
        [ValidateSet('Generic', 'Basic', 'NTLM', 'CurrentUser')]
        [string]$AuthMethod
    )

    switch ($AuthMethod) {
        'Generic' {
            # Any credentials work (testing mode)
            $creds = New-Object PSCredential("testuser", (ConvertTo-SecureString "password" -AsPlainText -Force))
            Connect-PnPOnline -Url $Url -Credentials $creds
        }
        'Basic' {
            # Prompt for credentials
            $creds = Get-Credential -Message "Enter Basic Auth credentials"
            Connect-PnPOnline -Url $Url -Credentials $creds
        }
        'NTLM' {
            # Prompt for domain credentials
            $creds = Get-Credential -Message "Enter domain credentials"
            Connect-PnPOnline -Url $Url -Credentials $creds
        }
        'CurrentUser' {
            # Use current Windows credentials
            Connect-PnPOnline -Url $Url -CurrentCredentials
        }
    }

    # Verify connection
    $web = Get-PnPWeb
    Write-Host "Connected to: $($web.Title)" -ForegroundColor Green
}

# Usage examples
Connect-Cesivi -Url "http://localhost:5000" -AuthMethod Generic
Connect-Cesivi -Url "http://localhost:5000" -AuthMethod Basic
Connect-Cesivi -Url "http://localhost:5000" -AuthMethod CurrentUser

Features

Setup

Troubleshooting


Last Updated: November 15, 2025 Version: 1.0.0

Navigation: Home | Documentation | Features | Authentication