Pilih preferensi cookie Anda

Kami menggunakan cookie penting serta alat serupa yang diperlukan untuk menyediakan situs dan layanan. Kami menggunakan cookie performa untuk mengumpulkan statistik anonim sehingga kami dapat memahami cara pelanggan menggunakan situs dan melakukan perbaikan. Cookie penting tidak dapat dinonaktifkan, tetapi Anda dapat mengklik “Kustom” atau “Tolak” untuk menolak cookie performa.

Jika Anda setuju, AWS dan pihak ketiga yang disetujui juga akan menggunakan cookie untuk menyediakan fitur situs yang berguna, mengingat preferensi Anda, dan menampilkan konten yang relevan, termasuk iklan yang relevan. Untuk menerima atau menolak semua cookie yang tidak penting, klik “Terima” atau “Tolak”. Untuk membuat pilihan yang lebih detail, klik “Kustomisasi”.

Gunakan otorisasi API Gateway Lambda

Mode fokus
Gunakan otorisasi API Gateway Lambda - Amazon API Gateway

Terjemahan disediakan oleh mesin penerjemah. Jika konten terjemahan yang diberikan bertentangan dengan versi bahasa Inggris aslinya, utamakan versi bahasa Inggris.

Terjemahan disediakan oleh mesin penerjemah. Jika konten terjemahan yang diberikan bertentangan dengan versi bahasa Inggris aslinya, utamakan versi bahasa Inggris.

Gunakan Lambda Authorizer (sebelumnya dikenal sebagai otorisasi kustom) untuk mengontrol akses ke API Anda. Saat klien membuat permintaan metode API Anda, API Gateway memanggil otorisasi Lambda Anda. Authorizer Lambda mengambil identitas pemanggil sebagai input dan mengembalikan kebijakan IAM sebagai output.

Gunakan otorisasi Lambda untuk mengimplementasikan skema otorisasi khusus. Skema Anda dapat menggunakan parameter permintaan untuk menentukan identitas pemanggil atau menggunakan strategi otentikasi token pembawa seperti OAuth atau SALL. Buat otorisasi Lambda di konsol API API Gateway REST API, menggunakan AWS CLI, atau SDK. AWS

Alur kerja otorisasi otorisasi Lambda

Diagram berikut menunjukkan alur kerja otorisasi untuk otorisasi Lambda.

Alur kerja otorisasi API Gateway Lambda
Alur kerja otorisasi API Gateway Lambda
  1. Klien memanggil metode pada API Gateway API, meneruskan token pembawa atau parameter permintaan.

  2. API Gateway memeriksa apakah permintaan metode dikonfigurasi dengan otorisasi Lambda. Jika ya, API Gateway memanggil fungsi Lambda.

  3. Fungsi Lambda mengautentikasi pemanggil. Fungsi ini dapat mengautentikasi dengan cara-cara berikut:

    • Dengan memanggil OAuth penyedia untuk mendapatkan token OAuth akses.

    • Dengan memanggil penyedia SAFL untuk mendapatkan pernyataan SAFL.

    • Dengan membuat kebijakan IAM berdasarkan nilai parameter permintaan.

    • Dengan mengambil kredensi dari database.

  4. Fungsi Lambda mengembalikan kebijakan IAM dan pengidentifikasi utama. Jika fungsi Lambda tidak mengembalikan informasi itu, panggilan gagal.

  5. API Gateway mengevaluasi kebijakan IAM.

    • Jika akses ditolak, API Gateway mengembalikan kode status HTTP yang sesuai, seperti403 ACCESS_DENIED.

    • Jika akses diizinkan, API Gateway akan memanggil metode.

      Jika Anda mengaktifkan caching otorisasi, API Gateway menyimpan kebijakan agar fungsi otorisasi Lambda tidak dipanggil lagi.

Anda dapat menyesuaikan 403 ACCESS_DENIED atau tanggapan 401 UNAUTHORIZED gateway. Untuk mempelajari selengkapnya, lihat Tanggapan Gateway untuk REST APIs di API Gateway.

Memilih jenis otorisasi Lambda

