Expressões de política de Gerenciamento de API

APLICA-SE A: todas as camadas do Gerenciamento de API

Este artigo descreve a sintaxe das expressões de política na C# 7. Cada expressão tem acesso a:

  • A variável de contexto fornecida implicitamente.
  • Um subconjunto permitido de tipos do .NET Framework.

Syntax

  • Expressões de instrução única:
    • Colocadas em @(expression), em que expression é uma instrução de expressão C# bem formada.
  • Expressões de instrução múltipla:
    • Colocadas em @{expression}.
    • Todos os caminhos de código dentro de expressões de várias instruções devem terminar com uma instrução return.

Exemplos

@(true)

@((1+1).ToString())

@("Hi There".Length)

@(Regex.Match(context.Response.Headers.GetValueOrDefault("Cache-Control",""), @"max-age=(?<maxAge>\d+)").Groups["maxAge"]?.Value)

@(context.Variables.ContainsKey("maxAge") ? int.Parse((string)context.Variables["maxAge"]) : 3600)

@{
  string[] value;
  if (context.Request.Headers.TryGetValue("Authorization", out value))
  {
      if(value != null && value.Length > 0)
      {
          return Encoding.UTF8.GetString(Convert.FromBase64String(value[0]));
      }
  }
  return null;

}

Uso

A menos que a referência da política especifique o contrário, as expressões podem ser usadas como valores de atributos ou valores de texto em qualquer política de Gerenciamento de API.

Importante

Quando a política é definida, as expressões de política têm apenas verificação limitada. As expressões são executadas pelo gateway em tempo de execução. Todas as exceções geradas pelas expressões de política resultam em um erro de tempo de execução.

Tipos do .NET Framework permitidos em expressões de política

A tabela a seguir lista os tipos e membros do .NET Framework permitidos em expressões de política.

