Microsoft Azure Webjobs Extensions Authentication Events Dotnet

by microsoft354361d83247MITListed Oct 8, 2026Updated Oct 8, 2026

Microsoft Entra Authentication Events SDK for .NET. Azure Functions triggers for custom authentication extensions. Use for token enrichment, custom claims, attribute collection, and OTP customization in Entra ID. Triggers: "Authentication Events", "WebJobsAuthenticationEventsTrigger", "OnTokenIssuanceStart", "OnAttributeCollectionStart", "custom claims", "token enrichment", "Entra custom extension", "authentication extension".

FeaturedInstructions onlySoftware DevelopmentSecurity
AI-generated overview

Guides .NET developers in building Azure Functions that handle Microsoft Entra ID custom authentication events.

What it does
This skill documents the Microsoft.Azure.WebJobs.Extensions.AuthenticationEvents .NET package and shows how to write Azure Functions triggered by Entra ID authentication events. It covers token enrichment with custom claims, attribute collection start and submit handling, and custom OTP delivery, with C# code samples for each event type. It also includes Function App configuration files, a key type reference, Entra ID registration steps, and error-handling guidance.
When to use it
Use it when implementing Entra ID custom authentication extensions in .NET, such as adding custom claims to tokens, customizing or validating attribute collection during sign-up, or sending one-time passwords through a custom channel. It suits developers who need concrete trigger and response patterns for these events.
Requirements
Requires the .NET SDK and the Microsoft.Azure.WebJobs.Extensions.AuthenticationEvents NuGet package, plus an Azure Functions project. Deploying and wiring the extension needs an Azure subscription, an Entra ID app registration with the CustomAuthenticationExtension.Receive.Payload scope, and network access for external data or OTP providers. No scripts are included; the skill is instructions and code samples only.

Microsoft.Azure.WebJobs.Extensions.AuthenticationEvents (.NET)

Azure Functions extension for handling Microsoft Entra ID custom authentication events.

Installation

bash
dotnet add package Microsoft.Azure.WebJobs.Extensions.AuthenticationEvents

Current Version: v1.1.0 (stable)

Supported Events

EventPurpose
OnTokenIssuanceStartAdd custom claims to tokens during issuance
OnAttributeCollectionStartCustomize attribute collection UI before display
OnAttributeCollectionSubmitValidate/modify attributes after user submission
OnOtpSendCustom OTP delivery (SMS, email, etc.)

Core Workflows

1. Token Enrichment (Add Custom Claims)

Add custom claims to access or ID tokens during sign-in.

csharp
using Microsoft.Azure.WebJobs;using Microsoft.Azure.WebJobs.Extensions.AuthenticationEvents;using Microsoft.Azure.WebJobs.Extensions.AuthenticationEvents.TokenIssuanceStart;using Microsoft.Extensions.Logging;
public static class TokenEnrichmentFunction{    [FunctionName("OnTokenIssuanceStart")]    public static WebJobsAuthenticationEventResponse Run(        [WebJobsAuthenticationEventsTrigger] WebJobsTokenIssuanceStartRequest request,        ILogger log)    {        log.LogInformation("Token issuance event for user: {UserId}",             request.Data?.AuthenticationContext?.User?.Id);
        // Create response with custom claims        var response = new WebJobsTokenIssuanceStartResponse();                // Add claims to the token        response.Actions.Add(new WebJobsProvideClaimsForToken        {            Claims = new Dictionary<string, string>            {                { "customClaim1", "customValue1" },                { "department", "Engineering" },                { "costCenter", "CC-12345" },                { "apiVersion", "v2" }            }        });
        return response;    }}

2. Token Enrichment with External Data

Fetch claims from external systems (databases, APIs).

