opção
LarLar Skill Segurança microsoft-azure-webjobs-extensions-authentication-events-dot

microsoft-azure-webjobs-extensions-authentication-events-dot

microsoft/skills microsoft/skills

Estenda os fluxos de autenticação do Microsoft Entra ID com reivindicações personalizadas, coleta de atributos e entrega de OTP usando gatilhos do Azure Functions.

...Expandir tudo
39
Tempo atualizado 19 de Setembro de 2026

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

Extensão do Azure Functions para manipular eventos de autenticação personalizados do Microsoft Entra ID.

Instalação

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

Versão Atual: v1.1.0 (estável)

Eventos Suportados

EventoFinalidade
`OnTokenIssuanceStart`Adicionar reivindicações personalizadas aos tokens durante a emissão
`OnAttributeCollectionStart`Personalizar a interface de coleta de atributos antes da exibição
`OnAttributeCollectionSubmit`Validar/modificar atributos após o envio pelo usuário
`OnOtpSend`Entrega personalizada de OTP (SMS, e-mail, etc.)

Fluxos de Trabalho Principais

1. Enriquecimento de Token (Adicionar Reivindicações Personalizadas)

Adicione reivindicações personalizadas aos tokens de acesso ou ID durante o login.

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("Evento de emissão de token para o usuário: {UserId}", 
            request.Data?.AuthenticationContext?.User?.Id);

        // Criar resposta com reivindicações personalizadas
        var response = new WebJobsTokenIssuanceStartResponse();

        // Adicionar reivindicações ao token
        response.Actions.Add(new WebJobsProvideClaimsForToken
        {
            Claims = new Dictionary<string>
            {
                { "customClaim1", "customValue1" },
                { "department", "Engineering" },
                { "costCenter", "CC-12345" },
                { "apiVersion", "v2" }
            }
        });

        return response;
    }
}
</string>

2. Enriquecimento de Token com Dados Externos

Busque reivindicações de sistemas externos (bancos de dados, APIs).

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("Nenhum ID de usuário na solicitação");
            return new WebJobsTokenIssuanceStartResponse();
        }

        // Buscar dados do usuário da API externa
        var userProfile = await GetUserProfileAsync(userId);

        var response = new WebJobsTokenIssuanceStartResponse();
        response.Actions.Add(new WebJobsProvideClaimsForToken
        {
            Claims = new Dictionary<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);
</userprofile></userprofile></string></webjobsauthenticationeventresponse>

3. Coleta de Atributos - Personalizar Interface (Evento Inicial)

Personalize a página de coleta de atributos antes que ela seja exibida.

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("Início da coleta de atributos para correlação: {CorrelationId}",
            request.Data?.AuthenticationContext?.CorrelationId);

        var response = new WebJobsAttributeCollectionStartResponse();

        // Opção 1: Continuar com o comportamento padrão
        response.Actions.Add(new WebJobsContinueWithDefaultBehavior());

        // Opção 2: Preencher atributos antecipadamente
        // response.Actions.Add(new WebJobsSetPrefillValues
        // {
        //     Attributes = new Dictionary<string>
        //     {
        //         { "city", "Seattle" },
        //         { "country", "USA" }
        //     }
        // });

        // Opção 3: Exibir página de bloqueio (impedir cadastro)
        // response.Actions.Add(new WebJobsShowBlockPage
        // {
        //     Message = "O cadastro está atualmente desabilitado."
        // });

        return response;
    }
}
</string>

4. Coleta de Atributos - Validar Envio (Evento de Envio)