Tipo Membros com suporte
Newtonsoft.Json.Formatting Tudo
Newtonsoft.Json.JsonConvert SerializeObject, DeserializeObject
Newtonsoft.Json.Linq.Extensions Tudo
Newtonsoft.Json.Linq.JArray Tudo
Newtonsoft.Json.Linq.JConstructor Tudo
Newtonsoft.Json.Linq.JContainer Tudo
Newtonsoft.Json.Linq.JObject Tudo
Newtonsoft.Json.Linq.JProperty Tudo
Newtonsoft.Json.Linq.JRaw Tudo
Newtonsoft.Json.Linq.JToken Tudo
Newtonsoft.Json.Linq.JTokenType Tudo
Newtonsoft.Json.Linq.JValue Tudo
System.Array Tudo
System.BitConverter Tudo
System.Boolean Tudo
System.Byte Tudo
System.Char Tudo
System.Collections.Generic.Dictionary<TKey, TValue> Tudo
System.Collections.Generic.HashSet<T> Tudo
System.Collections.Generic.ICollection<T> Tudo
System.Collections.Generic.IDictionary<TKey, TValue> Tudo
System.Collections.Generic.IEnumerable<T> Tudo
System.Collections.Generic.IEnumerator<T> Tudo
System.Collections.Generic.IList<T> Tudo
System.Collections.Generic.IReadOnlyCollection<T> Tudo
System.Collections.Generic.IReadOnlyDictionary<TKey, TValue> Tudo
System.Collections.Generic.ISet<T> Tudo
System.Collections.Generic.KeyValuePair<TKey, TValue> Tudo
System.Collections.Generic.List<T> Tudo
System.Collections.Generic.Queue<T> Tudo
System.Collections.Generic.Stack<T> Tudo
System.Convert Tudo
System.DateTime (Construtor), Add, AddDays, AddHours, AddMilliseconds, AddMinutes, AddMonths, AddSeconds, AddTicks, AddYears, Date, Day, DayOfWeek, DayOfYear, DaysInMonth, Hour, IsDaylightSavingTime, IsLeapYear, MaxValue, Millisecond, Minute, MinValue, Month, Now, Parse, Second, Subtract, Ticks, TimeOfDay, Today, ToString, UtcNow, Year
System.DateTimeKind Utc
System.DateTimeOffset Tudo
System.Decimal Tudo
System.Double Tudo
System.Enum Parse, TryParse, ToString
System.Exception Tudo
System.Guid Tudo
System.Int16 Tudo
System.Int32 Tudo
System.Int64 Tudo
System.IO.StringReader Tudo
System.IO.StringWriter Tudo
System.Linq.Enumerable Tudo
System.Math Tudo
System.MidpointRounding Tudo
System.Net.IPAddress AddressFamily, Equals, GetAddressBytes, IsLoopback, Parse, TryParse, ToString
System.Net.WebUtility Tudo
System.Nullable Tudo
System.Random Tudo
System.SByte Tudo
System.Security.Cryptography.AsymmetricAlgorithm Tudo
System.Security.Cryptography.CipherMode Tudo
System.Security.Cryptography.HashAlgorithm Tudo
System.Security.Cryptography.HashAlgorithmName Tudo
System.Security.Cryptography.HMAC Tudo
System.Security.Cryptography.HMACMD5 Tudo
System.Security.Cryptography.HMACSHA1 Tudo
System.Security.Cryptography.HMACSHA256 Tudo
System.Security.Cryptography.HMACSHA384 Tudo
System.Security.Cryptography.HMACSHA512 Tudo
System.Security.Cryptography.KeyedHashAlgorithm Tudo
System.Security.Cryptography.MD5 Tudo
System.Security.Cryptography.Oid Tudo
System.Security.Cryptography.PaddingMode Tudo
System.Security.Cryptography.RNGCryptoServiceProvider Tudo
System.Security.Cryptography.RSA Tudo
System.Security.Cryptography.RSAEncryptionPadding Tudo
System.Security.Cryptography.RSASignaturePadding Tudo
System.Security.Cryptography.SHA1 Tudo
System.Security.Cryptography.SHA1Managed Tudo
System.Security.Cryptography.SHA256 Tudo
System.Security.Cryptography.SHA256Managed Tudo
System.Security.Cryptography.SHA384 Tudo
System.Security.Cryptography.SHA384Managed Tudo
System.Security.Cryptography.SHA512 Tudo
System.Security.Cryptography.SHA512Managed Tudo
System.Security.Cryptography.SymmetricAlgorithm Tudo
System.Security.Cryptography.X509Certificates.PublicKey Tudo
System.Security.Cryptography.X509Certificates.RSACertificateExtensions Tudo
System.Security.Cryptography.X509Certificates.X500DistinguishedName Name
System.Security.Cryptography.X509Certificates.X509Certificate Tudo
System.Security.Cryptography.X509Certificates.X509Certificate2 Tudo
System.Security.Cryptography.X509Certificates.X509ContentType Tudo
System.Security.Cryptography.X509Certificates.X509NameType Tudo
System.Single Tudo
System.String Tudo
System.StringComparer Tudo
System.StringComparison Tudo
System.StringSplitOptions Tudo
System.Text.Encoding Tudo
System.Text.RegularExpressions.Capture Index, Length, Value
System.Text.RegularExpressions.CaptureCollection Count, Item
System.Text.RegularExpressions.Group Captures, Success
System.Text.RegularExpressions.GroupCollection Count, Item
System.Text.RegularExpressions.Match Empty, Groups, Result
System.Text.RegularExpressions.Regex (Construtor), IsMatch, Match, Matches, Replace, Unescape, Split
System.Text.RegularExpressions.RegexOptions Tudo
System.Text.StringBuilder Tudo
System.TimeSpan Tudo
System.TimeZone Tudo
System.TimeZoneInfo.AdjustmentRule Tudo
System.TimeZoneInfo.TransitionTime Tudo
System.TimeZoneInfo Tudo
System.Tuple Tudo
System.UInt16 Tudo
System.UInt32 Tudo
System.UInt64 Tudo
System.Uri Tudo
System.UriPartial Tudo
System.Xml.Linq.Extensions Tudo
System.Xml.Linq.XAttribute Tudo
System.Xml.Linq.XCData Tudo
System.Xml.Linq.XComment Tudo
System.Xml.Linq.XContainer Tudo
System.Xml.Linq.XDeclaration Tudo
System.Xml.Linq.XDocument Todos, exceto Load
System.Xml.Linq.XDocumentType Tudo
System.Xml.Linq.XElement Tudo
System.Xml.Linq.XName Tudo
System.Xml.Linq.XNamespace Tudo
System.Xml.Linq.XNode Tudo
System.Xml.Linq.XNodeDocumentOrderComparer Tudo
System.Xml.Linq.XNodeEqualityComparer Tudo
System.Xml.Linq.XObject Tudo
System.Xml.Linq.XProcessingInstruction Tudo
System.Xml.Linq.XText Tudo
System.Xml.XmlNodeType Tudo