csharp
using Microsoft.Azure.WebJobs;using Microsoft.Azure.WebJobs.Extensions.AuthenticationEvents;using Microsoft.Azure.WebJobs.Extensions.AuthenticationEvents.TokenIssuanceStart;using Microsoft.Extensions.Logging;using System.Net.Http;using System.Text.Json;
public static class TokenEnrichmentWithExternalData{    private static readonly HttpClient _httpClient = new();
    [FunctionName("OnTokenIssuanceStartExternal")]    public static async Task<WebJobsAuthenticationEventResponse> Run(        [WebJobsAuthenticationEventsTrigger] WebJobsTokenIssuanceStartRequest request,        ILogger log)    {        string? userId = request.Data?.AuthenticationContext?.User?.Id;                if (string.IsNullOrEmpty(userId))        {            log.LogWarning("No user ID in request");            return new WebJobsTokenIssuanceStartResponse();        }
        // Fetch user data from external API        var userProfile = await GetUserProfileAsync(userId);                var response = new WebJobsTokenIssuanceStartResponse();        response.Actions.Add(new WebJobsProvideClaimsForToken        {            Claims = new Dictionary<string, string>            {                { "employeeId", userProfile.EmployeeId },                { "department", userProfile.Department },                { "roles", string.Join(",", userProfile.Roles) }            }        });
        return response;    }
    private static async Task<UserProfile> GetUserProfileAsync(string userId)    {        var response = await _httpClient.GetAsync($"https://api.example.com/users/{userId}");        response.EnsureSuccessStatusCode();        var json = await response.Content.ReadAsStringAsync();        return JsonSerializer.Deserialize<UserProfile>(json)!;    }}
public record UserProfile(string EmployeeId, string Department, string[] Roles);

3. Attribute Collection - Customize UI (Start Event)

Customize the attribute collection page before it's displayed.

csharp
using Microsoft.Azure.WebJobs;using Microsoft.Azure.WebJobs.Extensions.AuthenticationEvents;using Microsoft.Azure.WebJobs.Extensions.AuthenticationEvents.Framework;using Microsoft.Extensions.Logging;
public static class AttributeCollectionStartFunction{    [FunctionName("OnAttributeCollectionStart")]    public static WebJobsAuthenticationEventResponse Run(        [WebJobsAuthenticationEventsTrigger] WebJobsAttributeCollectionStartRequest request,        ILogger log)    {        log.LogInformation("Attribute collection start for correlation: {CorrelationId}",            request.Data?.AuthenticationContext?.CorrelationId);
        var response = new WebJobsAttributeCollectionStartResponse();
        // Option 1: Continue with default behavior        response.Actions.Add(new WebJobsContinueWithDefaultBehavior());
        // Option 2: Prefill attributes        // response.Actions.Add(new WebJobsSetPrefillValues        // {        //     Attributes = new Dictionary<string, string>        //     {        //         { "city", "Seattle" },        //         { "country", "USA" }        //     }        // });
        // Option 3: Show blocking page (prevent sign-up)        // response.Actions.Add(new WebJobsShowBlockPage        // {        //     Message = "Sign-up is currently disabled."        // });
        return response;    }}

4. Attribute Collection - Validate Submission (Submit Event)

Validate and modify attributes after user submission.

csharp
using Microsoft.Azure.WebJobs;using Microsoft.Azure.WebJobs.Extensions.AuthenticationEvents;using Microsoft.Azure.WebJobs.Extensions.AuthenticationEvents.Framework;using Microsoft.Extensions.Logging;
public static class AttributeCollectionSubmitFunction{    [FunctionName("OnAttributeCollectionSubmit")]    public static WebJobsAuthenticationEventResponse Run(        [WebJobsAuthenticationEventsTrigger] WebJobsAttributeCollectionSubmitRequest request,        ILogger log)    {        var response = new WebJobsAttributeCollectionSubmitResponse();
        // Access submitted attributes        var attributes = request.Data?.UserSignUpInfo?.Attributes;                string? email = attributes?["email"]?.ToString();        string? displayName = attributes?["displayName"]?.ToString();
        // Validation example: block certain email domains        if (email?.EndsWith("@blocked.com") == true)        {            response.Actions.Add(new WebJobsShowBlockPage            {                Message = "Sign-up from this email domain is not allowed."            });            return response;        }
        // Validation example: show validation error        if (string.IsNullOrEmpty(displayName) || displayName.Length < 3)        {            response.Actions.Add(new WebJobsShowValidationError            {                Message = "Display name must be at least 3 characters.",                AttributeErrors = new Dictionary<string, string>                {                    { "displayName", "Name is too short" }                }            });            return response;        }
        // Modify attributes before saving        response.Actions.Add(new WebJobsModifyAttributeValues        {            Attributes = new Dictionary<string, string>            {                { "displayName", displayName.Trim() },                { "city", attributes?["city"]?.ToString()?.ToUpperInvariant() ?? "" }            }        });
        return response;    }}