Valide e modifique os atributos após o envio pelo usuário.

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();

        // Acessar atributos enviados
        var attributes = request.Data?.UserSignUpInfo?.Attributes;

        string? email = attributes?["email"]?.ToString();
        string? displayName = attributes?["displayName"]?.ToString();

        // Exemplo de validação: bloquear certos domínios de e-mail
        if (email?.EndsWith("@blocked.com") == true)
        {
            response.Actions.Add(new WebJobsShowBlockPage
            {
                Message = "Não é permitido o cadastro a partir deste domínio de e-mail."
            });
            return response;
        }

        // Exemplo de validação: exibir erro de validação
        if (string.IsNullOrEmpty(displayName) || displayName.Length 
                {
                    { "displayName", "O nome é muito curto" }
                }
            });
            return response;
        }

        // Modificar atributos antes de salvar
        response.Actions.Add(new WebJobsModifyAttributeValues
        {
            Attributes = new Dictionary<string>
            {
                { "displayName", displayName.Trim() },
                { "city", attributes?["city"]?.ToString()?.ToUpperInvariant() ?? "" }
            }
        });

        return response;
    }
}
</string>

5. Entrega Personalizada de OTP

Envie senhas de uso único (OTP) por canais personalizados (SMS, e-mail, notificação push).

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("Número de telefone ou OTP ausente");
            response.Actions.Add(new WebJobsOnOtpSendFailed
            {
                Error = "Dados obrigatórios ausentes"
            });
            return response;
        }

        try
        {
            // Enviar OTP através do seu provedor de SMS
            await SendSmsAsync(phoneNumber, $"Seu código de verificação é: {otp}");

            response.Actions.Add(new WebJobsOnOtpSendSuccess());
            log.LogInformation("OTP enviado com sucesso para {PhoneNumber}", phoneNumber);
        }
        catch (Exception ex)
        {
            log.LogError(ex, "Falha ao enviar OTP");
            response.Actions.Add(new WebJobsOnOtpSendFailed
            {
                Error = "Falha ao enviar código de verificação"
            });
        }

        return response;
    }

    private static async Task SendSmsAsync(string phoneNumber, string message)
    {
        // Implemente a integração com seu provedor de SMS (Twilio, Serviços de Comunicação do Azure, etc.)
        await Task.CompletedTask;
    }
}
</webjobsauthenticationeventresponse>

6. Configuração do Aplicativo de Funções

Configure o Aplicativo de Funções para eventos de autenticação.

// Program.cs (Modelo de trabalhador isolado)
using Microsoft.Extensions.Hosting;

var host = new HostBuilder()
    .ConfigureFunctionsWorkerDefaults()
    .Build();

host.Run();
// host.json
{
  "version": "2.0",
  "logging": {
    "applicationInsights": {
      "samplingSettings": {
        "isEnabled": true
      }
    }
  },
  "extensions": {
    "http": {
      "routePrefix": ""
    }
  }
}
// local.settings.json
{
  "IsEncrypted": false,
  "Values": {
    "AzureWebJobsStorage": "UseDevelopmentStorage=true",
    "FUNCTIONS_WORKER_RUNTIME": "dotnet"
  }
}

Referência de Tipos Principais

TipoFinalidade
`WebJobsAuthenticationEventsTriggerAttribute`Atributo de acionador de função
`WebJobsTokenIssuanceStartRequest`Solicitação de evento de emissão de token
`WebJobsTokenIssuanceStartResponse`Resposta de evento de emissão de token
`WebJobsProvideClaimsForToken`Ação para adicionar reivindicações
`WebJobsAttributeCollectionStartRequest`Solicitação de início de coleta de atributos
`WebJobsAttributeCollectionStartResponse`Resposta de início de coleta de atributos
`WebJobsAttributeCollectionSubmitRequest`Solicitação de envio de atributos
`WebJobsAttributeCollectionSubmitResponse`Resposta de envio de atributos
`WebJobsSetPrefillValues`Preencher valores do formulário antecipadamente
`WebJobsShowBlockPage`Bloquear usuário com mensagem
`WebJobsShowValidationError`Exibir erros de validação
`WebJobsModifyAttributeValues`Modificar valores enviados
`WebJobsOnOtpSendRequest`Solicitação de evento de envio de OTP
`WebJobsOnOtpSendResponse`Resposta de evento de envio de OTP
`WebJobsOnOtpSendSuccess`OTP enviado com sucesso
`WebJobsOnOtpSendFailed`Falha no envio de OTP
`WebJobsContinueWithDefaultBehavior`Continuar com o fluxo padrão

