Condividi tramite


ServiceSecurityContext Classe

Definizione

Rappresenta il contesto di sicurezza di una parte remota. Nel client rappresenta l'identità del servizio e, nel servizio, rappresenta l'identità client.

public ref class ServiceSecurityContext
public class ServiceSecurityContext
type ServiceSecurityContext = class
Public Class ServiceSecurityContext
Ereditarietà
ServiceSecurityContext

Esempio

Nell'esempio seguente viene utilizzata la ServiceSecurityContext classe per fornire informazioni sul contesto di sicurezza corrente. Il codice crea un'istanza della StreamWriter classe per scrivere le informazioni in un 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

Nell'esempio seguente viene illustrata un'implementazione del CheckAccessCore metodo che usa per ServiceSecurityContext analizzare un set di attestazioni.

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

Commenti

I dati fanno parte di SecurityMessageProperty per un messaggio.

Usare questa classe per ottenere informazioni su un contesto di sicurezza remoto in fase di esecuzione. Un contesto di sicurezza viene creato quando un client viene autenticato correttamente e autorizzato ad accedere a un metodo. Quando un messaggio viene autenticato e autorizzato correttamente, le informazioni di sicurezza dal client e per l'istanza del servizio corrente possono essere ottenute da un'istanza di questa classe.

È possibile recuperare un'istanza ServiceSecurityContext di dalla Current proprietà della OperationContext classe oppure usarla dall'interno di un metodo dell'operazione del servizio, come illustrato nell'esempio seguente.

Analisi di un oggetto ClaimSet

Un uso comune della classe consiste nel recuperare il set corrente di attestazioni allo scopo di identificare o autorizzare un client quando si accede a un metodo. La ClaimSet classe contiene una raccolta di Claim oggetti e ognuna può essere analizzata per determinare se è presente un'attestazione specifica. Se viene specificata l'attestazione specificata, è possibile concedere l'autorizzazione. Questa funzionalità viene fornita eseguendo l'override del CheckAccessCore metodo della ServiceAuthorizationManager classe . Per un esempio completo, vedere Criteri di autorizzazione.

Si noti che in alcune circostanze, la IsAuthenticated proprietà dell'interfaccia IIdentity restituisce true anche se il client remoto viene autenticato come utente anonimo. La PrimaryIdentity proprietà restituisce un'implementazione dell'interfaccia IIdentity . È necessario che si verifichino le circostanze seguenti:

  • Il servizio usa l'autenticazione di Windows.

  • Il servizio consente accessi anonimi.

  • L'associazione è customBinding<>.

  • L'associazione personalizzata include un <security> elemento .

  • L'elemento <security> include un <secureConversationBootstrap> con l'attributo requireSecurityContextCancellation impostato su false.

Costruttori

Nome Descrizione
ServiceSecurityContext(AuthorizationContext, ReadOnlyCollection<IAuthorizationPolicy>)

Inizializza una nuova istanza della ServiceSecurityContext classe con i parametri di autorizzazione e la raccolta di criteri specificati.

ServiceSecurityContext(AuthorizationContext)

Inizializza una nuova istanza della ServiceSecurityContext classe con i parametri di autorizzazione specificati.

ServiceSecurityContext(ReadOnlyCollection<IAuthorizationPolicy>)

Inizializza una nuova istanza della ServiceSecurityContext classe con l'insieme di oggetti criteri.

Proprietà

Nome Descrizione
Anonymous

Restituisce un'istanza della ServiceSecurityContext classe che contiene una raccolta vuota di attestazioni, identità e altri dati di contesto utilizzati in genere per rappresentare un'entità anonima.

AuthorizationContext

Ottiene le informazioni di autorizzazione per un'istanza di questa classe. AuthorizationContext Contiene una raccolta di ClaimSet che l'applicazione può interrogare e recuperare le informazioni della parte.

AuthorizationPolicies

Ottiene la raccolta di criteri associati a un'istanza di questa classe.

Current

Ottiene l'oggetto corrente ServiceSecurityContext.

IsAnonymous

Ottiene un valore che indica se il client corrente ha fornito le credenziali al servizio.

PrimaryIdentity

Ottiene l'identità primaria associata all'impostazione corrente.

WindowsIdentity

Ottiene l'identità di Windows dell'impostazione corrente.

Metodi

Nome Descrizione
Equals(Object)

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

(Ereditato da Object)
GetHashCode()

Funge da funzione hash predefinita.

(Ereditato da Object)
GetType()

Ottiene il Type dell'istanza corrente.

(Ereditato da Object)
MemberwiseClone()

Crea una copia superficiale del Objectcorrente.

(Ereditato da Object)
ToString()

Restituisce una stringa che rappresenta l'oggetto corrente.

(Ereditato da Object)

Si applica a

Vedi anche