Aller au contenu

Asp Net : Logon & AD

Hello

1er Étapes

Créer une classe

 using System;
 using System.Text;
 using System.Collections;
 using System.DirectoryServices;

namespace TOOLS
 {
 public class LdapAuthentication
 {
 private String _path;
 private String _filterAttribute;

public LdapAuthentication(String path)
 {
 _path = path;
 }

public bool IsAuthenticated(String domain, String username, String pwd)
 {

String domainAndUsername = domain + @"\" + username;
 DirectoryEntry entry = new DirectoryEntry(_path, domainAndUsername, pwd);

try
 {//Bind to the native AdsObject to force authentication.
 //Object obj = entry.NativeObject;

DirectorySearcher search = new DirectorySearcher(entry);

search.Filter = "(SAMAccountName=" + username + ")";
 search.PropertiesToLoad.Add("cn");
 SearchResult result = search.FindOne();

if (null == result)
 {
 return false;
 }

//Update the new path to the user in the directory.
 _path = result.Path;
 _filterAttribute = (String)result.Properties["cn"][0];
 }
 catch (Exception ex)
 {
 throw new Exception("Error authenticating user. " + ex.Message);
 }

return true;
 }

public String GetGroups()
 {
 DirectorySearcher search = new DirectorySearcher(_path);
 search.Filter = "(cn=" + _filterAttribute + ")";
 search.PropertiesToLoad.Add("memberOf");
 StringBuilder groupNames = new StringBuilder();

try
 {
 SearchResult result = search.FindOne();

int propertyCount = result.Properties["memberOf"].Count;

String dn;
 int equalsIndex, commaIndex;

for (int propertyCounter = 0; propertyCounter < propertyCount; propertyCounter++)
 {
 dn = (String)result.Properties["memberOf"][propertyCounter];

equalsIndex = dn.IndexOf("=", 1);
 commaIndex = dn.IndexOf(",", 1);
 if (-1 == equalsIndex)
 {
 return null;
 }

groupNames.Append(dn.Substring((equalsIndex + 1), (commaIndex - equalsIndex) - 1));
 groupNames.Append("|");

}
 }
 catch (Exception ex)
 {
 throw new Exception("Error obtaining group names. " + ex.Message);
 }
 return groupNames.ToString();
 }
 }
 }

2ème Etape

Ensuite créer un répertoire (ACCOUNT par exemple) dans votre projet puis ajoutez une webform que vous appellerez LOGON

Profitez s’en déjà pour ajouter aussi un fichier Web.config

Dans la WebForm Logon.aspx mettez le code suivant pour la partie HTML

<%@ Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Logon.aspx.cs" Inherits="TOOLS.Account.WebForm1" %>
<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
 <asp:Panel ID="panel1" runat="server" DefaultButton="btnLogin">
 <br />
<p>Utilisez votre compte AD pour vos connecter!</p>

<div class="text-center">
 <asp:Label ID="Label1" Runat=server >Domain:</asp:Label>
 <asp:TextBox ID="txtDomain" Runat=server  ></asp:TextBox> 
 <asp:Label ID="Label2" Runat=server >Username:</asp:Label>
 <asp:TextBox ID=txtUsername Runat=server ></asp:TextBox>
 <asp:Label ID="Label3" Runat=server >Password:</asp:Label>
 <asp:TextBox ID="txtPassword" Runat=server TextMode=Password></asp:TextBox><br>
 <asp:Button ID="btnLogin" Runat=server Text="Login" OnClick="Login_Click"></asp:Button><br>
 <asp:Label ID="errorLabel" Runat=server ForeColor=#ff3300></asp:Label><br>
 <asp:CheckBox ID=chkPersist Runat=server Text="Persist Cookie" />
 </div>
 <br />
 <div class="text-center">
 </div>

</asp:Panel>
</asp:Content>

Et dans le code C# (en rouge votre adresse LDAP à changer ) 

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Text;
using System.DirectoryServices;

