Esta página foi útil?
Seus comentários sobre este conteúdo são importantes. Queremos saber sua opinião.
Comentários adicionais?
1500 caracteres restantes
Exportar (0) Imprimir
Expandir Tudo
Este artigo foi traduzido por máquina. Coloque o ponteiro do mouse sobre as frases do artigo para ver o texto original. Mais informações.
Tradução
Original

HostSecurityManager Classe

Permite que o Controlarar e a personalização do comportamento de segurança para domínios do aplicativo.

Namespace:  System.Security
Assembly:  mscorlib (em mscorlib. dll)

[SerializableAttribute]
[ComVisibleAttribute(true)]
[SecurityPermissionAttribute(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.Infrastructure)]
[SecurityPermissionAttribute(SecurityAction.InheritanceDemand, Flags = SecurityPermissionFlag.Infrastructure)]
public class HostSecurityManager

When you create a new AppDomain, the common language runtime queries the AppDomainManager for the presence of a HostSecurityManager, which participates in making security decisions for the AppDomain.Host providers should implement a host security manager that inherits from the HostSecurityManager class.

OBSERVAÇÕES PARA Inheritors:

Some members of a HostSecurityManager are called whenever an assembly is loaded, either implicitly or explicitly.The get accessor for the DomainPolicy property and the ProvideAssemblyEvidence and ProvideAppDomainEvidence methods must not load any assemblies, because doing so will result in the members of the HostSecurityManager being recursively called.To avoid circular references, you should create new instances of classes that can cause assemblies to be loaded, either implicitly or explicitly, in the constructor of a class that derives from HostSecurityManager.

The following code example shows a very simple implementation of a HostSecurityManager.

// To replace the default security manager with MySecurityManager, add the 
// assembly to the GAC and call MySecurityManager in the
// custom implementation of the AppDomainManager.

using System;
using System.Collections;
using System.Net;
using System.Reflection;
using System.Security;
using System.Security.Permissions;
using System.Security.Policy;
using System.Security.Principal;
using System.Threading;
using System.Runtime.InteropServices;
using System.Runtime.Hosting;

[assembly: System.Security.AllowPartiallyTrustedCallersAttribute()]
namespace MyNamespace
{
	[Serializable()]
       [SecurityPermissionAttribute(SecurityAction.Demand, Flags=SecurityPermissionFlag.Infrastructure)]
	public class MySecurityManager : HostSecurityManager
	{
		public MySecurityManager()
		{
			Console.WriteLine(" Creating MySecurityManager.");
		}

		private PolicyLevel myDomainPolicy = null;
		public override PolicyLevel DomainPolicy
		{
			get
			{
				if (AppDomain.CurrentDomain.FriendlyName == "DefaultDomain" ||
					AppDomain.CurrentDomain.FriendlyName == "Compilation Domain")
					return null;

				if (myDomainPolicy == null)
					myDomainPolicy = CreateAppDomainPolicy();
				return myDomainPolicy;
			}
		}

		private HostSecurityManagerOptions hostFlags = HostSecurityManagerOptions.HostDetermineApplicationTrust |
												   HostSecurityManagerOptions.HostAssemblyEvidence;
		public override HostSecurityManagerOptions Flags
		{
			get
			{
				return hostFlags;
			}
		}

		public override Evidence ProvideAssemblyEvidence(Assembly loadedAssembly, Evidence evidence)
		{
			Console.WriteLine("Provide assembly evidence for: " + (loadedAssembly == null ? "Unknown" : loadedAssembly.ToString()) + ".");
			if (evidence == null)
				return null;

			evidence.AddAssembly(new CustomEvidenceType());
			return evidence;
		}
		public override Evidence ProvideAppDomainEvidence(Evidence evidence)
		{
			Console.WriteLine("Provide evidence for the " + AppDomain.CurrentDomain.FriendlyName + " AppDomain." );
			if (evidence == null)
				return null;

			evidence.AddHost(new CustomEvidenceType());
			return evidence;
		}

