KerberosCCache 1.0.0

dotnet add package KerberosCCache --version 1.0.0
                    
NuGet\Install-Package KerberosCCache -Version 1.0.0
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="KerberosCCache" Version="1.0.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="KerberosCCache" Version="1.0.0" />
                    
Directory.Packages.props
<PackageReference Include="KerberosCCache" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add KerberosCCache --version 1.0.0
                    
#r "nuget: KerberosCCache, 1.0.0"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package KerberosCCache@1.0.0
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=KerberosCCache&version=1.0.0
                    
Install as a Cake Addin
#tool nuget:?package=KerberosCCache&version=1.0.0
                    
Install as a Cake Tool

KerberosCCache

A lightweight .NET utility to dynamically set the KRB5CCNAME environment variable at runtime on Linux for Kerberos authentication.

Overview

The KerberosCCache NuGet package provides a safe and efficient way to programmatically set the KRB5CCNAME environment variable in .NET applications running on Linux. This variable tells Kerberos-aware tools (like kinit, curl, or .NET’s HttpClient with SPNEGO) where to find the Kerberos credentials cache (ticket file).

This is especially useful in containerized or server-side scenarios where your application needs to:

  • Impersonate different users,
  • Manage multiple Kerberos identities,
  • Switch tickets dynamically (e.g., per HTTP request in a reverse-proxy setup).

⚠️ Only supported on Linux. Windows and macOS use native authentication mechanisms and do not rely on KRB5CCNAME.


Limitations & Known Issues

Platform Support Notes
Linux ✅ Yes Fully supported via libc's setenv.
Windows ❌ No Throws PlatformNotSupportedException. Uses SSPI instead.
macOS ❌ No Throws PlatformNotSupportedException. Uses KCM by default.

Known Limitations:

  • Only affects the current process and its child processes—does not modify the parent shell’s environment.
  • Requires read access to the specified cache file path.
  • Does not validate whether the cache file exists or is valid—only sets the environment variable.

⚠️ On non-Linux platforms, Kerberos authentication uses native mechanisms (SSPI on Windows, KCM on macOS) and ignores KRB5CCNAME. This package is not applicable outside Linux.


Getting Started

1. Install the Package

Install via the .NET CLI:


dotnet add package KerberosCCache

Or via Package Manager Console:

Install-Package KerberosCCache

2. Use in Your Code

Add the namespace and call the static method:

using KerberosCCache;

// Set the Kerberos credentials cache path
KerberosCache.SetKrb5Cache("/tmp/krb5cc_1000");

That’s it! Your application (and any child processes) will now use the specified Kerberos ticket cache.


Visual Guide

Typical workflow in a Linux container:

+---------------------+
| .NET App (Linux)    |
|                     |
| Calls:              |
| SetKrb5Cache(...)   |
+----------+----------+
           |
           v
+---------------------+
| Environment Variable|
| KRB5CCNAME = /tmp/...|
+----------+----------+
           |
           v
+---------------------+
| Kerberos Client     |
| (e.g., curl, kinit) |
| Uses ticket from    |
| specified cache     |
+---------------------+

Examples

Example 1: Basic Usage

try
{
    KerberosCache.SetKrb5Cache("/tmp/krb5cc_custom");
    Console.WriteLine("KRB5CCNAME set successfully.");
}
catch (PlatformNotSupportedException ex)
{
    Console.WriteLine($"Platform not supported: {ex.Message}");
}
catch (InvalidOperationException ex)
{
    Console.WriteLine($"Failed to set KRB5CCNAME: {ex.Message}");
}

Example 2: Avoid Overwriting Existing Value

// Only set if KRB5CCNAME is not already defined
KerberosCache.SetKrb5Cache("/tmp/krb5cc_backup", overwrite: false);

🔒 The overwrite parameter maps directly to the overwrite argument in the underlying setenv() C function (1 = overwrite, 0 = do not overwrite).


Sample Project Snippet

This is an example of a minimal ASP.NET Core application that uses KerberosCCache to dynamically switch Kerberos credentials per HTTP request—ideal for reverse-proxy authentication (e.g., Apache + mod_auth_kerb or nginx + SPNEGO).

