ServiceSecurityContext Classe
Definição
Importante
Algumas informações dizem respeito a um produto pré-lançado que pode ser substancialmente modificado antes de ser lançado. A Microsoft não faz garantias, de forma expressa ou implícita, em relação à informação aqui apresentada.
Representa o contexto de segurança de uma parte remota. No cliente, representa a identidade do serviço e, no serviço, representa a identidade do cliente.
public ref class ServiceSecurityContext
public class ServiceSecurityContext
type ServiceSecurityContext = class
Public Class ServiceSecurityContext
- Herança
-
ServiceSecurityContext
Exemplos
O exemplo seguinte utiliza a ServiceSecurityContext classe para fornecer informações sobre o contexto de segurança atual. O código cria uma instância da StreamWriter classe para escrever a informação num ficheiro.
// 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
O exemplo seguinte mostra uma implementação do CheckAccessCore método que usa o ServiceSecurityContext para analisar um conjunto de reivindicações.
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
Observações
Os dados fazem parte do SecurityMessageProperty for uma mensagem.
Use esta classe para obter informações sobre um contexto de segurança remoto em tempo de execução. Um contexto de segurança é criado quando um cliente é autenticado com sucesso e autorizado a aceder a um método. Quando uma mensagem é autenticada e autorizada com sucesso, a informação de segurança do cliente e da instância de serviço atual pode ser obtida a partir de uma instância desta classe.
Pode recuperar uma instância do ServiceSecurityContext a partir da Current propriedade da OperationContext classe, ou usá-la dentro de um método de operação de serviço, como mostrado no exemplo seguinte.
Análise de um Conjunto de Reivindicações
Uma utilização comum da classe é recuperar o conjunto atual de reivindicações com o objetivo de identificar ou autorizar um cliente ao aceder a um método. A ClaimSet classe contém uma coleção de Claim objetos, e cada um pode ser analisado para determinar se existe uma reivindicação específica. Se a reivindicação especificada for fornecida, a autorização pode ser concedida. Esta funcionalidade é fornecida ao sobrepor o CheckAccessCore método da ServiceAuthorizationManager classe. Para um exemplo completo, consulte a Política de Autorização.
Modo Cookie e IsAuthenticated
Note-se que, em algumas circunstâncias, a IsAuthenticated propriedade da IIdentity interface retorna true mesmo que o cliente remoto esteja autenticado como utilizador anónimo. (A PrimaryIdentity propriedade devolve uma implementação da IIdentity interface.) As seguintes circunstâncias devem ser verdadeiras para que tal aconteça:
O serviço utiliza Windows authentication.
O serviço permite logons anónimos.
A encadernação é personalizada<>.
A encadernação personalizada inclui um
<security>elemento.O
<security>elemento inclui um <secureConversationBootstrap> com orequireSecurityContextCancellationatributo definido comofalse.
Construtores
| Name | Description |
|---|---|
| ServiceSecurityContext(AuthorizationContext, ReadOnlyCollection<IAuthorizationPolicy>) |
Inicializa uma nova instância da ServiceSecurityContext classe com os parâmetros de autorização especificados e a coleção de políticas. |
| ServiceSecurityContext(AuthorizationContext) |
Inicializa uma nova instância da ServiceSecurityContext classe com os parâmetros de autorização especificados. |
| ServiceSecurityContext(ReadOnlyCollection<IAuthorizationPolicy>) |
Inicializa uma nova instância da ServiceSecurityContext classe com o objeto de coleção de políticas. |
Propriedades
| Name | Description |
|---|---|
| Anonymous |
Devolve uma instância da ServiceSecurityContext classe que contém uma coleção vazia de reivindicações, identidades e outros dados de contexto que normalmente são usados para representar uma parte anónima. |
| AuthorizationContext |
Obtém a informação de autorização para uma instância desta classe. Contém AuthorizationContext uma coleção que ClaimSet o pedido pode interrogar e recuperar informações da parte. |
| AuthorizationPolicies |
Obtém a coleção de políticas associadas a uma instância desta classe. |
| Current |
Obtém a corrente ServiceSecurityContext. |
| IsAnonymous |
Recebe um valor que indica se o cliente atual forneceu credenciais ao serviço. |
| PrimaryIdentity |
Obtém a identidade principal associada à configuração atual. |
| WindowsIdentity |
Obtém a identidade do Windows com a definição atual. |
Métodos
| Name | Description |
|---|---|
| Equals(Object) |
Determina se o objeto especificado é igual ao objeto atual. (Herdado de Object) |
| GetHashCode() |
Serve como função de hash predefinida. (Herdado de Object) |
| GetType() |
Obtém o Type da instância atual. (Herdado de Object) |
| MemberwiseClone() |
Cria uma cópia superficial do atual Object. (Herdado de Object) |
| ToString() |
Devolve uma cadeia que representa o objeto atual. (Herdado de Object) |