        [SecurityPermissionAttribute(SecurityAction.Demand, Execution = true)]
		[SecurityPermissionAttribute(SecurityAction.Assert, Unrestricted = true)]
		public override ApplicationTrust DetermineApplicationTrust(Evidence applicationEvidence, Evidence activatorEvidence, TrustManagerContext context)
		{
			if (applicationEvidence == null)
				throw new ArgumentNullException("applicationEvidence");

			// Get the activation context from the application evidence.
			// This HostSecurityManager does not examine the activator evidence
			// nor is it concerned with the TrustManagerContext;
			// it simply grants the requested grant in the application manifest.

			IEnumerator enumerator = applicationEvidence.GetHostEnumerator();
			ActivationArguments activationArgs = null;
			while (enumerator.MoveNext())
			{
				activationArgs = enumerator.Current as ActivationArguments;
				if (activationArgs != null)
					break;
			}

			if (activationArgs == null)
				return null;

			ActivationContext activationContext = activationArgs.ActivationContext;
			if (activationContext == null)
				return null;

			ApplicationTrust trust = new ApplicationTrust(activationContext.Identity);
			ApplicationSecurityInfo asi = new ApplicationSecurityInfo(activationContext);
			trust.DefaultGrantSet = new PolicyStatement(asi.DefaultRequestSet, PolicyStatementAttribute.Nothing);
			trust.IsApplicationTrustedToRun = true;
			return trust;
		}

		private static NamedPermissionSet localIntranet;
		private static PolicyLevel CreateAppDomainPolicy()
		{
			Console.WriteLine("CreateAppDomainPolicy called.");
			PolicyLevel pLevel = PolicyLevel.CreateAppDomainLevel();
			// The root code group of the policy level combines all
			// permissions of its children.
			UnionCodeGroup rootCodeGroup;
			PermissionSet ps = new PermissionSet(PermissionState.None);
			ps.AddPermission(new SecurityPermission(SecurityPermissionFlag.Execution));
			rootCodeGroup = new UnionCodeGroup(new AllMembershipCondition(),
				new PolicyStatement(ps, PolicyStatementAttribute.Nothing));

			// The following code limits all code on this machine to local intranet permissions
			// when running in this application domain.
			FindNamedPermissionSet("LocalIntranet");
			UnionCodeGroup virtualIntranet = new UnionCodeGroup(
				new ZoneMembershipCondition(SecurityZone.MyComputer),
				new PolicyStatement(localIntranet,
				PolicyStatementAttribute.Nothing));
			virtualIntranet.Name = "Virtual Intranet";
			// Add the code groups to the policy level.
			rootCodeGroup.AddChild(virtualIntranet);
			pLevel.RootCodeGroup = rootCodeGroup;
			return pLevel;
		}

		private static void FindNamedPermissionSet(string name)
		{
			IEnumerator policyEnumerator = SecurityManager.PolicyHierarchy();

			while (policyEnumerator.MoveNext())
			{
				PolicyLevel currentLevel = (PolicyLevel)policyEnumerator.Current;

				if (currentLevel.Label == "Machine")
				{
					IList namedPermissions = currentLevel.NamedPermissionSets;
					IEnumerator namedPermission = namedPermissions.GetEnumerator();

					while (namedPermission.MoveNext())
					{
						if (((NamedPermissionSet)namedPermission.Current).Name == name)
						{
							Console.WriteLine("Named permission set " +
								((NamedPermissionSet)namedPermission.Current).Name + " found.");
							// Save the LocalIntranet permissions set for later use.
							localIntranet = ((NamedPermissionSet)namedPermission.Current);
						}
					}
				}
			}
		}
	}
    [Serializable()]
    public class CustomEvidenceType
    {
        public CustomEvidenceType() { }

        public override string ToString()
        {
            return "CustomEvidenceType";
        }
    }
}


System.Object
  System.Security.HostSecurityManager

Quaisquer membros públicos estático (compartilhados na Visual Basic) desse tipo são Thread seguro. Não há garantia de que qualquer membro de instância seja isento de segmentos.

Contribuições da comunidade

ADICIONAR
Mostrar:
© 2015 Microsoft