⚠️ Important: For Kerberos delegation to work end-to-end, the client browser must be configured to allow credential delegation to your service domain.

Browser Configuration (Firefox Example)

In Firefox, users (or administrators) must configure the following settings in about:config:

PREFERENCE VALUE PURPOSE
network.negotiate-auth.trusted-uris .example.com Enables SPNEGO (Kerberos) authentication for the domain.
network.negotiate-auth.delegation-uris .example.com Allows the browser to delegate the user’s Kerberos ticket to the server (required for impersonation).

Application Code

using System;
using Npgsql;
using KerberosCCache;

public class Program
{
    public static void Main(string[] args)
    {
        var builder = WebApplication.CreateBuilder(args);
        var app = builder.Build();

        // Map a secure endpoint that uses Kerberos delegation
        app.MapGet("/api/data", async(HttpContext context) => await GetDataAsync(context));
        app.Run();
    }

    /// <summary>
    /// Handles an authenticated request by switching to the user's Kerberos ticket cache
    /// and connecting to a PostgreSQL database using GSSAPI (Kerberos) authentication.
    /// </summary>
    /// <param name="context">The current HTTP context.</param>

    public static async Task GetDataAsync(HttpContext context)
    {

        // ⚠️ SECURITY:
        // These headers (X_KRB5CCNAME, X_GSS_NAME) must ONLY be set by a trusted reverse proxy
        // (e.g., Apache with mod_auth_kerb or nginx with SPNEGO module).
        // Never accept them from untrusted clients!

        // Get user's credential cache (KRB5CCNAME) and username from headers

        if (!context.Request.Headers.TryGetValue("X_KRB5CCNAME", out var krb5ccname) ||
            !context.Request.Headers.TryGetValue("X_GSS_NAME", out var gssName))
        {
            context.Response.StatusCode = 400;
            await context.Response.WriteAsync("Missing auth headers.");
            return;
        }

        try
        {
            // Dynamically set KRB5CCNAME (user's credential cache) for the current process
            // This affects all subsequent Kerberos operations in this process

            KerberosCache.SetKrb5Cache(krb5_path);

            // Connect to PostgreSQL using GSSAPI (Kerberos) authentication
            // 'Include Realm=true' ensures the realm is used during auth

            string cs = $"Host=my.example.com;Database=postgres;Include Realm=true;Username={user};";

            using var con = new NpgsqlConnection(cs);

            await con.OpenAsync();
            ...
        }
        catch (Exception ex)
        {
	        ...
        }
        finally
        {
            con.Close();
            ...
        }
}

Required Packages (*.csproj)

<PackageReference Include="KerberosCCache" Version="1.0.0" />
<PackageReference Include="Npgsql" Version="7.0.0" />
<PackageReference Include="Microsoft.AspNetCore.App" Version="7.0.0" />

Important Security & Deployment Notes

  1. Trusted Headers Only

The headers X_KRB5CCNAME and X_GSS_NAME must be injected by a trusted reverse proxy (e.g., Apache with mod_auth_kerb or mod_auth_gssapi). Never allow end-users to set these directly.

  1. Thread Safety

Since KRB5CCNAME is a process-wide environment variable, changing it affects all threads in the application. → This example assumes one request at a time or that all concurrent requests belong to the same user. → For true multi-tenancy, consider:

  • Using separate processes per user (e.g., via gunicorn-style workers), or
  • Leveraging Kerberos impersonation with constrained delegation (advanced).
  1. File Permissions

Ensure the .NET process has read access to the Kerberos cache file (e.g., /tmp/krb5cc_XXXX).

  1. Linux Only This will fail on Windows/macOS with PlatformNotSupportedException. Deploy only on Linux.

Additional Resources

Product Compatible and additional computed target framework versions.
.NET net6.0 is compatible.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 is compatible.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 is compatible.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 is compatible.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 is compatible.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.
  • net10.0

    • No dependencies.
  • net6.0

    • No dependencies.
  • net7.0

    • No dependencies.
  • net8.0

    • No dependencies.
  • net9.0

    • No dependencies.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
1.0.0 209 10/8/2025