Política SetOAuthV2Info

Esta página aplica-se ao Apigee e ao Apigee Hybrid.

Veja a documentação do Apigee Edge.

A política SetOAuthV2Info permite-lhe adicionar ou atualizar atributos personalizados associados a um token de acesso. Os atributos personalizados podem incluir elementos como o nome do departamento, um ID do cliente ou um identificador de sessão. Consulte também Personalizar símbolos e códigos de autorização.

Só pode adicionar ou modificar atributos personalizados. Não pode usar esta política para alterar campos como scope, status, expires_in, developer_email, client_id, org_name ou refresh_count. Se já existir um atributo, esta política atualiza-o. Se não existir, a política adiciona-o. O token de acesso referenciado tem de ser válido e estar num estado aprovado.

Esta política é uma política extensível e a utilização desta política pode ter implicações de custo ou utilização, consoante a sua licença do Apigee. Para ver informações sobre os tipos de políticas e as implicações de utilização, consulte Tipos de políticas.

Amostras

Exemplo básico

Segue-se um exemplo de uma política usada para atualizar uma chave de acesso OAuth 2.0. O exemplo abaixo localiza o token de acesso na mensagem de pedido procurando um parâmetro de consulta denominado access_token. Quando um token de acesso é apresentado por uma app cliente, a política abaixo localiza o token de acesso no parâmetro de consulta. Em seguida, atualiza o perfil da chave de acesso. Adiciona uma propriedade personalizada denominada department.id ao perfil.

<SetOAuthV2Info name="SetOAuthV2Info">
  <AccessToken ref="request.queryparam.access_token"></AccessToken>
  <Attributes>
    <Attribute name="department.id" ref="request.queryparam.department_id"></Attribute>
  </Attributes>
</SetOAuthV2Info>

Referência do elemento

A referência do elemento descreve os elementos e os atributos da política SetOAuthV2.

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<SetOAuthV2Info async="false" continueOnError="false" enabled="true" name="SetOAuthV2Info-1">
    <DisplayName>Set OAuth v2.0 Info 1</DisplayName>
    <AccessToken ref={some-variable}></AccessToken>
    <Attributes/>
</SetOAuthV2Info>
</xml>

Atributos <SetOAuthV2Info>

<SetOAuthV2Info async="false" continueOnError="false" enabled="true" name="Set-OAuth-v20-Info-1">

The following table describes attributes that are common to all policy parent elements:

Attribute Description Default Presence
name

The internal name of the policy. The value of the name attribute can contain letters, numbers, spaces, hyphens, underscores, and periods. This value cannot exceed 255 characters.

Optionally, use the <DisplayName> element to label the policy in the management UI proxy editor with a different, natural-language name.

N/A Required
continueOnError

Set to false to return an error when a policy fails. This is expected behavior for most policies.

Set to true to have flow execution continue even after a policy fails. See also:

false Optional
enabled

Set to true to enforce the policy.

Set to false to turn off the policy. The policy will not be enforced even if it remains attached to a flow.

true Optional
async

This attribute is deprecated.

false Deprecated

<DisplayName> element

Use in addition to the name attribute to label the policy in the management UI proxy editor with a different, natural-language name.

<DisplayName>Policy Display Name</DisplayName>
Default

N/A

If you omit this element, the value of the policy's name attribute is used.

Presence Optional
Type String

Elemento <AccessToken>

Identifica a variável onde o token de acesso está localizado. Por exemplo, se o token de acesso estiver anexado à mensagem de pedido como um parâmetro de consulta, especifique request.queryparam.access_token. Pode usar qualquer variável válida que faça referência ao token. Em alternativa, pode transmitir a string do token literal (caso raro).

 <AccessToken ref="request.queryparam.access_token"></AccessToken>
Predefinição: N/A
Presença: Obrigatória
Tipo: String

Atributos

Atributo Descrição Predefinição Presença
ref

