Implémentation CAS

Logique d’implémentation de l’ancienne version de CAS

Principe fondamental (protocole CAS 1.0)

  1. L’utilisateur accède à la page protégée /admin/admin.aspx
  2. Les règles de permissions dans web.config bloquent les utilisateurs anonymes et redirigent automatiquement vers la page de connexion CasEnter.aspx
  3. CasEnter.aspx vérifie la présence du paramètre ticket dans l’URL
  • Pas de ticket : redirection vers la page de connexion du serveur CAS avec l’adresse du site courant dans le paramètre service
  • Avec ticket : appel de l’API serviceValidate pour valider le billet auprès du serveur CAS
  1. CAS renvoie un document XML, on en extrait le nom d’utilisateur connecté
  2. Après validation réussie, appel à FormsAuthentication.SetAuthCookie() pour créer le billet d’authentification Forms local et rediriger vers la page cible
  3. Les accès suivants aux dossiers protégés utilisent ASP.NET Forms pour reconnaître l’état de connexion

Configuration web.config

<system.web>
  <authentication mode="Forms">
    <!-- loginUrl pointe vers CasEnter.aspx, page relais d’entrée CAS -->
    <forms loginUrl="CasEnter.aspx" 
           defaultUrl="admin/admin.aspx" 
           name=".LoginFormsTicket" 
           path="/" 
           timeout="40" 
           protection="All">
    </forms>
  </authentication>
  <authorization>
    <allow users="*"/>
  </authorization>
</system.web>

<!-- Interdit l’accès anonyme au dossier admin -->
<location path="admin">
  <system.web>
    <authorization>
      <deny users="?"/>
    </authorization>
  </system.web>
</location>Langage du code : HTML, XML (xml)

Les serveurs CAS récents imposent HTTPS par défaut. La valeur de casUrl doit être renseignée avec https://127.0.0.1:8443/cas/

<appSettings>
  <!-- Adresse CAS7 avec barre oblique finale -->
  <add key="casUrl" value="https://127.0.0.1:8443/cas/"/>
</appSettings>Langage du code : HTML, XML (xml)

Code‑source de CasEnter.aspx

1. Partie vue CasEnter.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="CasEnter.aspx.cs" Inherits="CasStudy.Web.CasEnter" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Connexion relais CAS</title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:Label ID="Label1" runat="server"></asp:Label><br />
            <asp:HyperLink ID="HyperLink1" runat="server">Ré‑authentifier</asp:HyperLink>
        </div>
    </form>
</body>
</html>Langage du code : HTML, XML (xml)
2. Code‑behind CasEnter.aspx.cs


API mise à jour vers CAS3.0 p3/serviceValidate
Remplacement de WebClient obsolète par HttpClient

Ajout de la compatibilité pour certificats auto‑signés (indispensable pour les tests locaux sur CAS récent)
Gestion des espaces de noms sur le XML renvoyé par CAS

using System;
using System.Configuration;
using System.Net;
using System.Net.Http;
using System.Xml;
using System.Web.Security;

public partial class CasEnter : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string casHost = ConfigurationManager.AppSettings["casUrl"];
        string ticket = Request.QueryString["ticket"];
        string service = Request.Url.GetLeftPart(UriPartial.Path);

        // Sans billet : redirection vers la page de connexion CAS
        if (string.IsNullOrEmpty(ticket))
        {
            string redirectUrl = $"{casHost}login?service={Uri.EscapeDataString(service)}";
            Response.Redirect(redirectUrl);
            return;
        }

        // Validation du billet
        string username = ValidateTicket(casHost, ticket, service);
        if (string.IsNullOrEmpty(username))
        {
            Label1.Text = "Désolé, l’authentification CAS a échoué. Veuillez réessayer.";
            HyperLink1.NavigateUrl = Request.Url.AbsolutePath;
        }
        else
        {
            // Génère le billet Forms pour la connexion locale
            FormsAuthentication.SetAuthCookie(username, false);
            // Redirige vers la page cible
            Response.Redirect(FormsAuthentication.DefaultUrl);
        }
    }

    /// <summary>
    /// Validation de billet CAS3.0 via p3/serviceValidate
    /// </summary>
    private string ValidateTicket(string casHost, string ticket, string service)
    {
        // CAS récent préconise p3/serviceValidate (protocole CAS3.0)
        string validateUrl = $"{casHost}p3/serviceValidate?ticket={Uri.EscapeDataString(ticket)}&service={Uri.EscapeDataString(service)}";

        // Tests locaux uniquement : autorise certificats SSL non fiables (supprimer en production!)
        ServicePointManager.ServerCertificateValidationCallback += (s, cert, chain, err) => true;

        using var httpClient = new HttpClient();
        string xml = httpClient.GetStringAsync(validateUrl).Result;

        XmlDocument doc = new XmlDocument();
        doc.LoadXml(xml);
        XmlNamespaceManager nsMgr = new XmlNamespaceManager(doc.NameTable);
        // Espace de noms du XML réponse CAS3
        nsMgr.AddNamespace("cas", "http://www.yale.edu/tp/cas");

        // Récupération du nœud utilisateur
        XmlNode userNode = doc.SelectSingleNode("//cas:authenticationSuccess/cas:user", nsMgr);
        return userNode?.InnerText;
    }
}Langage du code : HTML, XML (xml)

Implémentation CAS

Previous:

Laisser un commentaire

Votre adresse e-mail ne sera pas publiée. Les champs obligatoires sont indiqués avec *