ServiceSecurityContext ServiceSecurityContext ServiceSecurityContext ServiceSecurityContext Class

Définition

Représente le contexte de sécurité d'un tiers distant.Represents the security context of a remote party. Côté client, représente l'identité de service et, côté service, représente l'identité du client.On the client, represents the service identity and, on the service, represents the client identity.

public ref class ServiceSecurityContext
public class ServiceSecurityContext
type ServiceSecurityContext = class
Public Class ServiceSecurityContext
Héritage
ServiceSecurityContextServiceSecurityContextServiceSecurityContextServiceSecurityContext

Exemples

L'exemple suivant utilise la classe ServiceSecurityContext pour fournir des informations sur le contexte de sécurité actuel.The following example uses the ServiceSecurityContext class to provide information about the current security context. Le code crée une instance de la classe StreamWriter pour écrire les informations dans un fichier.The code creates an instance of the StreamWriter class to write the information to a file.

// When this method runs, the caller must be an authenticated user 
// and the ServiceSecurityContext is not a null instance. 
public double Add(double n1, double n2)
{
    // Write data from the ServiceSecurityContext to a file using the StreamWriter class.
    using (StreamWriter sw = new StreamWriter(@"c:\ServiceSecurityContextInfo.txt"))
    {
        // Write the primary identity and Windows identity. The primary identity is derived from 
        // the credentials used to authenticate the user. The Windows identity may be a null string.
        sw.WriteLine("PrimaryIdentity: {0}", ServiceSecurityContext.Current.PrimaryIdentity.Name);
        sw.WriteLine("WindowsIdentity: {0}", ServiceSecurityContext.Current.WindowsIdentity.Name);

        // Write the claimsets in the authorization context. By default, there is only one claimset
        // provided by the system. 
        foreach (ClaimSet claimset in ServiceSecurityContext.Current.AuthorizationContext.ClaimSets)
        {
            foreach (Claim claim in claimset)
            {
                // Write out each claim type, claim value, and the right. There are two
                // possible values for the right: "identity" and "possessproperty". 
                sw.WriteLine("Claim Type: {0}, Resource: {1} Right: {2}",
                    claim.ClaimType,
                    claim.Resource.ToString(),
                    claim.Right);
                sw.WriteLine();
            }
        }
    }
    return n1 + n2;
}
' When this method runs, the caller must be an authenticated user and the ServiceSecurityContext 
' is not a null instance. 
Public Function Add(ByVal n1 As Double, ByVal n2 As Double) As Double Implements ICalculator.Add
    ' Write data from the ServiceSecurityContext to a file using the StreamWriter class.
    Dim sw As New StreamWriter("c:\ServiceSecurityContextInfo.txt")
    Try
        ' Write the primary identity and Windows identity. The primary identity is derived from 
        ' the credentials used to authenticate the user. The Windows identity may be a null string.
        sw.WriteLine("PrimaryIdentity: {0}", ServiceSecurityContext.Current.PrimaryIdentity.Name)
        sw.WriteLine("WindowsIdentity: {0}", ServiceSecurityContext.Current.WindowsIdentity.Name)

        ' Write the claimsets in the authorization context. By default, there is only one claimset
        ' provided by the system. 
        Dim claimset As ClaimSet
        For Each claimset In ServiceSecurityContext.Current.AuthorizationContext.ClaimSets
            Dim claim As Claim
            For Each claim In claimset
                ' Write out each claim type, claim value, and the right. There are two
                ' possible values for the right: "identity" and "possessproperty". 
                sw.WriteLine("Claim Type: {0}, Resource: {1} Right: {2}", _
                claim.ClaimType, _
                claim.Resource.ToString(), _
                claim.Right)
                sw.WriteLine()
            Next claim
        Next claimset
    Finally
        sw.Dispose()
    End Try
    Return n1 + n2
End Function

L'exemple suivant présente une implémentation de la méthode CheckAccessCore qui utilise le ServiceSecurityContext pour analyser un ensemble de revendications.The following example shows an implementation of the CheckAccessCore method that uses the ServiceSecurityContext to parse a set of claims.