Configuração do Entra ID

Após implantar seu Aplicativo de Funções, configure a extensão personalizada no Entra ID:

  1. Registre a API no Entra ID → Registros de aplicativos
  2. Crie uma Extensão de Autenticação Personalizada no Entra ID → Identidades externas → Extensões de autenticação personalizadas
  3. Vincule ao Fluxo de Usuário no Entra ID → Identidades externas → Fluxos de usuário

Configurações Necessárias do Registro de Aplicativo

Expor uma API:
  - URI do ID do Aplicativo: api://<nome-do-seu-app-de-funções>.azurewebsites.net
  - Escopo: CustomAuthenticationExtension.Receive.Payload

Permissões da API:
  - Microsoft Graph: User.Read (delegado)
</your-function-app-name>

Melhores Práticas

  1. Valide todas as entradas — Nunca confie nos dados da solicitação; valide antes de processar
  2. Trate erros com graça — Retorne respostas de erro apropriadas
  3. Registre IDs de correlação — Use CorrelationId para solução de problemas
  4. Mantenha as funções rápidas — Eventos de autenticação têm limites de tempo de execução
  5. Use identidade gerenciada — Acesse recursos do Azure com segurança
  6. Armazene dados externos em cache — Evite consultas lentas em cada solicitação
  7. Teste localmente — Use as Ferramentas Principais do Azure Functions com cargas de trabalho de exemplo
  8. Monitore com o App Insights — Acompanhe a execução da função e erros

Manipulação de Erros

[FunctionName("OnTokenIssuanceStart")]
public static WebJobsAuthenticationEventResponse Run(
    [WebJobsAuthenticationEventsTrigger] WebJobsTokenIssuanceStartRequest request,
    ILogger log)
{
    try
    {
        // Sua lógica aqui
        var response = new WebJobsTokenIssuanceStartResponse();
        response.Actions.Add(new WebJobsProvideClaimsForToken
        {
            Claims = new Dictionary<string> { { "claim", "value" } }
        });
        return response;
    }
    catch (Exception ex)
    {
        log.LogError(ex, "Erro ao processar evento de emissão de token");

        // Retorne resposta vazia - a autenticação continua sem reivindicações personalizadas
        // NÃO lance exceções - isso falharia na autenticação
        return new WebJobsTokenIssuanceStartResponse();
    }
}
</string>

SDKs Relacionados

SDKFinalidadeInstalação
`Microsoft.Azure.WebJobs.Extensions.AuthenticationEvents`Eventos de autenticação (este SDK)`dotnet add package Microsoft.Azure.WebJobs.Extensions.AuthenticationEvents`
`Microsoft.Identity.Web`Autenticação de aplicativos web`dotnet add package Microsoft.Identity.Web`
`Azure.Identity`Autenticação do Azure`dotnet add package Azure.Identity`

Links de Referência

RecursoURL
Pacote NuGethttps://www.nuget.org/packages/Microsoft.Azure.WebJobs.Extensions.AuthenticationEvents
Visão Geral de Extensões Personalizadashttps://learn.microsoft.com/entra/identity-platform/custom-extension-overview
Eventos de Emissão de Tokenhttps://learn.microsoft.com/entra/identity-platform/custom-extension-tokenissuancestart-setup
Eventos de Coleta de Atributoshttps://learn.microsoft.com/entra/identity-platform/custom-extension-attribute-collection
Código Fonte no GitHubhttps://github.com/Azure/azure-sdk-for-net/tree/main/sdk/entra/Microsoft.Azure.WebJobs.Extensions.AuthenticationEvents
Ver no GitHub
---
name: microsoft-azure-webjobs-extensions-authentication-events-dot
description: Extend Microsoft Entra ID authentication flows with custom claims, attribute collection, and OTP delivery using Azure Functions triggers.
license: MIT
---