Uma variável de token de acesso. Normalmente, é obtido de uma variável de fluxo.

N/A Opcional

Elemento <Attributes>

Um conjunto de atributos no perfil do token de acesso que vai ser modificado ou aumentado.

Predefinição: N/A
Presença: Obrigatória
Tipo: N/A

Elemento <Attributes>/<Attribute>

Um atributo individual a atualizar.

O atributo name identifica a propriedade personalizada do perfil do token de acesso a ser atualizada. Este exemplo mostra como usar um valor de variável referenciado e um valor estático.

  <Attributes>
    <Attribute name="department.id" ref="request.queryparam.department_id"></Attribute>
    <Attribute name="foo">bar</Attribute>
  </Attributes>
Predefinição: N/A
Presença: Opcional
Tipo: N/A

Atributos

Atributo Descrição Predefinição Presença
nome O nome do atributo do perfil a adicionar ou alterar. N/A
ref

O valor a atribuir ao atributo do perfil.

N/A Opcional

Variáveis de fluxo

Em caso de êxito, são definidas as seguintes variáveis de fluxo:

  • oauthv2accesstoken.{policyName}.access_token
  • oauthv2accesstoken.{policyName}.client_id
  • oauthv2accesstoken.{policyName}.refresh_count
  • oauthv2accesstoken.{policyName}.organization_name
  • oauthv2accesstoken.{policyName}.expires_in //--in seconds
  • oauthv2accesstoken.{policyName}.refresh_token_expires_in //--in seconds
  • oauthv2accesstoken.{policyName}.issued_at
  • oauthv2accesstoken.{policyName}.status
  • oauthv2accesstoken.{policyName}.api_product_list
  • oauthv2accesstoken.{policyName}.token_type
  • oauthv2accesstoken.{policyName}.{custom_attribute_name}

Esquema

Cada tipo de política é definido por um esquema XML (.xsd). Para referência, os esquemas de políticas estão disponíveis no GitHub.

Referência de erro

This section describes the fault codes and error messages that are returned and fault variables that are set by Apigee when this policy triggers an error. This information is important to know if you are developing fault rules to handle faults. To learn more, see What you need to know about policy errors and Handling faults.

Runtime errors

These errors can occur when the policy executes.

Fault code HTTP status Cause
steps.oauth.v2.access_token_expired 500 The access token sent to the policy is expired.
steps.oauth.v2.invalid_access_token 500 The access token sent to the policy is invalid.
steps.oauth.v2.InvalidAPICallAsNoApiProductMatchFound 401 Please see Oauth2.0 Access Token Verification throws "Invalid API call as no apiproduct match found" error for information about troubleshooting this error.

Deployment errors

Refer to the message reported in the UI for information about deployment errors.

Fault variables

These variables are set when this policy triggers an error at runtime.

Variables Where Example
fault.name="fault_name" fault_name is the name of the fault, as listed in the Runtime errors table above. The fault name is the last part of the fault code. fault.name = "invalid_access_token"
oauthV2.policy_name.failed policy_name is the user-specified name of the policy that threw the fault. oauthV2.SetTokenInfo.failed = true
oauthV2.policy_name.fault.name policy_name is the user-specified name of the policy that threw the fault. oauthV2.SetTokenInfo.fault.name = invalid_access_token
oauthv2.policy_name.fault.cause policy_name is the user-specified name of the policy that threw the fault. oauthV2.SetTokenInfo.cause = Invalid Access Token

Example error response

{
  "fault": {
    "faultstring": "Invalid Access Token",
    "detail": {
      "errorcode": "keymanagement.service.invalid_access_token"
    }
  }
}

Example fault rule

<FaultRule name=SetOAuthV2Info Faults">
    <Step>
        <Name>AM-InvalidTokenResponse</Name>
        <Condition>(fault.name = "invalid_access_token")</Condition>
    </Step>
    <Condition>(oauthV2.failed = true) </Condition>
</FaultRule>

Tópicos relacionados