Variável de contexto

A variável context está implicitamente disponível em cada expressão de política. Seus membros:

  • Fornece informações relevantes para a solicitação e resposta da API, e propriedades relacionadas.
  • Todos são somente leitura.
Variável de contexto Valores de métodos, propriedades e parâmetros permitidos
context Api: IApi

Deployment

Decorrido: TimeSpan – intervalo de tempo entre o valor de Timestamp e a hora atual

GraphQL

LastError

Operation

Request

RequestId: Guid – identificador exclusivo da solicitação

Response

Subscription

Timestamp: DateTime – ponto no tempo em que a solicitação foi recebida

Tracing: bool – indica se o rastreamento está ativado ou desativado

Usuário

Variables: IReadOnlyDictionary<string, object>

void Trace(message: string)
context.Api Id: string

IsCurrentRevision: bool

Name: string

Path: string

Revision: string

ServiceUrl: IUrl

Version: string

Workspace: IWorkspace
context.Deployment Gateway

GatewayId: string (retorna 'managed' para gateways gerenciados)

Region: string

ServiceId: string

ServiceName: string

Certificates: IReadOnlyDictionary<string, X509Certificate2>
context.Deployment.Gateway Id: string (retorna 'managed' para gateways gerenciados)

InstanceId: string (retorna 'managed' para gateways gerenciados)

IsManaged: bool
context.GraphQL GraphQLArguments: IGraphQLDataObject

Parent: IGraphQLDataObject

Exemplos
context.LastError Source: string

Reason: string

Message: string

Scope: string

Section: string

Path: string

PolicyId: string

Para obter mais informações sobre context.LastError, confira Tratamento de erro.
context.Operation Id: string

Method: string

Name: string

UrlTemplate: string
context.Product ApprovalRequired: bool

Groups: IEnumerable<IGroup>

Id: string

Name: string

State: enum ProductState {NotPublished, Published}

SubscriptionsLimit: int?

SubscriptionRequired: bool

Workspace: IWorkspace
context.Request Body: IMessageBody ou null se a solicitação não tiver um corpo.

Certificate: System.Security.Cryptography.X509Certificates.X509Certificate2

Headers: IReadOnlyDictionary<string, string[]>

IpAddress: string

MatchedParameters: IReadOnlyDictionary<string, string>

Method: string

OriginalUrl: IUrl

Url: IUrl

PrivateEndpointConnection: IPrivateEndpointConnection ou null se a solicitação não vier de uma conexão de ponto de extremidade privado.
string context.Request.Headers.GetValueOrDefault(headerName: string, defaultValue: string) headerName: string

defaultValue: string

Retorna valores de cabeçalho de solicitação separados por vírgula ou defaultValue se o cabeçalho não for encontrado.
context.Response Body: IMessageBody