# 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

| Event | Purpose |
|-------|---------|
| `OnTokenIssuanceStart` | Add custom claims to tokens during issuance |
| `OnAttributeCollectionStart` | Customize attribute collection UI before display |
| `OnAttributeCollectionSubmit` | Validate/modify attributes after user submission |
| `OnOtpSend` | Custom 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

| Type | Purpose |
|------|---------|
| `WebJobsAuthenticationEventsTriggerAttribute` | Function trigger attribute |
| `WebJobsTokenIssuanceStartRequest` | Token issuance event request |
| `WebJobsTokenIssuanceStartResponse` | Token issuance event response |
| `WebJobsProvideClaimsForToken` | Action to add claims |
| `WebJobsAttributeCollectionStartRequest` | Attribute collection start request |
| `WebJobsAttributeCollectionStartResponse` | Attribute collection start response |
| `WebJobsAttributeCollectionSubmitRequest` | Attribute submission request |
| `WebJobsAttributeCollectionSubmitResponse` | Attribute submission response |
| `WebJobsSetPrefillValues` | Prefill form values |
| `WebJobsShowBlockPage` | Block user with message |
| `WebJobsShowValidationError` | Show validation errors |
| `WebJobsModifyAttributeValues` | Modify submitted values |
| `WebJobsOnOtpSendRequest` | OTP send event request |
| `WebJobsOnOtpSendResponse` | OTP send event response |
| `WebJobsOnOtpSendSuccess` | OTP sent successfully |
| `WebJobsOnOtpSendFailed` | OTP send failed |
| `WebJobsContinueWithDefaultBehavior` | Continue 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

| SDK | Purpose | Install |
|-----|---------|---------|
| `Microsoft.Azure.WebJobs.Extensions.AuthenticationEvents` | Auth events (this SDK) | `dotnet add package Microsoft.Azure.WebJobs.Extensions.AuthenticationEvents` |
| `Microsoft.Identity.Web` | Web app authentication | `dotnet add package Microsoft.Identity.Web` |
| `Azure.Identity` | Azure authentication | `dotnet add package Azure.Identity` |

## Reference Links

| Resource | URL |
|----------|-----|
| NuGet Package | https://www.nuget.org/packages/Microsoft.Azure.WebJobs.Extensions.AuthenticationEvents |
| Custom Extensions Overview | https://learn.microsoft.com/entra/identity-platform/custom-extension-overview |
| Token Issuance Events | https://learn.microsoft.com/entra/identity-platform/custom-extension-tokenissuancestart-setup |
| Attribute Collection Events | https://learn.microsoft.com/entra/identity-platform/custom-extension-attribute-collection |
| GitHub Source | https://github.com/Azure/azure-sdk-for-net/tree/main/sdk/entra/Microsoft.Azure.WebJobs.Extensions.AuthenticationEvents |

Instalar microsoft-azure-webjobs-extensions-authentication-events-dot

Baixe e extraia os arquivos de habilidade para o diretório .claude/skills/.

Baixar ZIP

Clone o repositório e copie os arquivos da habilidade para o seu projeto.

git clone https://github.com/microsoft/skills/tree/main/.github/plugins/azure-sdk-dotnet/skills/microsoft-azure-webjobs-extensions-authentication-events-dotnet # Copy SKILL.md to your .claude/skills/ directory

Copiar Copiar
Configuração rápida: Copie a pasta de habilidades para .claude/skills/ O Claude detectará e usará automaticamente a habilidade
Repositório microsoft/skills

Habilidades relacionadas

gmgn-portfolio
Tempo atualizado 1 de Julho de 2026
device-integrity
Tempo atualizado 29 de Junho de 2026
zeroize-audit
Tempo atualizado 1 de Julho de 2026
flutter-use-http-package
Tempo atualizado 30 de Junho de 2026
OR