namespace TOOLS.Account
{
 public partial class WebForm1 : System.Web.UI.Page
 {
 protected void Page_Load(object sender, EventArgs e)
 {
 
 }

protected void Login_Click(object sender, EventArgs e)
 {
 String adPath = "LDAP://domaine.com"; //Fully-qualified Domain Name
 LdapAuthentication adAuth = new LdapAuthentication(adPath);
 try
 {
 if (true == adAuth.IsAuthenticated(txtDomain.Text, txtUsername.Text, txtPassword.Text))
 {
 //String groups = adAuth.GetGroups();

//Create the ticket, and add the groups.
 bool isCookiePersistent = chkPersist.Checked;
 FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(1, txtUsername.Text,
 DateTime.Now, DateTime.Now.AddMinutes(60), isCookiePersistent, "");

//Encrypt the ticket.
 String encryptedTicket = FormsAuthentication.Encrypt(authTicket);

//Create a cookie, and then add the encrypted ticket to the cookie as data.
 HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);

if (true == isCookiePersistent)
 authCookie.Expires = authTicket.Expiration;

//Add the cookie to the outgoing cookies collection.
 Response.Cookies.Add(authCookie);

//You can redirect now.
 Response.Redirect(FormsAuthentication.GetRedirectUrl(txtUsername.Text, false));
 }
 else
 {
 errorLabel.Text = "Authentication did not succeed. Check user name and password.";
 }
 }
 catch (Exception ex)
 {
 errorLabel.Text = "Error authenticating. " + ex.Message;
 }
 }
 }
}

3éme Etapes

Editer le Web.Config de votre répertoire ACCOUNT 

<?xml version="1.0"?>
<configuration>

<system.web>
 <authorization>
 <allow users="*" />
 </authorization>
 </system.web>
</configuration>

Et Editer le Web.config de votre projet (celui à la racine normalement 🙂 )

Ajouter dans la partie system.web ceci :

 <authentication mode="Forms">
 <forms loginUrl="~/Account/Logon.aspx" name="adAuthCookie" timeout="10" path="/" >
 </forms>
 </authentication>
 <authorization>
 <deny users="?" />
 <allow users="*" />
 </authorization>
 <identity impersonate="true" />

4ème Etapes :

Dans le fichier Global.asax ajouter la fonction ci-dessous

void Application_AuthenticateRequest(Object sender, EventArgs e)
 {
 String cookieName = FormsAuthentication.FormsCookieName;
 HttpCookie authCookie = Context.Request.Cookies[cookieName];

if (null == authCookie)
 {//There is no authentication cookie.
 return;
 }

FormsAuthenticationTicket authTicket = null;

try
 {
 authTicket = FormsAuthentication.Decrypt(authCookie.Value);
 }
 catch (Exception ex)
 {
 //Write the exception to the Event Log.
 return;
 }

if (null == authTicket)
 {//Cookie failed to decrypt.
 return;
 }

//When the ticket was created, the UserData property was assigned a
 //pipe-delimited string of group names.
 String[] groups = authTicket.UserData.Split(new char[] { '|' });

//Create an Identity.
 GenericIdentity id = new GenericIdentity(authTicket.Name, "LdapAuthentication");

//This principal flows throughout the request.
 GenericPrincipal principal = new GenericPrincipal(id, groups);

Context.User = principal;

}

5ème Etape

Configurer votre IIS

Il vos faut activer le mode « Anonyme »

  • Pour IIS de visual studio (lors de vos test & dev) , Cliquez sur votre projet dans l’explorateur de projet puis la touche F4

Vous accédez à la fenêtre ci-dessous (à paramétrer comme ci-dessous)

  • Pour IIS sur votre serveur aller dans « Internet Information Services (IIS) Manager »  puis Authentification

Mettre Enabled sur « Anonymous Authentication » , « ASP.NET Impersonation » & « Forms Authentication »

 

AIDE:

Quelques liens pour vous aider dans le cas ou mes explications ne sont pas suffisantes (attention j’ai modifié un peu le code donc si vous reprenez les exemples des liens faites attention 🙂 )

https://support.microsoft.com/en-us/help/316748/how-to-authenticate-against-the-active-directory-by-using-forms-authentication-and-visual-c-.net

https://www.codeproject.com/Articles/608447/Directory-Authentication-for-Cross-Domain-Users-in

http://dotnetgallery.com/kb/resource6-Login-authentication-using-LDAP-Active-Directory-for-ASPNET-applications.aspx

Laisser un commentaire

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