Headers: IReadOnlyDictionary<string, string[]>

StatusCode: int

StatusReason: string
string context.Response.Headers.GetValueOrDefault(headerName: string, defaultValue: string) headerName: string

defaultValue: string

Retorna valores de cabeçalho de resposta separados por vírgula ou defaultValue se o cabeçalho não for encontrado.
context.Subscription CreatedDate: DateTime

EndDate: DateTime?

Id: string

Key: string

Name: string

PrimaryKey: string

SecondaryKey: string

StartDate: DateTime?
context.User Email: string

FirstName: string

Groups: IEnumerable<IGroup>

Id: string

Identities: IEnumerable<IUserIdentity>

LastName: string

Note: string

RegistrationDate: DateTime
IApi Id: string

Name: string

Path: string

Protocols: IEnumerable<string>

ServiceUrl: IUrl

SubscriptionKeyParameterNames: ISubscriptionKeyParameterNames
IGraphQLDataObject TBD

IGroup Id: string

Name: string
IMessageBody As<T>(bool preserveContent = false): Where T: string, byte[], JObject, JToken, JArray, XNode, XElement, XDocument

- Os métodos context.Request.Body.As<T> e context.Response.Body.As<T> leem o corpo de uma mensagem de solicitação ou resposta no tipo especificado T.

- Ou -

AsFormUrlEncodedContent(bool preserveContent = false)

- Os métodos context.Request.Body.AsFormUrlEncodedContent() e context.Response.Body.AsFormUrlEncodedContent() leem os dados de formulário codificados em URL no corpo de uma mensagem de solicitação ou resposta e retornam um objeto IDictionary<string, IList<string>. O objeto decodificado dá suporte a operações IDictionary e às seguintes expressões: ToQueryString(), JsonConvert.SerializeObject(), ToFormUrlEncodedContent().

Por padrão, os métodos As<T> e AsFormUrlEncodedContent():
  • Usam o fluxo de corpo da mensagem original.
  • Tornam o fluxo indisponível depois que retorna.

Para evitar isso e fazer com que o método opere em uma cópia do fluxo do corpo, defina o parâmetro preserveContent como true, conforme mostrado nos exemplos da política set-body.
IPrivateEndpointConnection Name: string

GroupId: string

MemberName: string

Para obter mais informações, consulte a REST API.
IUrl Host: string

Path: string

Port: int

Query: IReadOnlyDictionary<string, string[]>

QueryString: string

Scheme: string
ISubscriptionKeyParameterNames Header: string

Query: string
string IUrl.Query.GetValueOrDefault(queryParameterName: string, defaultValue: string) queryParameterName: string

defaultValue: string

Retorna valores de parâmetro de consulta separados por vírgula ou defaultValue se o parâmetro não for encontrado.
IUserIdentity Id: string

Provider: string
IWorkspace Id: string

Name: string
T context.Variables.GetValueOrDefault<T>(variableName: string, defaultValue: T) variableName: string

defaultValue: T

Retorna o valor da variável convertida para o tipo T ou defaultValue se a variável não for encontrada.

Esse método gerará uma exceção se o tipo especificado não corresponder ao tipo real da variável retornada.
BasicAuthCredentials AsBasic(input: this string) input: string

Se o parâmetro de entrada contiver um valor válido de cabeçalho de solicitação de autorização de Autenticação Básica HTTP, o método retornará um objeto do tipo BasicAuthCredentials, caso contrário, o método retornará nulo.
bool TryParseBasic(input: this string, result: out BasicAuthCredentials) input: string

result: out BasicAuthCredentials

Se o parâmetro de entrada contiver um valor de autorização de Autenticação Básica HTTP válido no cabeçalho de solicitação, o método retornará true e o parâmetro do resultado conterá um valor do tipo BasicAuthCredentials, caso contrário, o método retornará false.
BasicAuthCredentials Password: string

UserId: string
Jwt AsJwt(input: this string) input: string