public class MyServiceAuthorizationManager : ServiceAuthorizationManager
{
    protected override bool CheckAccessCore(OperationContext operationContext)
    {                
        // Extract the action URI from the OperationContext. Match this against the claims
        // in the AuthorizationContext.
        string action = operationContext.RequestContext.RequestMessage.Headers.Action;
        Console.WriteLine("action: {0}", action);

        // Iterate through the various claimsets in the AuthorizationContext.
        foreach(ClaimSet cs in operationContext.ServiceSecurityContext.AuthorizationContext.ClaimSets)
        {
            // Examine only those claim sets issued by System.
            if (cs.Issuer == ClaimSet.System)
            {
                // Iterate through claims of type "http://example.org/claims/allowedoperation".
                foreach (Claim c in cs.FindClaims("http://example.org/claims/allowedoperation", 
                    Rights.PossessProperty))
                {
                    // Write the Claim resource to the console.
                    Console.WriteLine("resource: {0}", c.Resource.ToString());

                    // If the Claim resource matches the action URI then return true to allow access.
                    if (action == c.Resource.ToString())
                        return true;
                }
            }
        }

        // If this point is reached, return false to deny access.
         return false;                 
    }
}
Public Class MyServiceAuthorizationManager
    Inherits ServiceAuthorizationManager
    
    Protected Overrides Function CheckAccessCore(ByVal operationContext As OperationContext) As Boolean 
        ' Extract the action URI from the OperationContext. Match this against the claims
        ' in the AuthorizationContext.
        Dim action As String = operationContext.RequestContext.RequestMessage.Headers.Action
        Console.WriteLine("action: {0}", action)
        
        ' Iterate through the various claimsets in the authorizationcontext.
        Dim cs As ClaimSet
        For Each cs In  operationContext.ServiceSecurityContext.AuthorizationContext.ClaimSets
            ' Examine only those claim sets issued by System.
            If cs.Issuer Is ClaimSet.System Then
                ' Iterate through claims of type "http://example.org/claims/allowedoperation".
                Dim c As Claim
                For Each c In  cs.FindClaims("http://example.org/claims/allowedoperation", _
                        Rights.PossessProperty)
                    ' Write the Claim resource to the console.
                    Console.WriteLine("resource: {0}", c.Resource.ToString())
                    
                    ' If the Claim resource matches the action URI then return true to allow access.
                    If action = c.Resource.ToString() Then
                        Return True
                    End If
                Next c
            End If
        Next cs 
        ' If we get here, return false, denying access.
        Return False
    
    End Function 
End Class 

Remarques

Les données font partie du SecurityMessageProperty pour un message.The data is part of the SecurityMessageProperty for a message.

Utilisez cette classe pour obtenir des informations sur un référentiel distant contexte de sécurité lors de l’exécution.Use this class to obtain information about a remote security context at runtime. Un contexte de sécurité est créé lorsqu'un client est authentifié avec succès et autorisé à accéder à une méthode.A security context is created when a client is successfully authenticated and authorized to access a method. Lorsqu'un message est authentifié et autorisé avec succès, les informations sur la sécurité du client et pour l'instance de service en cours peuvent être obtenues à partir d'une instance de cette classe.When a message is successfully authenticated and authorized, the security information from the client and for the current service instance can be obtained from an instance of this class.

Vous pouvez récupérer une instance du ServiceSecurityContext de la propriété Current de la classe OperationContext ou l'utiliser depuis une méthode d'opération de service, comme illustré dans l'exemple suivant.You can retrieve an instance of the ServiceSecurityContext from the Current property of the OperationContext class, or use it from within a service operation method, as shown in the following example.

Analyse d'une classe ClaimSetParsing a ClaimSet

La classe est couramment utilisée pour récupérer l'ensemble de revendications actuel pour identifier ou autoriser un client lors de l'accès à une méthode.A common use of the class is to retrieve the current set of claims for the purpose of identifying or authorizing a client when accessing a method. La classe ClaimSet contient une collection d'objets Claim, et chacun peut être analysé pour déterminer si une revendication spécifique est présente.The ClaimSet class contains a collection of Claim objects, and each can be parsed to determine whether a specific claim is present. Si la revendication spécifiée est fournie, l'autorisation peut être accordée.If the specified claim is provided, authorization can be granted. Cette fonctionnalité est fournie en substituant la méthode CheckAccessCore de la classe ServiceAuthorizationManager.This functionality is provided by overriding the CheckAccessCore method of the ServiceAuthorizationManager class. Pour obtenir un exemple complet, consultez la stratégie d’autorisation.For a complete example, see the Authorization Policy.

