

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# 使用 API Gateway Lambda 授權方
<a name="apigateway-use-lambda-authorizer"></a>

使用 *Lambda 授權方* (先前稱為*自訂授權方*) 控制存取 API。當用戶端請求 API 的方法時，API Gateway 會呼叫您的 Lambda 授權方。Lambda 授權方會將呼叫者的身分當作輸入項，並傳回 IAM 政策做為輸出。

使用 Lambda 授權方實作自訂授權機制。您的方案可以使用請求參數來判斷呼叫者的身分，或使用承載字符驗證策略，例如 OAuth 或 SAML。在 API Gateway REST API 主控台中使用 AWS CLI或 AWS SDK 建立 Lambda 授權方。

## Lambda 授權方授權工作流程
<a name="api-gateway-lambda-authorizer-flow"></a>

下圖說明 Lambda 授權方的授權工作流程。

![\[API Gateway Lambda 授權工作流程\]](http://docs.aws.amazon.com/zh_tw/apigateway/latest/developerguide/images/custom-auth-workflow.png)


**API Gateway Lambda 授權工作流程**

1. 用戶端在 API Gateway API 上呼叫方法，傳遞承載字符或請求參數。

1. API Gateway 會確認是否有使用 Lambda 授權方設定方法請求。如果已設定，API Gateway 將會呼叫 Lambda 函式。

1. Lambda 函數會驗證呼叫者。函數可以利用以下方式進行驗證：
   + 呼叫 OAuth 提供者以取得 OAuth 存取字符。
   + 呼叫 SAML 提供者以取得 SAML 聲明。
   + 根據請求參數值產生 IAM 政策。
   + 從資料庫擷取憑證。

1. Lambda 函數會傳回 IAM 政策和主體識別碼。如果 Lambda 函數未傳回該資訊，呼叫便失敗。

1. API Gateway 會評估 IAM 政策。
   + 如果拒絕存取，API Gateway 會傳回一個適當的 HTTP 狀態碼，例如 `403 ACCESS_DENIED`。
   + 如果允許存取，API Gateway 會調用該方法。

     如果啟用授權快取，API Gateway 會快取該政策，如此就不需要再次調用 Lambda 授權方函式。請確認您的政策適用於 API 中的所有資源和方法。

您可以自訂 `403 ACCESS_DENIED` 或 `401 UNAUTHORIZED` 閘道回應。如需詳細資訊，請參閱 [API Gateway 中 REST API 的閘道回應](api-gateway-gatewayResponse-definition.md)。

## 選擇 Lambda 授權方的類型
<a name="api-gateway-lambda-authorizer-choose"></a>

Lambda 授權方有兩種類型：

**請求參數型 Lambda 授權方 (`REQUEST` 授權方)**  
`REQUEST` 授權方利用標頭、查詢字串參數、[`stageVariables`](api-gateway-mapping-template-reference.md#stagevariables-template-reference) 和 [`$context`](api-gateway-mapping-template-reference.md#context-variable-reference) 變數的組合方式接呼叫者的身分。您可以使用 `REQUEST` 授權方，以根據來自多個身分來源的資訊建立精細政策，例如 `$context.path` 和 `$context.httpMethod` 內容變數。  
如果您開啟 `REQUEST` 授權方的授權快取，API Gateway 會驗證請求中是否存在所有指定的身分來源。如果指定的身分來源遺漏、為 Null 或空白，API Gateway 會傳回 `401 Unauthorized` HTTP 回應，而無需呼叫 Lambda 授權方函數。定義多個身分來源時，會使用這些來源衍生授權方的快取金鑰，並保留順序。您可以使用多個身分來源來定義精細快取金鑰。  
如果您變更任何快取金鑰部分並重新部署您的 API，則授權方會捨棄快取的政策文件，並產生新的政策文件。  
如果關閉 `REQUEST` 授權方的授權快取，則 API Gateway 會直接將請求傳遞給 Lambda 函數。

**以字符為基礎的 Lambda 授權方 (`TOKEN` 授權方)**  
`TOKEN` 授權方會以承載字符接收呼叫者的身分，例如 JSON Web Token (JWT) 或 OAuth 字符。  
如果您開啟 `TOKEN` 授權方的授權快取，則字符來源中指定的標頭名稱會成為快取金鑰。  
此外，您可以使用字符驗證來輸入 RegEx 陳述式。API Gateway 會對此表達式執行輸入字符的初始驗證，並在成功驗證時調用 Lambda 授權方函數。這樣做有助於減少對 API 的呼叫。  
`IdentityValidationExpression` 屬性僅支援 `TOKEN` 授權方。如需詳細資訊，請參閱[x-amazon-apigateway-authorizer 物件](api-gateway-swagger-extensions-authorizer.md)。

**注意**  
建議您使用 `REQUEST` 授權方來控制對 API 的存取。與使用 `TOKEN` 授權方時的單一身分來源相比，您可以在使用 `REQUEST` 授權方時，根據多個身分來源控制對 API 的存取。此外，您可以使用 `REQUEST` 授權方的多個身分來源來分隔快取金鑰。

## `REQUEST` 授權方 Lambda 函數範例
<a name="api-gateway-lambda-authorizer-request-lambda-function-create"></a>

下列範例程式碼會建立 Lambda 授權方函數，當用戶端提供的 `HeaderAuth1` 標頭、`QueryString1` 查詢參數和階段變數 `StageVar1` 分別符合 `headerValue1`、`queryValue1` 和 `stageValue1` 指定值時，允許請求。

------
#### [ Node.js ]

```
// A simple request-based authorizer example to demonstrate how to use request 
// parameters to allow or deny a request. In this example, a request is  
// authorized if the client-supplied HeaderAuth1 header, QueryString1
// query parameter, and stage variable of StageVar1 all match
// specified values of 'headerValue1', 'queryValue1', and 'stageValue1',
// respectively.
    
export const handler = function(event, context, callback) {
    console.log('Received event:', JSON.stringify(event, null, 2));
    
    // Retrieve request parameters from the Lambda function input:
    var headers = event.headers;
    var queryStringParameters = event.queryStringParameters;
    var pathParameters = event.pathParameters;
    var stageVariables = event.stageVariables;
        
    // Parse the input for the parameter values
    var tmp = event.methodArn.split(':');
    var apiGatewayArnTmp = tmp[5].split('/');
    var awsAccountId = tmp[4];
    var region = tmp[3];
    var restApiId = apiGatewayArnTmp[0];
    var stage = apiGatewayArnTmp[1];
    var method = apiGatewayArnTmp[2];
    var resource = '/'; // root resource
    if (apiGatewayArnTmp[3]) {
        resource += apiGatewayArnTmp[3];
    }
        
    // Perform authorization to return the Allow policy for correct parameters and 
    // the 'Unauthorized' error, otherwise.

     
    if (headers.HeaderAuth1 === "headerValue1"
        && queryStringParameters.QueryString1 === "queryValue1"
        && stageVariables.StageVar1 === "stageValue1") {
        callback(null, generateAllow('me', event.methodArn));
    }  else {
        callback(null, generateDeny('me', event.methodArn));
    }
}
     
// Help function to generate an IAM policy
var generatePolicy = function(principalId, effect, resource) {
    // Required output:
    var authResponse = {};
    authResponse.principalId = principalId;
    if (effect && resource) {
        var policyDocument = {};
        policyDocument.Version = '2012-10-17'; // default version
        policyDocument.Statement = [];
        var statementOne = {};
        statementOne.Action = 'execute-api:Invoke'; // default action
        statementOne.Effect = effect;
        statementOne.Resource = resource;
        policyDocument.Statement[0] = statementOne;
        authResponse.policyDocument = policyDocument;
    }
    // Optional output with custom properties of the String, Number or Boolean type.
    authResponse.context = {
        "stringKey": "stringval",
        "numberKey": 123,
        "booleanKey": true
    };
    return authResponse;
}
     
var generateAllow = function(principalId, resource) {
    return generatePolicy(principalId, 'Allow', resource);
}
     
var generateDeny = function(principalId, resource) {
    return generatePolicy(principalId, 'Deny', resource);
}
```

------
#### [ Python ]

```
# A simple request-based authorizer example to demonstrate how to use request
# parameters to allow or deny a request. In this example, a request is
# authorized if the client-supplied headerauth1 header, QueryString1
# query parameter, and stage variable of StageVar1 all match
# specified values of 'headerValue1', 'queryValue1', and 'stageValue1',
# respectively.

def lambda_handler(event, context):
    print(event)

    # Retrieve request parameters from the Lambda function input:
    headers = event['headers']
    queryStringParameters = event['queryStringParameters']
    pathParameters = event['pathParameters']
    stageVariables = event['stageVariables']

    # Parse the input for the parameter values
    tmp = event['methodArn'].split(':')
    apiGatewayArnTmp = tmp[5].split('/')
    awsAccountId = tmp[4]
    region = tmp[3]
    restApiId = apiGatewayArnTmp[0]
    stage = apiGatewayArnTmp[1]
    method = apiGatewayArnTmp[2]
    resource = '/'

    if (apiGatewayArnTmp[3]):
        resource += apiGatewayArnTmp[3]

    # Perform authorization to return the Allow policy for correct parameters
    # and the 'Unauthorized' error, otherwise.

    if (headers['HeaderAuth1'] == "headerValue1" and queryStringParameters['QueryString1'] == "queryValue1" and stageVariables['StageVar1'] == "stageValue1"):
        response = generateAllow('me', event['methodArn'])
        print('authorized')
        return response
    else:
        print('unauthorized')
        response = generateDeny('me', event['methodArn'])
        return response
    # Help function to generate IAM policy


def generatePolicy(principalId, effect, resource):
    authResponse = {}
    authResponse['principalId'] = principalId
    if (effect and resource):
        policyDocument = {}
        policyDocument['Version'] = '2012-10-17'
        policyDocument['Statement'] = []
        statementOne = {}
        statementOne['Action'] = 'execute-api:Invoke'
        statementOne['Effect'] = effect
        statementOne['Resource'] = resource
        policyDocument['Statement'] = [statementOne]
        authResponse['policyDocument'] = policyDocument

    authResponse['context'] = {
        "stringKey": "stringval",
        "numberKey": 123,
        "booleanKey": True
    }

    return authResponse


def generateAllow(principalId, resource):
    return generatePolicy(principalId, 'Allow', resource)


def generateDeny(principalId, resource):
    return generatePolicy(principalId, 'Deny', resource)
```

------

在此範例中，Lambda 授權方函數會檢查輸入參數，並運作如下：
+ 如果所有的必要參數值皆符合預期值，授權方函數會傳回一個 `200 OK` HTTP 回應和一個如下的 IAM 政策，而且方法請求會成功：

------
#### [ JSON ]

****  

  ```
  {
    "Version":"2012-10-17",		 	 	 
    "Statement": [
      {
        "Action": "execute-api:Invoke",
        "Effect": "Allow",
        "Resource": "arn:aws:execute-api:us-east-1:123456789012:ivdtdhp7b5/ESTestInvoke-stage/GET/"
      }
    ]
  }
  ```

------
+ 否則，授權方函數會傳回 `401 Unauthorized` HTTP 回應，而且方法請求失敗。

除了傳回 IAM 政策，Lambda 授權方函數還必須傳回發起人的主要識別符。也可以選擇傳回 `context` 物件，其中包含可傳入整合後端的其他資訊。如需詳細資訊，請參閱[來自 API Gateway Lambda 授權方的輸出](api-gateway-lambda-authorizer-output.md)。

在生產程式碼中，您可能需要驗證使用者，再授予授權。您可以在 Lambda 函數中新增驗證邏輯，方法為依照該提供者文件中的指示來呼叫驗證提供者。

## `TOKEN` 授權方 Lambda 函數範例
<a name="api-gateway-lambda-authorizer-token-lambda-function-create"></a>

下列範例程式碼會建立 `TOKEN` Lambda 授權方函數，允許呼叫者在用戶端提供的字符值為 `allow` 時，調用方法。如果字符值為 `deny`，則不允許呼叫者調用請求。如果字符值為 `unauthorized` 或空字串，則授權方函數會傳回 `401 UNAUTHORIZED` 回應。

------
#### [ Node.js ]

```
// A simple token-based authorizer example to demonstrate how to use an authorization token 
// to allow or deny a request. In this example, the caller named 'user' is allowed to invoke 
// a request if the client-supplied token value is 'allow'. The caller is not allowed to invoke 
// the request if the token value is 'deny'. If the token value is 'unauthorized' or an empty
// string, the authorizer function returns an HTTP 401 status code. For any other token value, 
// the authorizer returns an HTTP 500 status code. 
// Note that token values are case-sensitive.

export const handler =  function(event, context, callback) {
    var token = event.authorizationToken;
    switch (token) {
        case 'allow':
            callback(null, generatePolicy('user', 'Allow', event.methodArn));
            break;
        case 'deny':
            callback(null, generatePolicy('user', 'Deny', event.methodArn));
            break;
        case 'unauthorized':
            callback("Unauthorized");   // Return a 401 Unauthorized response
            break;
        default:
            callback("Error: Invalid token"); // Return a 500 Invalid token response
    }
};

// Help function to generate an IAM policy
var generatePolicy = function(principalId, effect, resource) {
    var authResponse = {};
    
    authResponse.principalId = principalId;
    if (effect && resource) {
        var policyDocument = {};
        policyDocument.Version = '2012-10-17'; 
        policyDocument.Statement = [];
        var statementOne = {};
        statementOne.Action = 'execute-api:Invoke'; 
        statementOne.Effect = effect;
        statementOne.Resource = resource;
        policyDocument.Statement[0] = statementOne;
        authResponse.policyDocument = policyDocument;
    }
    
    // Optional output with custom properties of the String, Number or Boolean type.
    authResponse.context = {
        "stringKey": "stringval",
        "numberKey": 123,
        "booleanKey": true
    };
    return authResponse;
}
```

------
#### [ Python ]

```
# A simple token-based authorizer example to demonstrate how to use an authorization token
# to allow or deny a request. In this example, the caller named 'user' is allowed to invoke
# a request if the client-supplied token value is 'allow'. The caller is not allowed to invoke
# the request if the token value is 'deny'. If the token value is 'unauthorized' or an empty
# string, the authorizer function returns an HTTP 401 status code. For any other token value,
# the authorizer returns an HTTP 500 status code.
# Note that token values are case-sensitive.

import json


def lambda_handler(event, context):
    token = event['authorizationToken']
    if token == 'allow':
        print('authorized')
        response = generatePolicy('user', 'Allow', event['methodArn'])
    elif token == 'deny':
        print('unauthorized')
        response = generatePolicy('user', 'Deny', event['methodArn'])
    elif token == 'unauthorized':
        print('unauthorized')
        raise Exception('Unauthorized')  # Return a 401 Unauthorized response
        return 'unauthorized'
    try:
        return json.loads(response)
    except BaseException:
        print('unauthorized')
        return 'unauthorized'  # Return a 500 error


def generatePolicy(principalId, effect, resource):
    authResponse = {}
    authResponse['principalId'] = principalId
    if (effect and resource):
        policyDocument = {}
        policyDocument['Version'] = '2012-10-17'
        policyDocument['Statement'] = []
        statementOne = {}
        statementOne['Action'] = 'execute-api:Invoke'
        statementOne['Effect'] = effect
        statementOne['Resource'] = resource
        policyDocument['Statement'] = [statementOne]
        authResponse['policyDocument'] = policyDocument
    authResponse['context'] = {
        "stringKey": "stringval",
        "numberKey": 123,
        "booleanKey": True
    }
    authResponse_JSON = json.dumps(authResponse)
    return authResponse_JSON
```

------

在此範例中，當 API 收到方法請求時，API Gateway 會在 `event.authorizationToken` 屬性中將來源字符傳遞至此 Lambda 授權方函數。Lambda 授權方函數會讀取字符，並運作如下：
+ 如果字符值為 `allow`，授權方函數會傳回一個 `200 OK` HTTP 回應和一個如下的 IAM 政策，而且方法請求會成功：

------
#### [ JSON ]

****  

  ```
  {
    "Version":"2012-10-17",		 	 	 
    "Statement": [
      {
        "Action": "execute-api:Invoke",
        "Effect": "Allow",
        "Resource": "arn:aws:execute-api:us-east-1:123456789012:ivdtdhp7b5/ESTestInvoke-stage/GET/"
      }
    ]
  }
  ```

------
+ 如果字符值為 `deny`，授權方函數會傳回一個 `200 OK` HTTP 回應和一個如下的 `Deny` IAM 政策，而且方法請求會失敗：

------
#### [ JSON ]

****  

  ```
  {
    "Version":"2012-10-17",		 	 	 
    "Statement": [
      {
        "Action": "execute-api:Invoke",
        "Effect": "Deny",
        "Resource": "arn:aws:execute-api:us-east-1:123456789012:ivdtdhp7b5/ESTestInvoke-stage/GET/"
      }
    ]
  }
  ```

------
**注意**  
在測試環境之外，則 API Gateway 會傳回 `403 Forbidden` HTTP 回應，而且方法請求會失敗。
+ 如果符記值為 `unauthorized` 或空字串，授權方函數會傳回 `401 Unauthorized` HTTP 回應，而且方法呼叫會失敗。
+ 如果符記為其他值，用戶端會收到 `500 Invalid token` 回應，而且方法呼叫會失敗。

除了傳回 IAM 政策，Lambda 授權方函數還必須傳回發起人的主要識別符。也可以選擇傳回 `context` 物件，其中包含可傳入整合後端的其他資訊。如需詳細資訊，請參閱[來自 API Gateway Lambda 授權方的輸出](api-gateway-lambda-authorizer-output.md)。

在生產程式碼中，您可能需要驗證使用者，再授予授權。您可以在 Lambda 函數中新增驗證邏輯，方法為依照該提供者文件中的指示來呼叫驗證提供者。

## Lambda 授權方函數的其他範例
<a name="api-gateway-lambda-authorizer-lambda-function-create"></a>

下列清單顯示 Lambda 授權方函數的其他範例。您可以在與您建立 API 的相同帳戶或不同帳戶中建立 Lambda 函數。

對於先前的範例 Lambda 函數，您可以使用內建的 [AWSLambdaBasicExecutionRole](https://docs.aws.amazon.com/lambda/latest/dg/lambda-intro-execution-role.html)，因為這些函數不會呼叫其他 AWS 服務。如果您的 Lambda 函數呼叫其他 AWS 服務，您將需要將 IAM 執行角色指派給 Lambda 函數。若要建立角色，請依照 [AWS Lambda 執行角色](https://docs.aws.amazon.com/lambda/latest/dg/lambda-intro-execution-role.html)中的指示。

**Lambda 授權方函數的其他範例**
+  如需範例應用程式，請參閱 GitHub 上的 [Open Banking Brazil - Authorization Samples](https://github.com/aws-samples/openbanking-brazilian-auth-samples)。
+  如需更多的範例 Lambda 函數，請參閱 GitHub 上的 [aws-apigateway-lambda-authorizer-blueprints](https://github.com/awslabs/aws-apigateway-lambda-authorizer-blueprints)。
+ 您可以建立 Lambda 授權方，以使用 Amazon Cognito 使用者集區對使用者進行驗證，並使用 Verified Permissions 根據政策存放區授權給呼叫者。如需詳細資訊，請參閱[利用 Verified Permissions 根據身分的屬性控制存取權](apigateway-lambda-authorizer-verified-permissions.md)。
+ Lambda 主控台會提供 Python 藍圖，您可以選擇 **Use a blueprint (使用藍圖)**，並選擇 **api-gateway-authorizer-python** 藍圖來使用此藍圖。

# 設定 API Gateway Lambda 授權方
<a name="configure-api-gateway-lambda-authorization"></a>

建立 Lambda 函數後，可以將 Lambda 函數設定為 API 的授權方。然後，可以設定方法來調用 Lambda 授權方，以判斷呼叫者是否可以調用您的方法。您可以在與您建立 API 的相同帳戶或不同帳戶中建立 Lambda 函數。

您可以使用 API Gateway 主控台的內建工具，或使用 [Postman](https://www.postman.com/) 來測試 Lambda 授權方。如需有關如何使用 Postman 測試 Lambda 授權方函數的指示，請參閱 [使用 API Gateway Lambda 授權方呼叫 API](call-api-with-api-gateway-lambda-authorization.md)。

## 設定 Lambda 授權方 (主控台)
<a name="configure-api-gateway-lambda-authorization-with-console"></a>

 下列程序顯示如何在 API Gateway REST API 主控台建立 Lambda 授權方。若要進一步了解不同類型的 Lambda 授權方，請參閱 [選擇 Lambda 授權方的類型](apigateway-use-lambda-authorizer.md#api-gateway-lambda-authorizer-choose)。

------
#### [ REQUEST authorizer ]

**設定 `REQUEST` Lambda 授權方**

1. 在以下網址登入 API Gateway 主控台：[https://console.aws.amazon.com/apigateway](https://console.aws.amazon.com/apigateway)。

1. 選取 API，然後選擇**授權方**。

1. 選擇**建立授權方**。

1. 針對**授權方名稱**，輸入授權方的名稱。

1. 針對**授權方類型**，選取 **Lambda**。

1. 針對 **Lambda 函數**，選取您建立 Lambda 授權方函數 AWS 區域 的 ，然後輸入函數名稱。

1. 將 **Lambda 調用角色**保留空白，以便讓 API Gateway REST API 主控台設定資源型政策。此政策會授與 API Gateway 許可，以調用 Lambda 授權方函數。您也可以選擇輸入 IAM 角色的名稱，以允許 API Gateway 調用 Lambda 授權方函數。如需範例角色，請參閱 [建立可擔任的 IAM 角色](integrating-api-with-aws-services-lambda.md#api-as-lambda-proxy-setup-iam-role-policies)。

1. 針對 **Lambda 事件承載**，選取**請求**。

1. 針對**身分來源類型**，選取參數類型。支援的參數類型為 `Header`、`Query string`、`Stage variable` 與 `Context`。若要新增更多身分來源，請選擇**新增參數**。

1. 若要快取授權方產生的授權政策，請將**授權快取**保持開啟狀態。啟用政策快取時，您可以修改 **TTL** 值。將 **TTL** 設定為零會停用政策快取。

   如果啟用快取，您的授權方必須傳回適用於 API 之所有方法的政策。若要強制執行方法特定的政策，請使用內容變數 `$context.path` 和 `$context.httpMethod`。

1. 選擇**建立授權方**。

------
#### [ TOKEN authorizer ]

**設定 `TOKEN` Lambda 授權方**

1. 在以下網址登入 API Gateway 主控台：[https://console.aws.amazon.com/apigateway](https://console.aws.amazon.com/apigateway)。

1. 選取 API，然後選擇**授權方**。

1. 選擇**建立授權方**。

1. 針對**授權方名稱**，輸入授權方的名稱。

1. 針對**授權方類型**，選取 **Lambda**。

1. 針對 **Lambda 函數**，選取您建立 Lambda 授權方函數 AWS 區域 的 ，然後輸入函數名稱。

1. 將 **Lambda 調用角色**保留空白，以便讓 API Gateway REST API 主控台設定資源型政策。此政策會授與 API Gateway 許可，以調用 Lambda 授權方函數。您也可以選擇輸入 IAM 角色的名稱，以允許 API Gateway 調用 Lambda 授權方函數。如需範例角色，請參閱 [建立可擔任的 IAM 角色](integrating-api-with-aws-services-lambda.md#api-as-lambda-proxy-setup-iam-role-policies)。

1. 針對 **Lambda 事件承載**，選取**權杖**。

1. 針對**權杖來源**，輸入包含授權權杖的標頭名稱。呼叫者必須包含此名稱的標頭，才能將授權字符傳送到 Lambda 授權方。

1. 或者，針對**符記驗證**，輸入 RegEx 陳述式。API Gateway 會對此表達式執行輸入字符的初始驗證，並在成功驗證時調用授權方。

1. 若要快取授權方產生的授權政策，請將**授權快取**保持開啟狀態。啟用政策快取時，**權杖來源**中指定的標頭名稱會成為快取金鑰。啟用政策快取時，您可以修改 **TTL** 值。將 **TTL** 設定為零會停用政策快取。

   如果啟用快取，您的授權方必須傳回適用於 API 之所有方法的政策。若要強制執行方法特定政策，您可以關閉**授權快取**。

1. 選擇**建立授權方**。

------

建立 Lambda 授權方之後，您可以測試該授權方。下列程序顯示如何測試您的 Lambda 授權方。

------
#### [ REQUEST authorizer ]

**測試 `REQUEST` Lambda 授權方**

1. 在以下網址登入 API Gateway 主控台：[https://console.aws.amazon.com/apigateway](https://console.aws.amazon.com/apigateway)。

1. 選取授權方的名稱。

1. 在**測試授權方**下，輸入身分來源的值。

   如果您使用的是 [`REQUEST` 授權方 Lambda 函數範例](apigateway-use-lambda-authorizer.md#api-gateway-lambda-authorizer-request-lambda-function-create)，請執行以下操作：

   1. 選取**標頭**並輸入 **headerValue1**，然後選擇**新增參數**。

   1. 在**身分來源類型**底下，選取**查詢字串**並輸入 **queryValue1**，然後選擇**新增參數**。

   1. 在**身分來源類型**底下，選取**階段變數**並輸入 **stageValue1**。

   您無法修改測試調用的內容變數，但您可以修改 Lambda 函數的 **API Gateway Authorizer** 測試事件範本。然後，您可以使用修訂內容變數來測試 Lambda 授權方函數。如需詳細資訊，請參閱《AWS Lambda 開發人員指南》**中的[在主控台測試 Lambda 函數](https://docs.aws.amazon.com/lambda/latest/dg/testing-functions.html)。

1. 選擇**測試授權方**。

------
#### [ TOKEN authorizer ]

**測試 `TOKEN` Lambda 授權方**

1. 在以下網址登入 API Gateway 主控台：[https://console.aws.amazon.com/apigateway](https://console.aws.amazon.com/apigateway)。

1. 選取授權方的名稱。

1. 在**測試授權方**下，輸入字符的值。

   如果您使用的是 [`TOKEN` 授權方 Lambda 函數範例](apigateway-use-lambda-authorizer.md#api-gateway-lambda-authorizer-token-lambda-function-create)，請執行以下操作：

   1. 對於 **authorizationToken** 值，輸入 **allow**。

1. 選擇**測試授權方**。

    如果您的 Lambda 授權方成功拒絕測試環境中的請求，測試會以 `200 OK` HTTP 回應來回應。然而，在測試環境之外，API Gateway 會傳回 `403 Forbidden` HTTP 回應，方法請求失敗。

------

## 設定 Lambda 授權方 (AWS CLI)
<a name="configure-api-gateway-lambda-authorization-cli"></a>

以下 [create-authorizer](https://docs.aws.amazon.com/cli/latest/reference/apigateway/create-authorizer.html) 命令指示使用 AWS CLI建立 Lambda 授權方。

------
#### [ REQUEST authorizer ]

以下 [create-authorizer](https://docs.aws.amazon.com/cli/latest/reference/apigateway/create-authorizer.html) 命令會建立 `REQUEST` 授權方，並使用 `Authorizer` 標頭和 `accountId` 內容變數作為身分來源：

```
aws apigateway create-authorizer \
    --rest-api-id 1234123412 \
    --name 'First_Request_Custom_Authorizer' \
    --type REQUEST \
    --authorizer-uri 'arn:aws:apigateway:us-west-2:lambda:path/2015-03-31/functions/arn:aws:lambda:us-west-2:123412341234:function:customAuthFunction/invocations' \
    --identity-source 'method.request.header.Authorization,context.accountId' \
    --authorizer-result-ttl-in-seconds 300
```

------
#### [ TOKEN authorizer ]

以下 [create-authorizer](https://docs.aws.amazon.com/cli/latest/reference/apigateway/create-authorizer.html) 命令會建立 `TOKEN` 授權方，並使用 `Authorization` 標頭作為身分來源：

```
aws apigateway create-authorizer \
    --rest-api-id 1234123412 \
    --name 'First_Token_Custom_Authorizer' \
    --type TOKEN \
    --authorizer-uri 'arn:aws:apigateway:us-west-2:lambda:path/2015-03-31/functions/arn:aws:lambda:us-west-2:123412341234:function:customAuthFunction/invocations' \
    --identity-source 'method.request.header.Authorization' \
    --authorizer-result-ttl-in-seconds 300
```

------

建立 Lambda 授權方之後，您可以測試該授權方。以下 [test-invoke-authorizer](https://docs.aws.amazon.com/cli/latest/reference/apigateway/test-invoke-authorizer.html) 命令會測試 Lambda 授權方：

```
aws apigateway test-invoke-authorizer --rest-api-id 1234123412 \
   --authorizer-id efg1234 \
   --headers Authorization='Value'
```

## 設定使用 Lambda 授權方 (主控台) 的方法
<a name="configure-api-gateway-lambda-authorization-method-console"></a>

設定 Lambda 授權方之後，您必須將其連接至 API 的方法。如果您的授權方使用授權快取，請務必更新政策以控制其他方法的存取。

**設定 API 方法使用 Lambda 授權方**

1. 在以下網址登入 API Gateway 主控台：[https://console.aws.amazon.com/apigateway](https://console.aws.amazon.com/apigateway)。

1. 選取 API。

1. 選擇**資源**，然後選擇新方法，或選擇現有方法。

1. 在**方法請求**索引標籤的**方法請求設定**下，選擇**編輯**。

1. 針對**授權方**，從下拉式選單選取您剛才建立的 Lambda 授權方。

1.  (選用) 如果您要將授權權杖傳遞至後端，請選擇 **HTTP 請求標頭**。選擇**新增標頭**，然後新增授權標頭的名稱。在**名稱**中，輸入標頭名稱，此名稱須符合您在建立 API 的 Lambda 授權方時指定的**符記來源**名稱。此步驟不適用於 `REQUEST` 授權方。

1. 選擇**儲存**。

1. 選擇**部署 API** 將 API 部署到階段。針對使用階段變數的 `REQUEST` 授權方，您還必須定義必要的階段變數，並在**階段編輯器**頁面上指定這些變數的值。

## 設定使用 Lambda 授權方的方法 (AWS CLI)
<a name="configure-api-gateway-lambda-authorization-method-cli"></a>

設定 Lambda 授權方之後，您必須將其連接至 API 的方法。您可以建立新的方法，或使用修補程式操作，將授權方連接到現有方法。如果您的授權方使用授權快取，請務必更新政策以控制其他方法的存取。

以下 [put-method](https://docs.aws.amazon.com/cli/latest/reference/apigateway/put-method.html) 命令會建立使用 Lambda 授權方的新方法：

```
aws apigateway put-method --rest-api-id 1234123412 \
  --resource-id a1b2c3 \
  --http-method PUT \
  --authorization-type CUSTOM \
  --authorizer-id efg1234
```

以下 [update-method](https://docs.aws.amazon.com/cli/latest/reference/apigateway/update-method.html) 命令會更新現有方法以使用 Lambda 授權方：

```
aws apigateway update-method \
    --rest-api-id 1234123412 \
    --resource-id a1b2c3 \
    --http-method PUT \
    --patch-operations op="replace",path="/authorizationType",value="CUSTOM" op="replace",path="/authorizerId",value="efg1234"
```

# 輸入至 API Gateway Lambda 授權方
<a name="api-gateway-lambda-authorizer-input"></a>

下一節說明從 API Gateway 到 Lambda 授權方的輸入格式。

## `TOKEN` 輸入格式
<a name="w2aac15b9c23c25c19b5"></a>

 針對 `TOKEN` 類型的 Lambda 授權方 (先前稱作自訂授權方)，您必須在設定 API 的授權方時，將自訂標頭指定為**字符來源**。API 用戶端必須在傳入請求中以該標頭傳遞必要的授權符記。收到傳入方法請求時，API Gateway 會從自訂標頭中擷取字符。然後，它會傳遞字符作為 Lambda 函數之 `event` 物件的 `authorizationToken` 屬性，並傳遞方法 ARN 作為 `methodArn` 屬性：

```
{
    "type":"TOKEN",
    "authorizationToken":"{caller-supplied-token}",
    "methodArn":"arn:aws:execute-api:{regionId}:{accountId}:{apiId}/{stage}/{httpVerb}/[{resource}/[{child-resources}]]"
}
```

 在此範例中，`type` 屬性會指定 `TOKEN` 授權方做為授權方類型。`{caller-supplied-token}` 源自用戶端要求的授權標頭，可以是任何字串值。`methodArn` 是傳入方法請求的 ARN，並會由 API Gateway 根據 Lambda 授權方組態填入。

## `REQUEST` 輸入格式
<a name="w2aac15b9c23c25c19b7"></a>

針對 `REQUEST` 類型的 Lambda 授權方，API Gateway 會將請求參數傳遞到授權方 Lambda 函數，做為 `event` 物件的一部分。請求參數包括標頭、路徑參數、查詢字串參數、階段變數與一些請求上下文變數。API 發起人可以設定路徑參數、標頭與查詢字串參數。API 開發人員必須在 API 部署期間設定階段變數，而 API Gateway 則會在執行時間提供請求內容。

**注意**  
路徑參數可作為請求參數傳遞到 Lambda 授權方函數，但無法作為身分來源使用。

 下列範例顯示具有代理整合之 API 方法 (`REQUEST`) 的 `GET /request` 授權方輸入：

```
{
  "type": "REQUEST",
  "methodArn": "arn:aws:execute-api:us-east-1:123456789012:abcdef123/test/GET/request",
  "resource": "/request",
  "path": "/request",
  "httpMethod": "GET",
  "headers": {
    "X-AMZ-Date": "20170718T062915Z",
    "Accept": "*/*",
    "HeaderAuth1": "headerValue1",
    "CloudFront-Viewer-Country": "US",
    "CloudFront-Forwarded-Proto": "https",
    "CloudFront-Is-Tablet-Viewer": "false",
    "CloudFront-Is-Mobile-Viewer": "false",
    "User-Agent": "..."
  },
  "queryStringParameters": {
    "QueryString1": "queryValue1"
  },
  "pathParameters": {},
  "stageVariables": {
    "StageVar1": "stageValue1"
  },
  "requestContext": {
    "path": "/request",
    "accountId": "123456789012",
    "resourceId": "05c7jb",
    "stage": "test",
    "requestId": "...",
    "identity": {
      "apiKey": "...",
      "sourceIp": "...",
      "clientCert": {
        "clientCertPem": "CERT_CONTENT",
        "subjectDN": "www.example.com",
        "issuerDN": "Example issuer",
        "serialNumber": "a1:a1:a1:a1:a1:a1:a1:a1:a1:a1:a1:a1:a1:a1:a1:a1",
        "validity": {
          "notBefore": "May 28 12:30:02 2019 GMT",
          "notAfter": "Aug  5 09:36:04 2021 GMT"
        }
      }
    },
    "resourcePath": "/request",
    "httpMethod": "GET",
    "apiId": "abcdef123"
  }
}
```

 `requestContext` 是鍵值對的對應，並對應到 [\$1context](api-gateway-mapping-template-reference.md#context-variable-reference) 變數。它的結果是與 API 相關。

 API Gateway 可能會將新的金鑰加入至地圖。如需 Lambda 代理整合中 Lambda 函數輸入的詳細資訊，請參閱[代理整合之 Lambda 函數的輸入格式](set-up-lambda-proxy-integrations.md#api-gateway-simple-proxy-for-lambda-input-format)。

# 來自 API Gateway Lambda 授權方的輸出
<a name="api-gateway-lambda-authorizer-output"></a>

Lambda 授權方函數的輸出是類似字典的物件，其中必須包含主要識別符 (`principalId`) 以及列出政策陳述式的政策文件 (`policyDocument`)。此輸出也可包含由鍵值對組成的 `context` 對應。如果 API 使用用量計劃 ([https://docs.aws.amazon.com/apigateway/latest/api/API_RestApi.html#apiKeySource](https://docs.aws.amazon.com/apigateway/latest/api/API_RestApi.html#apiKeySource) 設為 `AUTHORIZER`)，Lambda 授權方函數必須傳回其中一個用量計劃的 API 金鑰做為 `usageIdentifierKey` 屬性值。

以下示範此輸出。

------
#### [ JSON ]

****  

```
{
  "principalId": "yyyyyyyy", 
  "policyDocument": {
    "Version":"2012-10-17",		 	 	 
    "Statement": [
      {
        "Action": "execute-api:Invoke",
        "Effect": "Allow|Deny",
        "Resource": "arn:aws:execute-api:{regionId}:{accountId}:{apiId}/{stage}/{httpVerb}/[{resource}/[{child-resources}]]"
      }
    ]
  },
  "context": {
    "stringKey": "value",
    "numberKey": "1",
    "booleanKey": "true"
  },
  "usageIdentifierKey": "{api-key}"
}
```

------

 在本例中，政策陳述式會指定要允許或拒絕 (`Effect`) API Gateway 執行服務呼叫 (`Action`) 指定的 API 方法 (`Resource`)。您可能需要根據您的授權方來控制對多個資源的存取。您可以使用萬用字元 (`*`) 來指定資源類型 (方法)。如需設定有效政策來呼叫 API 的資訊，請參閱「[在 API Gateway 中執行 API 之 IAM 政策的陳述式參考](api-gateway-control-access-using-iam-policies-to-invoke-api.md#api-gateway-calling-api-permissions)」。

針對啟用授權的方法 ARN (例如 `arn:aws:execute-api:{regionId}:{accountId}:{apiId}/{stage}/{httpVerb}/[{resource}/[{child-resources}]]`)，長度上限為 1600 位元組。路徑參數值是在執行時間所決定的大小，可能會導致 ARN 長度超過限制。發生此情況時，API 用戶端會收到 `414 Request URI too long` 回應。

此外，授權方之政策陳述式輸出中所示的資源 ARN 長度目前限制為 512 個字元。因此，您不得在請求 URI 中，使用 JWT 字符長度很長的 URI。反之，您可以在請求標頭中安全傳遞此 JWT 字符。

 您可以使用 `principalId` 變數，來存取對應範本中的 `$context.authorizer.principalId` 值。如果您想要將此值傳遞到後端，這會很有用。如需詳細資訊，請參閱 [資料轉換的內容變數](api-gateway-mapping-template-reference.md#context-variable-reference)。

 您可以分別呼叫 `stringKey`、`numberKey` 或 `booleanKey`，來存取對應範本中 `"value"` 對應的 `"1"`、`"true"` 或 `context` 值 (例如 `$context.authorizer.stringKey`、`$context.authorizer.numberKey` 或 `$context.authorizer.booleanKey`)。傳回的值全部都已字串化。請注意，您無法將 JSON 物件或陣列設定為 `context` 對應中任何金鑰的有效值。

 您可以透過整合請求對應範本，使用 `context` 對應將快取的登入資料從授權方傳回後端。這可讓後端使用快取的登入資料來降低存取秘密金鑰的需求，並開啟每個請求的授權字符，藉此提供改善的使用者體驗。

 對於 Lambda 代理整合，API Gateway 會將 `context` 物件從 Lambda 授權方直接傳遞至後端 Lambda 函式，做為輸入 `event` 的一部分。您可以呼叫 `$event.requestContext.authorizer.key`，來擷取 Lambda 函數中的 `context` 索引鍵/值組。

API 階段用量計劃中，`{api-key}` 代表 API 金鑰。如需詳細資訊，請參閱 [API Gateway 中 REST API 的用量計畫和 API 金鑰](api-gateway-api-usage-plans.md)。

 以下顯示範例 Lambda 授權方的範例輸出。範例輸出包含政策陳述式，可針對 AWS 帳戶 (`Deny`) 的 API () `dev`階段封鎖 (`ymy8tbxw7b`) 對 `GET` 方法的呼叫`123456789012`。

------
#### [ JSON ]

****  

```
{
  "principalId": "user",
  "policyDocument": {
    "Version":"2012-10-17",		 	 	 
    "Statement": [
      {
        "Action": "execute-api:Invoke",
        "Effect": "Deny",
        "Resource": "arn:aws:execute-api:us-west-2:123456789012:ymy8tbxw7b/dev/GET/"
      }
    ]
  }
}
```

------

# 使用 API Gateway Lambda 授權方呼叫 API
<a name="call-api-with-api-gateway-lambda-authorization"></a>

 設定 Lambda 授權方 (先前稱作自訂授權方) 並部署 API 之後，您應該測試啟用 Lambda 授權方的 API。為此，您需要一個 REST 用戶端，例如 cURL 或 [Postman](https://www.postman.com/)。在下列範例中，我們使用 Postman。

**注意**  
 呼叫啟用授權方的方法時，如果 `TOKEN` 授權方的必要字符未設定、為 Null 或因指定的 **Token validation expression (字符驗證表達式)** 而失效，則 API Gateway 不會將呼叫記錄到 CloudWatch。同樣地，如果 `REQUEST` 授權方的任何必要身分來源未設定、為 Null 或空白，API Gateway 不會將呼叫記錄到 CloudWatch。

 以下示範如何使用 Postman 來呼叫或測試具有 Lambda `TOKEN` 授權方的 API。如果您明確指定必要的路徑、標頭或查詢字串參數，則可以套用此方法呼叫具有 Lambda `REQUEST` 授權方的 API。

**呼叫具有自訂 `TOKEN` 授權方的 API**

1.  開啟 **Postman**，選擇 **GET** 方法，然後將 API 的 **Invoke URL (呼叫 URL)** 貼到相鄰的 URL 欄位中。

    新增 Lambda 授權字符標頭，並將值設定為 `allow`。選擇 **Send (傳送)**。  
![\[使用 Lambda 授權 Allow (允許) 字符呼叫 API\]](http://docs.aws.amazon.com/zh_tw/apigateway/latest/developerguide/images/custom-auth-call-api-with-allow-token.png)

    回應顯示 API Gateway Lambda 授權方傳回 **200 OK (200 OK)** 回應，並成功授權呼叫存取與方法整合的 HTTP 端點 (http://httpbin.org/get)。

1.  同樣在 Postman 中，將 Lambda 授權字符標頭值變更為 `deny`。選擇 **Send (傳送)**。  
![\[使用 Lambda 授權 Deny (拒絕) 字符呼叫 API\]](http://docs.aws.amazon.com/zh_tw/apigateway/latest/developerguide/images/custom-auth-call-api-with-deny-token.png)

   回應顯示 API Gateway Lambda 授權方傳回 **403 Forbidden (403 禁止)** 回應，而不授權呼叫存取 HTTP 端點。

1.  在 Postman 中，將 Lambda 授權字符標頭值變更為 `unauthorized`，然後選擇 **Send (傳送)**。  
![\[使用 Lambda 授權 Unauthorized (未經授權) 字符呼叫 API\]](http://docs.aws.amazon.com/zh_tw/apigateway/latest/developerguide/images/custom-auth-call-api-with-unauthorized-token.png)

    回應顯示 API Gateway 傳回 **401 Unauthorized (401 未經授權)** 回應，而不授權呼叫存取 HTTP 端點。

1.  現在，將 Lambda 授權字符標頭值變更為 `fail`。選擇 **Send (傳送)**。  
![\[使用 Lambda 授權 Fail (失敗) 字符呼叫 API\]](http://docs.aws.amazon.com/zh_tw/apigateway/latest/developerguide/images/custom-auth-call-api-with-fail-token.png)

    回應顯示 API Gateway 傳回 **500 Internal Server Error (500 內部伺服器錯誤)** 回應，而不授權呼叫存取 HTTP 端點。

# 設定跨帳戶 API Gateway Lambda 授權方
<a name="apigateway-lambda-authorizer-cross-account-lambda-authorizer"></a>

您現在可以使用來自不同 AWS 帳戶的 AWS Lambda 函數做為 API 授權方函數。每個帳戶可以位於 Amazon API Gateway 可用的任何區域。Lambda 授權方函數可以使用承載字符身分驗證策略，例如 OAuth 或 SAML。這可讓您輕鬆地集中管理和分享跨多個 API Gateway API 的中央 Lambda 授權方函數。

在本節中，我們將示範如何使用 Amazon API Gateway 主控台設定跨帳戶 Lambda 授權方功能。

這些指示假設您在一個 AWS 帳戶中已有 API Gateway API，而在另一個帳戶中已有 Lambda 授權方函數。

## 使用 API Gateway 主控台設定跨帳戶 Lambda 授權方
<a name="apigateway-cross-account-lambda-auth-configure-cross-account-authorizer"></a>

在您 API 所在的帳戶中，登入 Amazon API Gateway 主控台，然後執行下列操作：

1. 選擇您的 API，然後在主導覽窗格中選擇**授權方**。

1. 選擇**建立授權方**。

1. 針對**授權方名稱**，輸入授權方的名稱。

1. 針對**授權方類型**，選取 **Lambda**。

1. 對於 **Lambda 函數**，輸入您在第二個帳戶中擁有之 Lambda 授權方函數的完整 ARN。
**注意**  
在 Lambda 主控台中，您可以在主控台視窗的右上角找到適用於您函數的 ARN。

1. 此時會出現包含 `aws lambda add-permission` 命令的警告。此政策會授與 API Gateway 許可，以調用授權方 Lambda 函數。複製指令並儲存，以供日後使用。建立授權方之後，您可以執行命令。

1. 針對 **Lambda 事件承載**，選擇**權杖**代表 `TOKEN` 授權方，或選擇**請求**代表 `REQUEST` 授權方。

1. 根據上一個步驟的選擇，執行下列其中一項操作：

   1.  針對**權杖**選項，執行下列操作：
      + 針對**權杖來源**，輸入包含授權權杖的標頭名稱。API 用戶端必須包含此名稱的標頭，才能將授權字符傳送到 Lambda 授權方。
      + 或者，針對**權杖驗證**，輸入 RegEx 陳述式。API Gateway 會對此表達式執行輸入字符的初始驗證，並在成功驗證時調用授權方。這樣做有助於減少對 API 的呼叫。
      + 若要快取授權方產生的授權政策，請將**授權快取**保持開啟狀態。啟用政策快取時，您可以選擇修改 **TTL** 值。將 **TTL** 設定為零會停用政策快取。啟用政策快取時，**權杖來源**中指定的標頭名稱會成為快取金鑰。如果在請求中將多個值傳遞給此標頭，則所有值都將成為快取金鑰，並會保留順序。
**注意**  
預設 **TTL** 值為 300 秒。最大值為 3600 秒，而且無法增加此限制。

   1. 針對 **請求** 選項，執行下列操作：
      + 針對**身分來源類型**，選取參數類型。支援的參數類型為 `Header`、`Query string`、`Stage variable` 與 `Context`。若要新增更多身分來源，請選擇**新增參數**。
      + 若要快取授權方產生的授權政策，請將**授權快取**保持開啟狀態。啟用政策快取時，您可以選擇修改 **TTL** 值。將 **TTL** 設定為零會停用政策快取。

        API Gateway 使用指定的身分來源作為請求授權方快取金鑰。啟用快取時，只有在成功驗證執行時間存在所有指定的身分來源之後，API Gateway 才會呼叫授權方的 Lambda 函數。如果指定的身分來源遺漏、為 null 或是空白，則 API Gateway 會傳回 `401 Unauthorized` 回應，而不會呼叫授權方 Lambda 函式。

        定義多個身分來源時，會使用這些來源衍生授權方的快取金鑰。變更任何快取金鑰部分都會使授權方捨棄快取的政策文件，並產生新的文件。如果在請求中傳遞具有多個值的標頭，則所有值將成為快取金鑰的一部分，並會保留順序。
      + 快取關閉時，不需指定身分來源。
**注意**  
 若要啟用快取，您的授權方必須傳回適用於 API 之所有方法的政策。若要強制執行方法特定政策，您可以關閉**授權快取**。

1. 選擇**建立授權方**。

1. 將您在上一個步驟中複製的`aws lambda add-permission`命令字串貼到為第二個帳戶設定的 AWS CLI 視窗中。將授權方 ID 取代為 `AUTHORIZER_ID` 。這會授與您的第一個帳戶對第二個帳戶的 Lambda 授權方函數的存取權。

# 利用 Verified Permissions 根據身分的屬性控制存取權
<a name="apigateway-lambda-authorizer-verified-permissions"></a>

使用 Amazon Verified Permissions 控制對 API Gateway API 的存取。當您搭配 Verified Permissions 使用 API Gateway 時，Verified Permissions 會建立 Lambda 授權方，該授權方會使用精細的授權決策來控制對 API 的存取。Verified Permissions 會根據政策存放區結構描述和政策，使用 Cedar 政策語言來授權呼叫者，以定義應用程式使用者的精細許可權。如需詳細資訊，請參閱《*Amazon Verified Permissions 使用者指南*》中的[使用連線 API 和身分提供者建立政策存放區](https://docs.aws.amazon.com/verifiedpermissions/latest/userguide/getting-started-api-policy-store.html)。

Verified Permissions 支援 Amazon Cognito 使用者集區或 OpenID Connect (OIDC) 身分提供者做為身分來源。Verified Permissions 假設主體先前已識別，並已驗證身分。Verified Permissions 僅支援區域和邊緣最佳化的 REST API。

## 使用 Verified Permissions 建立 Lambda 授權方
<a name="apigateway-lambda-authorizer-verified-permissions-attach"></a>

Verified Permissions 會建立 Lambda 授權方，用以判斷主體是否可在 API 上採取行動。您可以建立 Verified Permissions 用來執行其授權任務的 Cedar 政策。

以下是一個 Cedar 策略範例，允許 `developer` 群組基於 Amazon Cognito 使用者集區 `us-east-1_ABC1234` 對 API 的 `GET /users` 資源調用 API。Verified Permissions 會剖析呼叫者身分的承載字符來判定群組成員資格。

```
permit(
  principal in MyAPI::UserGroup::"us-east-1_ABC1234|developer",
  action in [ MyAPI::Action::"get /users" ],
  resource
  );
```

或者，Verified Permissions 可以將授權方附加至 API 的方法。在 API 的生產階段，建議您不要允許 Verified Permissions 為您附加授權方。

下列清單顯示如何設定 Verified Permissions，以附加或不附加 Lambda 授權方至 API 方法的方法請求。

**為您附加授權方 (AWS 管理主控台)**  
當您在 Verified Permissions 主控台選擇**建立政策存放區**時，請在**部署應用程式整合**頁面上選擇**現在**。

**請勿為您附加授權方 (AWS 管理主控台)**  
當您在 Verified Permissions 主控台選擇**建立政策存放區**時，請在**部署應用程式整合**頁面上選擇**稍後**。  
Verified Permissions 仍會為您建立 Lambda 授權方。Lambda 授權方以 `AVPAuthorizerLambda-` 開頭。如需有關如何在方法上附加授權方的詳細資訊，請參閱 [設定使用 Lambda 授權方 (主控台) 的方法](configure-api-gateway-lambda-authorization.md#configure-api-gateway-lambda-authorization-method-console)。

**為您附加授權方 (CloudFormation)**  
在 Verified Permissions 產生的 CloudFormation 範本中，在 `Conditions`區段中，將 `"Ref": "shouldAttachAuthorizer"`設定為 `true`。

**請勿為您附加授權方 (CloudFormation)**  
在 Verified Permissions 產生的 CloudFormation 範本中，在 `Conditions`區段中，將 `"Ref": "shouldAttachAuthorizer"`設定為 `false`。  
Verified Permissions 仍會為您建立 Lambda 授權方。Lambda 授權方以 `AVPAuthorizerLambda-` 開頭。如需有關如何在方法上附加授權方的詳細資訊，請參閱 [設定使用 Lambda 授權方的方法 (AWS CLI)](configure-api-gateway-lambda-authorization.md#configure-api-gateway-lambda-authorization-method-cli)。

## 使用 Verified Permissions 呼叫 Lambda 授權方
<a name="apigateway-lambda-authorizer-verified-permissions-call"></a>

您可以在 `Authorization` 標頭中提供身分或存取字符，以呼叫 Lambda 授權方。如需詳細資訊，請參閱[使用 API Gateway Lambda 授權方呼叫 API](call-api-with-api-gateway-lambda-authorization.md)。

API Gateway 會花 120 秒時間快取 Lambda 授權方傳回的政策。您可以在 API Gateway 主控台或使用 AWS CLI修改 TTL。