Notifications Slack depuis Auth0 Actions : logins, alertes et onboarding

Envoyer des notifications Slack depuis les Auth0 Actions : alerte sécurité, notification onboarding, rapport quotidien d'authentification.

Par Auth0.Expert · 2025-03-28 · 7 min de lecture

Slack Notifications Actions

Notifications Slack depuis Auth0 Actions

TL;DR

Auth0 Actions peuvent appeler n'importe quelle API externe, y compris Slack. Ce guide présente les patterns les plus utiles : alertes sécurité, notifications d'onboarding et rapports.

---

Setup : Slack Incoming Webhook

Voici comment connecter Slack à Auth0 via un webhook pour poster des notifications de manière sécurisée.

  1. Slack API → Create App → From scratch
  2. Incoming Webhooks → Activate → Add to workspace
  3. Copier l'URL webhook : https://hooks.slack.com/services/T.../B.../xxx
  4. Stocker dans Auth0 Action Secrets : SLACK_WEBHOOK_URL

---

Pattern 1 : Alerte premier login admin

Ce code détecte le premier login d'un utilisateur ayant le rôle admin et envoie une alerte contextualisée dans Slack pour surveillance.

exports.onExecutePostLogin = async (event, api) => {
  const roles = event.authorization?.roles || [];
  if (!roles.includes('admin')) return;

  const isFirstLogin = event.stats.logins_count === 1;
  if (!isFirstLogin) return;

  await sendSlackAlert(event.secrets.SLACK_SECURITY_WEBHOOK, {
    text: '🔐 *Nouveau compte administrateur activé*',
    blocks: [
      {
        type: 'section',
        text: {
          type: 'mrkdwn',
          text: `*Nouvel admin connecté pour la première fois*

` +
                `👤 *Email:* ${event.user.email}
` +
                `🌍 *Pays:* ${event.request.geoip?.country_name || 'Inconnu'}
` +
                `📍 *IP:* ${event.request.ip}
` +
                `🕐 *Heure:* ${new Date().toLocaleString('fr-FR', {timeZone: 'Europe/Paris'})}`,
        },
      },
      {
        type: 'actions',
        elements: [
          {
            type: 'button',
            text: { type: 'plain_text', text: '✅ Approuver' },
            style: 'primary',
            url: `https://manage.auth0.com/dashboard/us/${event.secrets.AUTH0_TENANT}/users/${event.user.user_id}`,
          },
          {
            type: 'button',
            text: { type: 'plain_text', text: '🚫 Bloquer' },
            style: 'danger',
            url: `https://yourapp.com/admin/block-user?id=${event.user.user_id}`,
          },
        ],
      },
    ],
  });
};

async function sendSlackAlert(webhook, message) {
  try {
    await fetch(webhook, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(message),
    });
  } catch (err) {
    // Ne jamais bloquer le login pour Slack
    console.error('Slack notification failed:', err.message);
  }
}

Ce script notifie votre équipe à chaque création effective d'un administrateur en donnant des options d'action immédiate.

---

Pattern 2 : Bienvenue nouvel utilisateur (#sales-notifications)

Voici comment notifier l’équipe commerciale sur Slack à chaque nouvelle inscription utilisateur, en enrichissant l’alerte avec des détails du profil.

// Action: Post User Registration
exports.onExecutePostUserRegistration = async (event, api) => {
  const email = event.user.email;
  const domain = email.split('@')[1];

  await fetch(event.secrets.SLACK_SALES_WEBHOOK, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
      blocks: [
        {
          type: 'header',
          text: { type: 'plain_text', text: '🎉 Nouveau signup !' },
        },
        {
          type: 'section',
          fields: [
            { type: 'mrkdwn', text: `*Email:*
${email}` },
            { type: 'mrkdwn', text: `*Domaine:*
${domain}` },
            { type: 'mrkdwn', text: `*Méthode:*
${event.connection.strategy}` },
            { type: 'mrkdwn', text: `*Pays:*
${event.request.geoip?.country_name || '?'}` },
          ],
        },
        {
          type: 'context',
          elements: [
            {
              type: 'mrkdwn',
              text: `🔍 <https://clearbit.com/s#${domain}|Lookup ${domain} sur Clearbit>`,
            },
          ],
        },
      ],
    }),
  });
};

Ce code publie un message contenant les informations clés d’un nouvel utilisateur, facilitant ainsi la prise de contact rapide par l’équipe.

---

Pattern 3 : Alerte brute force

Pour signaler sur Slack lorsqu’un compte est potentiellement bloqué après des tentatives de connexion suspectes, utilisez ce bloc.

// Surveiller via Log Streaming + votre backend
// Ou directement dans une Action si vous utilisez un compteur Redis

exports.onExecutePostLogin = async (event, api) => {
  if (event.transaction?.protocol !== 'oidc-basic-profile') return;

  // Vérifier si Auth0 a détecté une anomalie (via le log type)
  // Les types "f", "fp", "limit_wc" arrivent dans Log Streaming
  // Cette Action est pour enrichir l'alerte avec contexte

  if (event.user.blocked) {
    await fetch(event.secrets.SLACK_SECURITY_WEBHOOK, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        text: `🚨 *Compte bloqué suite à trop de tentatives*
` +
              `Email: ${event.user.email} | IP: ${event.request.ip} | ` +
              `Pays: ${event.request.geoip?.country_name}`
      }),
    });
  }
};

Ce pattern complète vos logs en envoyant une notification enrichie en temps réel lorsqu’un blocage est détecté.

---

Rapport quotidien (via cron + Management API)

Ce script python illustre comment produire et poster un rapport d’utilisation quotidien depuis Auth0 vers Slack, idéal pour le suivi d’activité et la sécurité.

# Script Python à exécuter en cron quotidien
import httpx
from datetime import datetime, timedelta

async def send_daily_auth_report():
    yesterday = (datetime.utcnow() - timedelta(days=1)).isoformat() + 'Z'

    # Récupérer les stats Auth0
    logs = await fetch_auth0_logs(
        query=f"date:[{yesterday} TO *]",
        per_page=1000,
    )

    stats = {
        'total': len(logs),
        'success': sum(1 for l in logs if l['type'] == 's'),
        'failure': sum(1 for l in logs if l['type'] == 'f'),
        'signups': sum(1 for l in logs if l['type'] == 'ss'),
        'mfa': sum(1 for l in logs if l['type'] in ['gd_start_auth', 'gd_auth_succeed']),
    }

    await send_slack_report(stats)

async def send_slack_report(stats):
    success_rate = round(100 * stats['success'] / max(stats['total'], 1), 1)
    await httpx.AsyncClient().post(
        SLACK_WEBHOOK,
        json={
            "text": f"📊 *Rapport Auth0 quotidien*
"
                    f"• Total logins: {stats['total']}
"
                    f"• Taux de succès: {success_rate}%
"
                    f"• Nouveaux signups: {stats['signups']}
"
                    f"• Events MFA: {stats['mfa']}
"
                    f"• Échecs: {stats['failure']}"
        }
    )

Ce script génère et envoie un résumé statistique quotidien sur votre activité Auth0, pour une visibilité instantanée dans Slack.

---

> 💬 Intégrations Slack sur mesure : nous configurons votre système d'alertes Auth0→Slack adapté à votre workflow sécurité et commercial.

📧 [email protected]


Autres articles