Se o parâmetro de entrada contiver um valor válido de token JWT, o método retornará um objeto do tipo Jwt, caso contrário, o método retornará null.
bool TryParseJwt(input: this string, result: out Jwt) input: string

result: out Jwt

Se o parâmetro de entrada contiver um valor válido de token JWT, o método retornará true e o parâmetro de resultado conterá um valor do tipo Jwt, caso contrário, o método retornará false.
Jwt Algorithm: string

Audiences: IEnumerable<string>

Claims: IReadOnlyDictionary<string, string[]>

ExpirationTime: DateTime?

Id: string

Issuer: string

IssuedAt: DateTime?

NotBefore: DateTime?

Subject: string

Type: string
string Jwt.Claims.GetValueOrDefault(claimName: string, defaultValue: string) claimName: string

defaultValue: string

Retorna valores de declaração separados por vírgula ou defaultValue se o cabeçalho não for encontrado.
byte[] Encrypt(input: this byte[], alg: string, key:byte[], iv:byte[]) input – texto sem formatação a ser criptografado

alg – nome de um algoritmo de criptografia simétrico

key – chave de criptografia

iv – vetor de inicialização

Retorna texto sem formatação criptografado.
byte[] Encrypt(input: this byte[], alg: System.Security.Cryptography.SymmetricAlgorithm) input – texto sem formatação a ser criptografado

alg – algoritmo de criptografia

Retorna texto sem formatação criptografado.
byte[] Encrypt(input: this byte[], alg: System.Security.Cryptography.SymmetricAlgorithm, key:byte[], iv:byte[]) input – texto sem formatação a ser criptografado

alg – algoritmo de criptografia

key – chave de criptografia

iv – vetor de inicialização

Retorna texto sem formatação criptografado.
byte[] Decrypt(input: this byte[], alg: string, key:byte[], iv:byte[]) input – texto criptografado a ser descriptografado

alg – nome de um algoritmo de criptografia simétrico

key – chave de criptografia

iv – vetor de inicialização

Retorna o texto sem formatação.
byte[] Decrypt(input: this byte[], alg: System.Security.Cryptography.SymmetricAlgorithm) input – texto criptografado a ser descriptografado

alg – algoritmo de criptografia

Retorna o texto sem formatação.
byte[] Decrypt(input: this byte[], alg: System.Security.Cryptography.SymmetricAlgorithm, key:byte[], iv:byte[]) input – texto criptografado a ser descriptografado

alg – algoritmo de criptografia

key – chave de criptografia

iv – vetor de inicialização

Retorna o texto sem formatação.
bool VerifyNoRevocation(input: this System.Security.Cryptography.X509Certificates.X509Certificate2) Executa uma validação de cadeia X.509 sem verificar o status de revogação do certificado.

input – objeto de certificado

Retornará true se a validação for bem-sucedida e false se a validação falhar.

Para obter mais informações sobre como trabalhar com políticas, consulte:

Para mais informações:

  • Veja como fornecer informações de contexto ao serviço de back-end. Use as políticas Definir parâmetro de cadeia de caracteres de consulta e Definir cabeçalho HTTP para fornecer essas informações.
  • Como usar a política Validar JWT para pré-autorizar o acesso a operações baseadas em declarações de token.
  • Veja como usar um rastreamento de Inspetor de API para detectar como as políticas são avaliadas e os resultados da avaliações.
  • Como usar expressões com as políticas Obter do cache e Armazenar em cache para configurar o cache de resposta de Gerenciamento de API. Defina uma duração que coincida com o cache de resposta do serviço de back-end conforme especificado pela diretiva Cache-Control do serviço de backup.
  • Veja como realizar a filtragem de conteúdo. Remova os elementos de dados da resposta recebida do back-end usando as políticas Controlar fluxo e Definir corpo.
  • Para baixar as instruções de política, confira o repositório GitHub api-management-samples/policies.