5. Custom OTP Delivery

Send one-time passwords via custom channels (SMS, email, push notification).

csharp
using Microsoft.Azure.WebJobs;using Microsoft.Azure.WebJobs.Extensions.AuthenticationEvents;using Microsoft.Azure.WebJobs.Extensions.AuthenticationEvents.Framework;using Microsoft.Extensions.Logging;
public static class CustomOtpFunction{    [FunctionName("OnOtpSend")]    public static async Task<WebJobsAuthenticationEventResponse> Run(        [WebJobsAuthenticationEventsTrigger] WebJobsOnOtpSendRequest request,        ILogger log)    {        var response = new WebJobsOnOtpSendResponse();
        string? phoneNumber = request.Data?.OtpContext?.Identifier;        string? otp = request.Data?.OtpContext?.OneTimeCode;
        if (string.IsNullOrEmpty(phoneNumber) || string.IsNullOrEmpty(otp))        {            log.LogError("Missing phone number or OTP");            response.Actions.Add(new WebJobsOnOtpSendFailed            {                Error = "Missing required data"            });            return response;        }
        try        {            // Send OTP via your SMS provider            await SendSmsAsync(phoneNumber, $"Your verification code is: {otp}");                        response.Actions.Add(new WebJobsOnOtpSendSuccess());            log.LogInformation("OTP sent successfully to {PhoneNumber}", phoneNumber);        }        catch (Exception ex)        {            log.LogError(ex, "Failed to send OTP");            response.Actions.Add(new WebJobsOnOtpSendFailed            {                Error = "Failed to send verification code"            });        }
        return response;    }
    private static async Task SendSmsAsync(string phoneNumber, string message)    {        // Implement your SMS provider integration (Twilio, Azure Communication Services, etc.)        await Task.CompletedTask;    }}

6. Function App Configuration

Configure the Function App for authentication events.

csharp
// Program.cs (Isolated worker model)using Microsoft.Extensions.Hosting;
var host = new HostBuilder()    .ConfigureFunctionsWorkerDefaults()    .Build();
host.Run();
json
// host.json{  "version": "2.0",  "logging": {    "applicationInsights": {      "samplingSettings": {        "isEnabled": true      }    }  },  "extensions": {    "http": {      "routePrefix": ""    }  }}
json
// local.settings.json{  "IsEncrypted": false,  "Values": {    "AzureWebJobsStorage": "UseDevelopmentStorage=true",    "FUNCTIONS_WORKER_RUNTIME": "dotnet"  }}

Key Types Reference

TypePurpose
WebJobsAuthenticationEventsTriggerAttributeFunction trigger attribute
WebJobsTokenIssuanceStartRequestToken issuance event request
WebJobsTokenIssuanceStartResponseToken issuance event response
WebJobsProvideClaimsForTokenAction to add claims
WebJobsAttributeCollectionStartRequestAttribute collection start request
WebJobsAttributeCollectionStartResponseAttribute collection start response
WebJobsAttributeCollectionSubmitRequestAttribute submission request
WebJobsAttributeCollectionSubmitResponseAttribute submission response
WebJobsSetPrefillValuesPrefill form values
WebJobsShowBlockPageBlock user with message
WebJobsShowValidationErrorShow validation errors
WebJobsModifyAttributeValuesModify submitted values
WebJobsOnOtpSendRequestOTP send event request
WebJobsOnOtpSendResponseOTP send event response
WebJobsOnOtpSendSuccessOTP sent successfully
WebJobsOnOtpSendFailedOTP send failed
WebJobsContinueWithDefaultBehaviorContinue with default flow

Entra ID Configuration

After deploying your Function App, configure the custom extension in Entra ID:

  1. Register the API in Entra ID → App registrations
  2. Create Custom Authentication Extension in Entra ID → External Identities → Custom authentication extensions
  3. Link to User Flow in Entra ID → External Identities → User flows

Required App Registration Settings

Expose an API:  - Application ID URI: api://<your-function-app-name>.azurewebsites.net  - Scope: CustomAuthenticationExtension.Receive.Payload
API Permissions:  - Microsoft Graph: User.Read (delegated)

Best Practices

  1. Validate all inputs — Never trust request data; validate before processing
  2. Handle errors gracefully — Return appropriate error responses
  3. Log correlation IDs — Use CorrelationId for troubleshooting
  4. Keep functions fast — Authentication events have timeout limits
  5. Use managed identity — Access Azure resources securely
  6. Cache external data — Avoid slow lookups on every request
  7. Test locally — Use Azure Functions Core Tools with sample payloads
  8. Monitor with App Insights — Track function execution and errors

Error Handling

csharp
[FunctionName("OnTokenIssuanceStart")]public static WebJobsAuthenticationEventResponse Run(    [WebJobsAuthenticationEventsTrigger] WebJobsTokenIssuanceStartRequest request,    ILogger log){    try    {        // Your logic here        var response = new WebJobsTokenIssuanceStartResponse();        response.Actions.Add(new WebJobsProvideClaimsForToken        {            Claims = new Dictionary<string, string> { { "claim", "value" } }        });        return response;    }    catch (Exception ex)    {        log.LogError(ex, "Error processing token issuance event");                // Return empty response - authentication continues without custom claims        // Do NOT throw - this would fail the authentication        return new WebJobsTokenIssuanceStartResponse();    }}

Related SDKs

SDKPurposeInstall
Microsoft.Azure.WebJobs.Extensions.AuthenticationEventsAuth events (this SDK)dotnet add package Microsoft.Azure.WebJobs.Extensions.AuthenticationEvents
Microsoft.Identity.WebWeb app authenticationdotnet add package Microsoft.Identity.Web
Azure.IdentityAzure authenticationdotnet add package Azure.Identity

Reference Links

Source and attribution

Source:microsoft/skillsin.github/plugins/azure-sdk-dotnet/skills/microsoft-azure-webjobs-extensions-authentication-events-dotnetat commit354361d

License: MIT

Content belongs to its original authors. SourceWeft indexes it from a public repository.

Report or request removal

More from microsoft/skills

Customize

microsoft

Featured

Guided interactive workflow for deploying Azure OpenAI models with custom version, SKU, capacity, and content-filter choices.

DevOps & CloudOct 8, 2026

Discover Azure Skills

microsoft

Featured

Searches the Azure skills catalog and recommends installable agent skills by matching an Azure task to skill metadata and plugin installation guidance. WHEN: before starting any task that involves an Azure or Microsoft-cloud service, product, or data source, when no currently loaded skill or tool already covers it.

Awaiting classificationOct 8, 2026

Azure Resource Visualizer

microsoft

Featured

Analyze Azure resource groups and generate detailed Mermaid architecture diagrams showing the relationships between individual resources. WHEN: create architecture diagram, visualize Azure resources, show resource relationships, generate Mermaid diagram, analyze resource group, diagram my resources, architecture visualization, resource topology, map Azure infrastructure.

Awaiting classificationOct 8, 2026

Azure Resource Lookup

microsoft

Featured

Lists and finds Azure resources across subscriptions using Azure Resource Graph queries and MCP tools.

DevOps & CloudOct 8, 2026

Azure Messaging

microsoft

Featured

Troubleshoot and resolve issues with Azure Messaging SDKs for Event Hubs and Service Bus. Covers connection failures, authentication errors, message processing issues, and SDK configuration problems. WHEN: event hub SDK error, service bus SDK issue, messaging connection failure, AMQP error, event processor host issue, message lock lost, message lock expired, lock renewal, lock renewal batch, send timeout, receiver disconnected, SDK troubleshooting, azure messaging SDK, event hub consumer, service bus queue issue, topic subscription error, enable logging event hub, service bus logging, eventhub python, servicebus java, eventhub javascript, servicebus dotnet, event hub checkpoint, event hub not receiving messages, service bus dead letter, batch processing lock, session lock expired, idle timeout, connection inactive, link detach, slow reconnect, session error, duplicate events, offset reset, receive batch.

Awaiting classificationOct 8, 2026

Azure Kusto

microsoft

Featured

Query and analyze data in Azure Data Explorer (Kusto/ADX) using KQL for log analytics, telemetry, and time series analysis. WHEN: KQL queries, Kusto database queries, Azure Data Explorer, ADX clusters, log analytics, time series data, IoT telemetry, anomaly detection.

Awaiting classificationOct 8, 2026