Ada dua jenis otorisasi Lambda:

Minta otorisasi Lambda berbasis parameter (otorisasi) REQUEST

REQUESTAuthorizer menerima identitas pemanggil dalam kombinasi header, parameter string kueri, dan variabel stageVariables. $context Anda dapat menggunakan REQUEST otorisasi untuk membuat kebijakan berbutir halus berdasarkan informasi dari beberapa sumber identitas, seperti variabel dan konteks. $context.path $context.httpMethod

Jika Anda mengaktifkan caching otorisasi untuk REQUEST otorisasi, API Gateway memverifikasi bahwa semua sumber identitas yang ditentukan ada dalam permintaan. Jika sumber identifikasi tertentu hilang, null, atau kosong, API Gateway mengembalikan respons 401 Unauthorized HTTP tanpa memanggil fungsi otorisasi Lambda. Ketika beberapa sumber identitas didefinisikan, mereka semua digunakan untuk mendapatkan kunci cache otorisasi, dengan urutan dipertahankan. Anda dapat menentukan kunci cache berbutir halus dengan menggunakan beberapa sumber identitas.

Jika Anda mengubah salah satu bagian kunci cache, dan menerapkan ulang API Anda, otorisasi akan membuang dokumen kebijakan yang di-cache dan membuat yang baru.

Jika Anda mematikan caching otorisasi untuk REQUEST otorisasi, API Gateway langsung meneruskan permintaan ke fungsi Lambda.

Pengotorisasi Lambda berbasis token (otorisasi) TOKEN

TOKENAuthorizer menerima identitas penelepon dalam token pembawa, seperti JSON Web Token (JWT) atau token. OAuth

Jika Anda mengaktifkan caching otorisasi untuk TOKEN otorisasi, nama header yang ditentukan dalam sumber token menjadi kunci cache.

Selain itu, Anda dapat menggunakan validasi token untuk memasukkan RegEx pernyataan. API Gateway melakukan validasi awal token input terhadap ekspresi ini dan memanggil fungsi otorisasi Lambda setelah validasi berhasil. Ini membantu mengurangi panggilan ke API Anda.

IdentityValidationExpressionProperti ini didukung hanya untuk TOKEN otorisasi. Untuk informasi selengkapnya, lihat x-amazon-apigateway-authorizer objek.

catatan

Kami menyarankan Anda menggunakan REQUEST otorisasi untuk mengontrol akses ke API Anda. Anda dapat mengontrol akses ke API berdasarkan beberapa sumber identitas saat menggunakan REQUEST otorisasi, dibandingkan dengan satu sumber identitas saat menggunakan TOKEN otorisasi. Selain itu, Anda dapat memisahkan kunci cache menggunakan beberapa sumber identitas untuk REQUEST otorisasi.

Contoh fungsi Lambda REQUEST authorizer

Kode contoh berikut membuat fungsi otorisasi Lambda yang memungkinkan permintaan jika HeaderAuth1 header yang disediakan klien, parameter QueryString1 kueri, dan variabel tahap StageVar1 semua cocok dengan nilai yang ditentukan,, danheaderValue1, queryValue1 masing-masing. 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("Unauthorized"); } } // 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') raise Exception('Unauthorized') # Return a 401 Unauthorized 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)
// 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("Unauthorized"); } } // 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); }

Dalam contoh ini, fungsi Lambda Authorizer memeriksa parameter input dan bertindak sebagai berikut:

  • Jika semua nilai parameter yang diperlukan cocok dengan nilai yang diharapkan, fungsi authorizer mengembalikan respons 200 OK HTTP dan kebijakan IAM yang terlihat seperti berikut, dan permintaan metode berhasil:

    { "Version": "2012-10-17", "Statement": [ { "Action": "execute-api:Invoke", "Effect": "Allow", "Resource": "arn:aws:execute-api:us-east-1:123456789012:ivdtdhp7b5/ESTestInvoke-stage/GET/" } ] }
  • Jika tidak, fungsi authorizer mengembalikan respon 401 Unauthorized HTTP, dan permintaan metode gagal.

