Upload
imadelaabedy
View
222
Download
5
Embed Size (px)
DESCRIPTION
La gestion des identités et roles dans le framework .net
Citation preview
Authentification et autorisation .NETSécurité basée sur les rôlesSécurité basée sur les rôles
La classe WindowsIdentity Représente un utilisateur Windows. Méthodes statiques:
GetAnonymous(): Retourne un objet WindowsIdentity qui représente un utilisateur GetAnonymous(): Retourne un objet WindowsIdentity qui représente un utilisateur anonyme.
GetCurrent(): Retourne un objet WindowsIdentity qui représente l'utilisateur Windows actuel
Impersonate(): Permet d'emprunter l'identité d'un utilisateur Windows différent. Méthodes et propriétés d'instance
AuthenticationType: Définit le type d'authentification utilisé pour identifier AuthenticationType: Définit le type d authentification utilisé pour identifier l'utilisateur.
IsAuthenticated: IsGuestIsGuest IsSystem Name: nom de l'utilisateur actuel au format DOMAIN\Username où DOMAIN représente
le nom de la machine dans le cas d'un compte local, et le nom AD DS dans le cas d'un compte de p , pdomaine.
Token: jeton d'accès associé au thread d'exécution actuel. Groups: groupes auxquels l'utilisateur Windows actuel appartient
2 http://www.itformation.com
p g p q pp
ApplicationWindowsIdentity UCourant = WindowsIdentity.GetCurrent();y y ()
Console.WriteLine("Nom: " + UCourant.Name);Console.WriteLine("Token: " + UCourant.Token.ToString());Console WriteLine("Type Authentification : " + UCourant AuthenticationType);Console.WriteLine( Type Authentification : + UCourant.AuthenticationType);
if (UCourant.IsAnonymous)l lConsole.WriteLine("Utilisateur anonyme");
if (UCourant.IsAuthenticated)Console.WriteLine("Utilisateur authentifié");
if (UCourant.IsGuest)Console.WriteLine("Utilisateur Invité");
if (UCourant IsSystem)if (UCourant.IsSystem)Console.WriteLine("Utilisateur système");
http://www.itformation.com3
La classe WindowsPrincipal Permet de vérifier l'appartenance d'un utilisateur à un groupe Windows .g Un objet WindowsPrincipal doit être associé à un objet identité.
WindowsPrincipal wpCourant = new WindowsPrincipal(uCourant); // uCourant de type WindowsIdentity
U t lt ti t d é l' bj t P i i l à ti d th d t Une autre alternative est de créer l'objet Principal à partir du thread courant// La stratégie WindowsPrincipal doit être utiliséeAppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);// transtyper le principal courant (CurrentPrincipal de type IPrincipal) comme un objet de // transtyper le principal courant (CurrentPrincipal de type IPrincipal) comme un objet de
type WindowsPrincipal; la classe Thread est définie dans l'espace de noms System.Threading.
WindowsPrincipal wp=(WindowsPrincipal) Thread.CurrentPrincipal ;L é h d I I R l é ifi l' d l' ili Wi d é ifié La méthode IsInRole vérifie l'appartenance de l'utilisateur au groupe Windows spécifié en argument, il existe 4 surcharges pour cette méthode: IsInRole (Int32 rid): le groupe est identier par un identificateur relatif IsInRole(SecurityIdentifier sid): le groupe est identifié par son SIDIsInRole(SecurityIdentifier sid): le groupe est identifié par son SID IsInRole(WindowsBuiltInRole role): pour un groupe Windows Intégré. IsInRole( string nom): le groupe est identifié par son nom
http://www.itformation.com4
Application Exemple:
AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);WindowsPrincipal wpCourant = (WindowsPrincipal)Thread.CurrentPrincipal;Console.WriteLine("L'utilisateur courant est membre des groupes suivants: ");
if ( C I I R l (Wi d B il I R l Ad i i ))if (wpCourant.IsInRole(WindowsBuiltInRole.Administrator))Console.WriteLine(WindowsBuiltInRole.Administrator.ToString());
if (wpCourant.IsInRole(WindowsBuiltInRole.PowerUser))Console WriteLine(WindowsBuiltInRole PowerUser ToString());Console.WriteLine(WindowsBuiltInRole.PowerUser.ToString());
if (wpCourant.IsInRole(WindowsBuiltInRole.User))Console.WriteLine(WindowsBuiltInRole.User.ToString());
WindowsBuiltInRole est une énumération (type enum):( yp ) Administrator, User, Guest, PowerUser, AccountOperator, SystemOperator,
PrintOperator, BackupOperator,Replicator On peut aussi identifier un groupe par son nom au format suivant: "Domaine\groupe"
@ if (wpCourant.IsInRole(@"NAJA\Comptabilite"))Console.WriteLine("L'utilisateur est un membre du groupe comptabilite");
http://www.itformation.com5
La classe PrincipalPermissionEspace de noms: System Security PermissionsEspace de noms: System.Security.Permissions
La classe PrincipalPermission permet de définir les utilisateurs qui ont la permission d'exécuter un bloc de codeont la permission d exécuter un bloc de code.
Propriétés A th ti t d (t f l ) défi it i l' tili t d it êt Authenticated (true ou false ): définit si l'utilisateur doit être
authentifié ou non. Name: nom utilisateurName: nom utilisateur Role: un compte windows.
La classe peut être utilisée d'une manière déclarative ou bien La classe peut être utilisée d une manière déclarative ou bien impérative.
http://www.itformation.com6
Restriction de l'accès à une méthode Définir la stratégie de l'entité de sécurité du domaine d'application actuel : WindowsPrincipal
A D i C D i S P i i lP li (P i i lP li Wi d P i i l) AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal); Appeler la méthode qui nécessite des privilèges dans un bloc try
try{ AdminMethode(); }{ AdminMethode(); }
Dans un bloc catch intercepter l'exception SecurityException catch (System.Security.SecurityException ex){ Console.WriteLine("Vous n'avez pas les permissions p prequises pour exécuter
cette fonction."); } Ajouter une déclaration de demande d'autorisation basée sur les rôles.
[ i i l i i ( i i d l @ \[PrincipalPermission(SecurityAction.Demand,Role=@"BUILTIN\Administrateurs")]
private static void AdminMethode(){{Console.WriteLine("Exécution par un adminstrateuruniquement");
}
http://www.itformation.com7
Remarque La classse SecurityAction Spécifie les actions de sécurité à y p
effectuer en utilisant la sécurité déclarative. La déclaration supporte les paramètres nommés suivants: R l Role Authenticated User
Plusieurs déclarations peuvent être associées à une seule méthode [[PrincipalPermission(SecurityAction.Demand,Name = @"MACHINE1\Administrateur")]d,Name @ MACHINE1\Administrateur )]
[PrincipalPermission(SecurityAction.Demand, Name = @"MACHINE1\User1", Role = @
"MACHINE1\Managers")] MACHINE1\Managers )] [PrincipalPermission(SecurityAction.Demand, Authenticated = true)]
http://www.itformation.com8
Restreindre l'accès à un bloc de code La classe PrincipalPermission possède trois constructeurs
PrincipalPermission(PermissionState) PrincipalPermission(Name, Role) PrincipalPermission(Name, Role, Authenticated)
Exemple:void ComptaMethode(){ System.AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.y
WindowsPrincipal);// Construire le nom du groupe à partir du nom de la machinestring r = System.Environment.MachineName + @"\compta";
//try{// Créer l'objet PrincipalPermission avec le rôle rPrincipalPermission p = new PrincipalPermission(null, r, true);
// Demander la permission au CLR// Demander la permission au CLRp.Demand();Console.WriteLine("Accès autorisé.");}catch (System.Security.SecurityException ex)
http://www.itformation.com9
{Console.WriteLine("Accès refusé: " + ex.Message);}}
Implémenter une gestion personnalisée des identités et des rôles Deux interfaces IIdentity et IPrincipal Deux interfaces IIdentity et IPrincipal
Implémentations disponibles dans le framework .Net Windo sIdentit et Windo sPrincipal WindowsIdentity, et WindowsPrincipal
FormsIdentity et FormsPrincipal
GenericIdentity GenericPrincipal: des implémentation simplifiées des GenericIdentity, GenericPrincipal: des implémentation simplifiées des interfaces IIdentity et IPrincipal.
Pour implémenter une gestion personnalisée des identités et des rôles Pour implémenter une gestion personnalisée des identités et des rôles, il existe deux approches1. Utiliser les classes GenericIdentity et GenericPrincipal1. Utiliser les classes GenericIdentity et GenericPrincipal
2. Implémenter les interfaces IIdentity et IPrincipal
http://www.itformation.com10
L'interface IIdentity Pour implémenter l'interface IIdentity, il faut définr les propriétés suivantes:p y p p
AutheniticationType IsAutheticated Name
Classe PIdentiteclass PIdentite: IIdentity{
public PIdentite(){thi St i E t{
// Champs privésprivate bool isAuthenticated;private string name,
this.name = String.Empty;this.isAuthenticated = false;this.authenticationType = "None";this.prenom = String.Empty;p g ,
authenticationType;//Pour supporter de nouvelles propriétési t t i
p g p ythis.nom = String.Empty;this.addresse = String.Empty;this.ville = String.Empty;}private string prenom, nom,
addresse, ville;// Constructeur par défaut
}
http://www.itformation.com11
//Constructeur avec paramètrespublic PIdentite(bool isLogin
public string AuthenticationType{ get { returnpublic PIdentite(bool isLogin,
string nTypeAuthentification,string Nprenom,string Nnom, string Nadresse,
{ get { return this.authenticationType; } }// Implémenter les propriétés supplémentaires
string Nville){this.name = prenom + nom;this isAuthenticated = isLogin;
public string Prenom{ get { return this.prenom; } }public string Nom{ get { return this nom; } }this.isAuthenticated = isLogin;
this.authenticationType = nTypeAuthentification;this.prenom = Nprenom;
{ get { return this.nom; } }public string Addresse{ get { return this.addresse; } }public string Ville
this.nom = Nnom;this.addresse = Nadresse;this.ville = Nville;}
{ get { return this.ville; } }}
}// Implémenter les propriétéspublic bool IsAuthenticated{ get { return this.isAuthenticated; } }public string Name{ get { return this.name; } }
http://www.itformation.com12
L'interface IPrincipalP lé l' f IP l l f lé l é h d Pour implémenter l'interface IPrincipal , il faut implémenter les méthodes suivantes: Un constructeur qui accepte un paramètre de type IIdentity et un paramètre de type
String [] contenant les rôles associés à l'identité. La propriété Identity, qui doit retourner l'identité de l'objet Principal.a p op été e t ty, qu o t etou e e t té e objet c pa . La méthode bool IsInRole(String rôle).
Classe PPrincipalclass PPrincipal : IPrincipal{
}public IIdentity Identity{ t { t id tit } }{
private IIdentity _identity;private string[] _roles;// Constructeur
{ get { return _identity; } }public bool IsInRole(string role){ //Array:BianrySearch utilise l'algorithme de rechecrche binaire
public PPrincipal(IIdentityidentite, string[] roles){_identit identite
gdans un tableau, letableau//doit être préalablement trié, et reto rne la position de l'élémentidentity = identite;
_roles = new string[roles.Length];// CopyTo crée une copie du tableau roles à partir de la
retourne la position de l'élément recherché dans letableaureturn Array.BinarySearch( roles,
position// spécifiée en deuxième argument.roles.CopyTo(_roles, 0);Array Sort( roles);
_role) >= 0 ? true : false; }}
http://www.itformation.com13
Array.Sort(_roles);
Les classes GenericIdentity et GenericPrincipaly p
La classe GenericIdentity Deux constructeurs
GenericIdentity user1 = new GenericIdentity("user1");GenericIdentity( user1 );
GenericIdentity user2 = new GenericIdentity("user2", "SmartCard");
La classe GenericPrincipal Constructeur String[] rolesU1 = new String[] { "Développeurs", "Users", "Administrateurs" };
GenericPrincipal p1 = new GenericPrincipal(user1, rolesU1);
http://www.itformation.com14
RBS dans le cas d'une implémentation personnalisée des identités et des rôles. Etapesp Créer un objet identité de type GenericIdentity ou bien de type une classe
qui implémente l'interface Iidentity. (u1) Créer une entité de sécurité basée sur l'objet identité (p1) Créer une entité de sécurité basée sur l objet identité (p1) Définir l'entité de sécurité du thread courant System.Threading.Thread.CurrentPrincipal = p1;
Aj t l d d d' t i ti dé l ti i é ti Ajouter les demandes d'autorisations déclaratives ou impératives....try{
}…[PrincipalPermission(SecurityAction
Thread.CurrentPrincipal =p1;methode1();}catch (Exception ex)
.Demand, Role = "développeur")]void methode1(){Console WriteLine(Thread CurrentPricatch (Exception ex)
{Console.WriteLine(ex.GetType().ToString()+" déclenchée par" +Thread.CurrentPrincipal.Identity.Na
Console.WriteLine(Thread.CurrentPrincipal.Identity.Name + " est un développeur");}
http://www.itformation.com15
me);
Exercice1. Ecrire un programme qui affiche les informations suivantes, sur p g q ,
l'utilisateur Windows courant: Le nom d'utilisateur Le SID Le SID La liste des groupes dans lesquels il est membre.
2. Autorisations basées sur le rôle.créer une calculatrice qui réalise les opérations q p
arithmétiques de base, en tenant compte des restrictions suivantes
Uniquement les membres du groupe "utilisateurs" sont autorisés à effectuer une ddi iaddition
Uniquement les administrateurs doivent avoir accès à l'opération de division
Uniquement l'utilisateur user1 est autorisé à effectuer une multiplicationeffectuer une multiplication.
Afficher uniquement les boutons de commande qui correspondent aux opérations accessibles à l'utilisateur en cours
http://www.itformation.com16