Leggi in inglese

Condividi tramite


CodeAccessPermission Classe

Definizione

Attenzione

Code Access Security is not supported or honored by the runtime.

Definisce la struttura sottostante di tutte le autorizzazioni di accesso al codice.

C#
public abstract class CodeAccessPermission : System.Security.IPermission, System.Security.IStackWalk
C#
[System.Obsolete("Code Access Security is not supported or honored by the runtime.", DiagnosticId="SYSLIB0003", UrlFormat="https://aka.ms/dotnet-warnings/{0}")]
public abstract class CodeAccessPermission : System.Security.IPermission, System.Security.IStackWalk
C#
[System.Serializable]
public abstract class CodeAccessPermission : System.Security.IPermission, System.Security.IStackWalk
C#
[System.Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public abstract class CodeAccessPermission : System.Security.IPermission, System.Security.IStackWalk
Ereditarietà
CodeAccessPermission
Derivato
Attributi
Implementazioni

Esempio

Nell'esempio di codice seguente viene illustrata un'autorizzazione CodeAccessPermission derivata dalla classe .

C#
//#define debug
// This custom permission is intended only for the purposes of illustration.
// The following code shows how to create a custom permission that inherits
// from CodeAccessPermission. The code implements all required overrides.
// A wildcard character ('*') is implemented for the Name property.
using System;
using System.Security;
using System.Security.Permissions;
using System.IO;
using System.Security.Policy;
using System.Collections;
using System.Text;

[assembly:System.Reflection.AssemblyKeyFile("Key.snk")]
[assembly:System.Security.AllowPartiallyTrustedCallersAttribute()]

namespace MyPermission
{
    [Serializable()] sealed public class   NameIdPermission : CodeAccessPermission, IUnrestrictedPermission
    {
        private String m_Name;
        private bool m_Unrestricted;

        public  NameIdPermission(String name)
        {
            m_Name = name;
        }

        public  NameIdPermission(PermissionState state)
        {
            if (state == PermissionState.None)
            {
                m_Name = "";
            }
            else
                if (state == PermissionState.Unrestricted)
            {
                throw new ArgumentException("Unrestricted state is not allowed for identity permissions.");
            }
            else
            {
                throw new ArgumentException("Invalid permission state.");
            }
        }

        public String Name
        {
            set{m_Name = value;}
            get{ return m_Name;}
        }
        public override IPermission Copy()
        {
            string name = m_Name;
            return new  NameIdPermission( name );
        }
        public bool IsUnrestricted()
        {
            // Always false, unrestricted state is not allowed.
            return m_Unrestricted;
        }

        private bool VerifyType(IPermission target)
        {
            return (target is  NameIdPermission);
        }
        public override bool IsSubsetOf(IPermission target)
        {
#if(debug)
            Console.WriteLine ("************* Entering IsSubsetOf *********************");
#endif
            if (target == null)
            {
                Console.WriteLine ("IsSubsetOf: target == null");
                return false;
            }
#if(debug)

            Console.WriteLine ("This is = " + (( NameIdPermission)this).Name);
            Console.WriteLine ("Target is " + (( NameIdPermission)target).m_Name);
#endif
            try
            {
                 NameIdPermission operand = ( NameIdPermission)target;

                // The following check for unrestricted permission is only included as an example for
                // permissions that allow the unrestricted state. It is of no value for this permission.
                if (true == operand.m_Unrestricted)
                {
                    return true;
                }
                else if (true == this.m_Unrestricted)
                {
                    return false;
                }

                if (this.m_Name != null)
                {
                    if (operand.m_Name == null) return false;

                    if (this.m_Name == "") return true;
                }

                if (this.m_Name.Equals (operand.m_Name))
                {
                    return true;
                }
                else
                {
                    // Check for wild card character '*'.
                    int i = operand.m_Name.LastIndexOf ("*");

                    if (i > 0)
                    {
                        string prefix = operand.m_Name.Substring (0, i);

                        if (this.m_Name.StartsWith (prefix))
                        {
                            return true;
                        }
                    }
                }

                return false;
            }
            catch (InvalidCastException)
            {
                throw new ArgumentException (String.Format ("Argument_WrongType", this.GetType ().FullName));
            }
        }
        public override IPermission Intersect(IPermission target)
        {
            Console.WriteLine ("************* Entering Intersect *********************");
            if (target == null)
            {
                return null;
            }
#if(debug)
            Console.WriteLine ("This is = " + (( NameIdPermission)this).Name);
            Console.WriteLine ("Target is " + (( NameIdPermission)target).m_Name);
#endif
            if (!VerifyType(target))
            {
                throw new ArgumentException (String.Format ("Argument is wrong type.", this.GetType ().FullName));
            }

             NameIdPermission operand = ( NameIdPermission)target;

            if (operand.IsSubsetOf (this)) return operand.Copy ();
            else if (this.IsSubsetOf (operand)) return this.Copy ();
            else
                return null;
        }

        public override IPermission Union(IPermission target)
        {
#if(debug)
            Console.WriteLine ("************* Entering Union *********************");
#endif
            if (target == null)
            {
                return this;
            }
#if(debug)
            Console.WriteLine ("This is = " + (( NameIdPermission)this).Name);
            Console.WriteLine ("Target is " + (( NameIdPermission)target).m_Name);
#endif
            if (!VerifyType(target))
            {
                throw new ArgumentException (String.Format ("Argument_WrongType", this.GetType ().FullName));
            }

             NameIdPermission operand = ( NameIdPermission)target;

            if (operand.IsSubsetOf (this)) return this.Copy ();
            else if (this.IsSubsetOf (operand)) return operand.Copy ();
            else
                return null;
        }
        
        
        
        
       public override void FromXml(SecurityElement e)
        {
            // The following code for unrestricted permission is only included as an example for
            // permissions that allow the unrestricted state. It is of no value for this permission.
            String elUnrestricted = e.Attribute("Unrestricted");
            if (null != elUnrestricted)
            {
                m_Unrestricted = bool.Parse(elUnrestricted);
                return;
            }

            String elName = e.Attribute( "Name" );
            m_Name = elName == null ? null : elName;
        }
        public override SecurityElement ToXml()
        {
            // Use the SecurityElement class to encode the permission to XML.
            SecurityElement esd = new SecurityElement("IPermission");
            String name = typeof( NameIdPermission).AssemblyQualifiedName;
            esd.AddAttribute("class", name);
            esd.AddAttribute("version", "1.0");

            // The following code for unrestricted permission is only included as an example for
            // permissions that allow the unrestricted state. It is of no value for this permission.
            if (m_Unrestricted)
            {
                esd.AddAttribute("Unrestricted", true.ToString());
            }
            if (m_Name != null) esd.AddAttribute( "Name", m_Name );
            return esd;
        }
     }
}

Commenti

Attenzione

La sicurezza di accesso al codice è stata deprecata in tutte le versioni di .NET Framework e .NET. Le versioni recenti di .NET non rispettano le annotazioni CAS e generano errori se vengono usate API correlate a CAS. Gli sviluppatori devono cercare mezzi alternativi per eseguire attività di sicurezza.

Le autorizzazioni di accesso al codice usano una procedura dettagliata dello stack per assicurarsi che tutti i chiamanti del codice siano stati concessi un'autorizzazione. Se un oggetto di autorizzazione è null, viene gestito come un oggetto di autorizzazione con lo stato PermissionState.None.

Lo stack di chiamate è in genere rappresentato come in crescita, in modo che i metodi più elevati nei metodi di chiamata stack di chiamate siano inferiori nello stack di chiamate.

Gli ereditatori della CodeAccessPermission classe devono essere concessi attendibilità completa per funzionare correttamente come autorizzazioni che estendono l'infrastruttura di sicurezza. Per determinare che gli ereditatori sono completamente attendibili, CodeAccessPermission genera un InheritanceDemand oggetto pertrue = ControlEvidence e = ControlPolicytrue .

Note per gli implementatori

Quando si eredita da CodeAccessPermission, è necessario implementare anche l'interfaccia IUnrestrictedPermission .

I membri seguenti CodeAccessPermission devono essere sottoposti a override: Copy(), ToXml()Intersect(IPermission)IsSubsetOf(IPermission), FromXml(SecurityElement)e Union(IPermission).

È anche necessario definire un costruttore che accetta un PermissionState oggetto come solo parametro.

È necessario applicare l'attributo SerializableAttribute a una classe che eredita da CodeAccessPermission.

Costruttori

CodeAccessPermission()
Obsoleti.

Inizializza una nuova istanza della classe CodeAccessPermission.

Metodi

Assert()
Obsoleti.

Dichiara che il codice chiamante può accedere alla risorsa protetta da una richiesta di autorizzazione tramite il codice che chiama il metodo, anche se ai chiamanti più in alto nello stack non è stata concessa l'autorizzazione per accedere alla risorsa. L'uso di Assert() può creare problemi di sicurezza.

Copy()
Obsoleti.

Quando viene implementato da una classe derivata, crea e restituisce una copia identica dell'oggetto autorizzazioni corrente.

Demand()
Obsoleti.

Forza un oggetto SecurityException in fase di esecuzione se tutti i chiamanti in posizioni superiori nello stack di chiamate non hanno l'autorizzazione specificata dall'istanza corrente.

Deny()
Obsoleti.
Obsoleti.

Impedisce ai chiamanti in posizione più elevata nello stack di chiamate di usare il codice che chiama questo metodo per accedere alla risorsa specificata dall'istanza corrente.

Equals(Object)
Obsoleti.

Consente di determinare se l'oggetto CodeAccessPermission specificato è uguale all'oggetto CodeAccessPermission corrente.

Equals(Object)
Obsoleti.

Determina se l'oggetto specificato è uguale all'oggetto corrente.

(Ereditato da Object)
FromXml(SecurityElement)
Obsoleti.

Quando ne viene eseguito l'override in una classe derivata, ricostruisce un oggetto di sicurezza con uno stato specificato da una codifica XML.

GetHashCode()
Obsoleti.

Ottiene un codice hash per l'oggetto CodeAccessPermission adatto per l'uso in algoritmi di hash e in strutture di dati, come una tabella hash.

GetHashCode()
Obsoleti.

Funge da funzione hash predefinita.

(Ereditato da Object)
GetType()
Obsoleti.

Ottiene l'oggetto Type dell'istanza corrente.

(Ereditato da Object)
Intersect(IPermission)
Obsoleti.

Quando è implementato da una classe derivata, crea e restituisce un'autorizzazione costituita dall'intersezione dell'autorizzazione corrente e dell'autorizzazione specificata.

IsSubsetOf(IPermission)
Obsoleti.

Quando implementata da una classe derivata, determina se l'autorizzazione corrente è un sottoinsieme dell'autorizzazione specificata.

MemberwiseClone()
Obsoleti.

Crea una copia superficiale dell'oggetto Object corrente.

(Ereditato da Object)
PermitOnly()
Obsoleti.

Impedisce ai chiamanti in posizione più elevata nello stack di chiamate di usare il codice che chiama questo metodo per accedere a tutte le risorse eccetto quella specificata dall'istanza corrente.

RevertAll()
Obsoleti.

Tutti i precedenti override per il frame corrente vengono rimossi e non sono più attivi.

RevertAssert()
Obsoleti.

Qualsiasi Assert() precedente per il frame corrente viene rimosso e non è più attivo.

RevertDeny()
Obsoleti.
Obsoleti.

Qualsiasi Deny() precedente per il frame corrente viene rimosso e non è più attivo.

RevertPermitOnly()
Obsoleti.

Qualsiasi PermitOnly() precedente per il frame corrente viene rimosso e non è più attivo.

ToString()
Obsoleti.

Crea e restituisce una rappresentazione di stringa dell'oggetto autorizzazione corrente.

ToXml()
Obsoleti.

Quando sottoposto a override in una classe derivata, crea una codifica XML dell'oggetto di sicurezza e del relativo stato corrente.

Union(IPermission)
Obsoleti.

Quando sottoposto a override in una classe derivata, crea un'autorizzazione che rappresenta l'unione dell'autorizzazione corrente e di quella specificata.

Si applica a

Prodotto Versioni (obsoleto)
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
Windows Desktop 3.0, 3.1 (5, 6, 7, 8, 9)