Selain mengembalikan kebijakan IAM, fungsi otorisasi Lambda juga harus mengembalikan pengenal utama pemanggil. Secara opsional, ini dapat mengembalikan context objek yang berisi informasi tambahan yang dapat diteruskan ke backend integrasi. Untuk informasi selengkapnya, lihat Keluaran dari otorisasi API Gateway Lambda.

Dalam kode produksi, Anda mungkin perlu mengautentikasi pengguna sebelum memberikan otorisasi. Anda dapat menambahkan logika otentikasi dalam fungsi Lambda dengan memanggil penyedia otentikasi seperti yang diarahkan dalam dokumentasi untuk penyedia tersebut.

Contoh fungsi Lambda TOKEN authorizer

Kode contoh berikut membuat fungsi otorisasi TOKEN Lambda yang memungkinkan pemanggil untuk memanggil metode jika nilai token yang disediakan klien adalah. allow Penelepon tidak diizinkan untuk memanggil permintaan jika nilai tokennya. deny Jika nilai token adalah unauthorized atau string kosong, fungsi authorizer mengembalikan 401 UNAUTHORIZED respons.

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
// 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; }

Dalam contoh ini, ketika API menerima permintaan metode, API Gateway meneruskan token sumber ke fungsi otorisasi Lambda ini di atribut. event.authorizationToken Fungsi otorisasi Lambda membaca token dan bertindak sebagai berikut:

  • Jika nilai tokenallow, fungsi authorizer mengembalikan respons 200 OK HTTP dan kebijakan IAM yang terlihat seperti berikut, dan permintaan metode berhasil:

    { "Version": "2012-10-17", "Statement": [ { "Action": "execute-api:Invoke", "Effect": "Allow", "Resource": "arn:aws:execute-api:us-east-1:123456789012:ivdtdhp7b5/ESTestInvoke-stage/GET/" } ] }
  • Jika nilai tokendeny, fungsi authorizer mengembalikan respons 200 OK HTTP dan kebijakan Deny IAM yang terlihat seperti berikut, dan permintaan metode gagal:

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

    Di luar lingkungan pengujian, API Gateway mengembalikan respons 403 Forbidden HTTP dan permintaan metode gagal.

  • Jika nilai token unauthorized atau string kosong, fungsi authorizer mengembalikan respons 401 Unauthorized HTTP, dan panggilan metode gagal.

  • Jika token adalah hal lain, klien menerima 500 Invalid token respons, dan panggilan metode gagal.

Selain mengembalikan kebijakan IAM, fungsi otorisasi Lambda juga harus mengembalikan pengenal utama pemanggil. Secara opsional, ini dapat mengembalikan context objek yang berisi informasi tambahan yang dapat diteruskan ke backend integrasi. Untuk informasi selengkapnya, lihat Keluaran dari otorisasi API Gateway Lambda.

Dalam kode produksi, Anda mungkin perlu mengautentikasi pengguna sebelum memberikan otorisasi. Anda dapat menambahkan logika otentikasi dalam fungsi Lambda dengan memanggil penyedia otentikasi seperti yang diarahkan dalam dokumentasi untuk penyedia tersebut.

Contoh tambahan fungsi otorisasi Lambda

Daftar berikut menunjukkan contoh tambahan fungsi otorisasi Lambda. Anda dapat membuat fungsi Lambda di akun yang sama, atau akun lain, dari tempat Anda membuat API.

Untuk contoh fungsi Lambda sebelumnya, Anda dapat menggunakan built-in AWSLambdaBasicExecutionRole, karena fungsi ini tidak memanggil layanan lain AWS . Jika fungsi Lambda Anda memanggil AWS layanan lain, Anda harus menetapkan peran eksekusi IAM ke fungsi Lambda. Untuk membuat peran, ikuti instruksi dalam Peran AWS Lambda Eksekusi.

Contoh tambahan fungsi otorisasi Lambda
PrivasiSyarat situsPreferensi cookie
© 2025, Amazon Web Services, Inc. atau afiliasinya. Semua hak dilindungi undang-undang.