Notez que dans certaines circonstances, la propriété IsAuthenticated de l'interface IIdentity retourne true même si le client distant est authentifié en tant qu'utilisateur anonyme.Note that under some circumstances, the IsAuthenticated property of the IIdentity interface returns true even if the remote client is authenticated as an anonymous user. (La propriété PrimaryIdentity retourne une implémentation de l'interface IIdentity). Les circonstances suivantes doivent être remplies pour que ceci se produise :(The PrimaryIdentity property returns an implementation of the IIdentity interface.) The following circumstances must be true for this to occur:

  • Le service utilise l'authentification Windows.The service uses Windows authentication.

  • Le service autorise les ouvertures de session anonymes.The service allows anonymous logons.

  • La liaison est un <customBinding>.The binding is a <customBinding>.

  • La liaison personnalisée inclut un élément <security>.The custom binding includes a <security> element.

  • Le <security> élément inclut un <secureConversationBootstrap> avec la requireSecurityContextCancellation attribut la valeur false.The <security> element includes a <secureConversationBootstrap> with the requireSecurityContextCancellation attribute set to false.

Constructeurs

ServiceSecurityContext(AuthorizationContext) ServiceSecurityContext(AuthorizationContext) ServiceSecurityContext(AuthorizationContext) ServiceSecurityContext(AuthorizationContext)

Initialise une nouvelle instance de la classe ServiceSecurityContext avec les paramètres d'autorisation spécifiés.Initializes a new instance of the ServiceSecurityContext class with the specified authorization parameters.

ServiceSecurityContext(AuthorizationContext, ReadOnlyCollection<IAuthorizationPolicy>) ServiceSecurityContext(AuthorizationContext, ReadOnlyCollection<IAuthorizationPolicy>) ServiceSecurityContext(AuthorizationContext, ReadOnlyCollection<IAuthorizationPolicy>) ServiceSecurityContext(AuthorizationContext, ReadOnlyCollection<IAuthorizationPolicy>)

Initialise une nouvelle instance de la classe ServiceSecurityContext avec les paramètres d’autorisation spécifiés et la collection de stratégies.Initializes a new instance of the ServiceSecurityContext class with the specified authorization parameters and collection of policies.

ServiceSecurityContext(ReadOnlyCollection<IAuthorizationPolicy>) ServiceSecurityContext(ReadOnlyCollection<IAuthorizationPolicy>) ServiceSecurityContext(ReadOnlyCollection<IAuthorizationPolicy>) ServiceSecurityContext(ReadOnlyCollection<IAuthorizationPolicy>)

Initialise une nouvelle instance de la classe ServiceSecurityContext avec la collection d’objets de stratégies.Initializes a new instance of the ServiceSecurityContext class with the collection of policies object.

Propriétés

Anonymous Anonymous Anonymous Anonymous

Retourne une instance de la classe ServiceSecurityContext qui contient une collection de revendications vide, les identités et les autres données de contexte habituellement utilisées pour représenter une partie anonyme.Returns an instance of the ServiceSecurityContext class that contains an empty collection of claims, identities, and other context data that is usually used to represent an anonymous party.

AuthorizationContext AuthorizationContext AuthorizationContext AuthorizationContext

Obtient les informations d'autorisation d'une instance de cette classe.Gets the authorization information for an instance of this class. Le AuthorizationContext contient une collection de ClaimSet que l'application peut interroger et dont elle peut récupérer les informations sur la partie.The AuthorizationContext contains a collection of ClaimSet that the application can interrogate and retrieve the information of the party.

AuthorizationPolicies AuthorizationPolicies AuthorizationPolicies AuthorizationPolicies

Obtient la collection de stratégies associée à une instance de cette classe.Gets the collection of policies associated with an instance of this class.

Current Current Current Current

Obtient le ServiceSecurityContext actuel.Gets the current ServiceSecurityContext.

IsAnonymous IsAnonymous IsAnonymous IsAnonymous

Obtient une valeur qui indique si le client actuel a fourni les informations d'identification au service.Gets a value that indicates whether the current client has provided credentials to the service.

PrimaryIdentity PrimaryIdentity PrimaryIdentity PrimaryIdentity

Obtient l'identité principale associée au paramètre en cours.Gets the primary identity associated with the current setting.

WindowsIdentity WindowsIdentity WindowsIdentity WindowsIdentity

Obtient l'identité Windows du paramètre en cours.Gets the Windows identity of the current setting.

Méthodes

Equals(Object) Equals(Object) Equals(Object) Equals(Object)

Détermine si l'objet spécifié est identique à l'objet actuel.Determines whether the specified object is equal to the current object.

(Inherited from Object)
GetHashCode() GetHashCode() GetHashCode() GetHashCode()

Fait office de fonction de hachage par défaut.Serves as the default hash function.

(Inherited from Object)
GetType() GetType() GetType() GetType()

Obtient le Type de l'instance actuelle.Gets the Type of the current instance.

(Inherited from Object)
MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

Crée une copie superficielle de l'objet Object actuel.Creates a shallow copy of the current Object.

(Inherited from Object)
ToString() ToString() ToString() ToString()

Retourne une chaîne qui représente l'objet actuel.Returns a string that represents the current object.

(Inherited from Object)

S’applique à

Voir aussi