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”.

Kontrol akses ke HTTP APIs dengan otorisasi JWT di API Gateway

Mode fokus
Kontrol akses ke HTTP APIs dengan otorisasi JWT di API Gateway - 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.

Anda dapat menggunakan JSON Web Tokens (JWTs) sebagai bagian dari OpenID Connect (OIDC OAuth ) dan 2.0 framework untuk membatasi akses klien ke Anda. APIs

Jika Anda mengonfigurasi otorisasi JWT untuk rute API Anda, API Gateway memvalidasi yang dikirimkan klien dengan JWTs permintaan API. API Gateway memungkinkan atau menolak permintaan berdasarkan validasi token, dan secara opsional, cakupan dalam token. Jika Anda mengonfigurasi cakupan untuk rute, token harus menyertakan setidaknya satu cakupan rute.

Anda dapat mengonfigurasi otorisasi yang berbeda untuk setiap rute API, atau menggunakan otorisasi yang sama untuk beberapa rute.

catatan

Tidak ada mekanisme standar untuk membedakan token akses JWT dari jenis lain JWTs, seperti token ID OpenID Connect. Kecuali Anda memerlukan token ID untuk otorisasi API, kami sarankan Anda mengonfigurasi rute Anda agar memerlukan cakupan otorisasi. Anda juga dapat mengonfigurasi otorisasi JWT Anda untuk meminta penerbit atau audiens yang hanya digunakan penyedia identitas Anda saat mengeluarkan token akses JWT.

Mengotorisasi permintaan API dengan otorisasi JWT

API Gateway menggunakan alur kerja umum berikut untuk mengotorisasi permintaan ke rute yang dikonfigurasi untuk menggunakan otorisasi JWT.

  1. identitySourcePeriksa token. identitySourceDapat hanya menyertakan token, atau token yang diawali denganBearer.

  2. Mendekode token.

  3. Periksa algoritma dan tanda tangan token dengan menggunakan kunci publik yang diambil dari penerbit. jwks_uri Saat ini, hanya algoritma berbasis RSA yang didukung. API Gateway dapat menyimpan kunci publik selama dua jam. Sebagai praktik terbaik, saat Anda memutar tombol, izinkan masa tenggang di mana kunci lama dan baru valid.

  4. Validasi klaim. API Gateway mengevaluasi klaim token berikut:

    • kid— Token harus memiliki klaim header yang cocok dengan kunci jwks_uri yang menandatangani token.

    • iss— Harus cocok dengan issueryang dikonfigurasi untuk otorisasi.

    • audatau client_id — Harus cocok dengan salah satu audienceentri yang dikonfigurasi untuk otorisasi. API Gateway client_id hanya memvalidasi jika tidak aud ada. Saat keduanya aud dan client_id ada, API Gateway mengevaluasi. aud

    • exp— Harus setelah waktu saat ini di UTC.

    • nbf— Harus sebelum waktu saat ini di UTC.

    • iat— Harus sebelum waktu saat ini di UTC.

    • scopeatau scp — Token harus menyertakan setidaknya satu cakupan dalam rute. authorizationScopes

Jika salah satu langkah ini gagal, API Gateway menolak permintaan API.

Setelah memvalidasi JWT, API Gateway meneruskan klaim dalam token ke integrasi rute API. Sumber daya backend, seperti fungsi Lambda, dapat mengakses klaim JWT. Misalnya, jika JWT menyertakan klaim identitasemailID, itu tersedia untuk integrasi Lambda di. $event.requestContext.authorizer.jwt.claims.emailID Untuk informasi selengkapnya tentang payload yang dikirimkan API Gateway ke integrasi Lambda, lihat. Buat integrasi AWS Lambda proxy untuk HTTP APIs di API Gateway

Buat otorisasi JWT

Sebelum Anda membuat otorisasi JWT, Anda harus mendaftarkan aplikasi klien dengan penyedia identitas. Anda juga harus membuat API HTTP. Untuk contoh pembuatan API HTTP, lihatBuat API HTTP.

Buat otorisasi JWT menggunakan konsol

Langkah-langkah berikut menunjukkan cara membuat otorisasi JWT menggunakan konsol.

Untuk membuat otorisasi JWT menggunakan konsol
  1. Masuk ke konsol API Gateway di https://console.aws.amazon.com/apigateway.

  2. Pilih API HTTP.

  3. Di panel navigasi utama, pilih Otorisasi.

  4. Pilih tab Kelola otorisasi.

  5. Pilih Buat.

  6. Untuk jenis Authorizer, pilih JWT.

  7. Konfigurasikan otorisasi JWT Anda, dan tentukan sumber Identitas yang menentukan sumber token.

  8. Pilih Buat.

Buat otorisasi JWT menggunakan AWS CLI

Perintah create-authorizer berikut membuat authorizer JWT. Untukjwt-configuration, tentukan Audience dan Issuer untuk penyedia identitas Anda. Jika Anda menggunakan Amazon Cognito sebagai penyedia identitas, itu adalah. IssuerUrl https://cognito-idp.us-east-2.amazonaws.com/userPoolID

aws apigatewayv2 create-authorizer \ --name authorizer-name \ --api-id api-id \ --authorizer-type JWT \ --identity-source '$request.header.Authorization' \ --jwt-configuration Audience=audience,Issuer=IssuerUrl
Buat otorisasi JWT menggunakan AWS CloudFormation

AWS CloudFormation Template berikut membuat API HTTP dengan otorisasi JWT yang menggunakan Amazon Cognito sebagai penyedia identitas.

Output dari AWS CloudFormation template adalah URL untuk UI yang dihosting Amazon Cognito tempat klien dapat mendaftar dan masuk untuk menerima JWT. Setelah klien masuk, klien dialihkan ke HTTP API Anda dengan token akses di URL. Untuk menjalankan API dengan token akses, ubah URL ke a ? untuk menggunakan token sebagai parameter string kueri. #

AWSTemplateFormatVersion: '2010-09-09' Description: | Example HTTP API with a JWT authorizer. This template includes an Amazon Cognito user pool as the issuer for the JWT authorizer and an Amazon Cognito app client as the audience for the authorizer. The outputs include a URL for an Amazon Cognito hosted UI where clients can sign up and sign in to receive a JWT. After a client signs in, the client is redirected to your HTTP API with an access token in the URL. To invoke the API with the access token, change the '#' in the URL to a '?' to use the token as a query string parameter. Resources: MyAPI: Type: AWS::ApiGatewayV2::Api Properties: Description: Example HTTP API Name: api-with-auth ProtocolType: HTTP Target: !GetAtt MyLambdaFunction.Arn DefaultRouteOverrides: Type: AWS::ApiGatewayV2::ApiGatewayManagedOverrides Properties: ApiId: !Ref MyAPI Route: AuthorizationType: JWT AuthorizerId: !Ref JWTAuthorizer JWTAuthorizer: Type: AWS::ApiGatewayV2::Authorizer Properties: ApiId: !Ref MyAPI AuthorizerType: JWT IdentitySource: - '$request.querystring.access_token' JwtConfiguration: Audience: - !Ref AppClient Issuer: !Sub https://cognito-idp.${AWS::Region}.amazonaws.com/${UserPool} Name: test-jwt-authorizer MyLambdaFunction: Type: AWS::Lambda::Function Properties: Runtime: nodejs18.x Role: !GetAtt FunctionExecutionRole.Arn Handler: index.handler Code: ZipFile: | exports.handler = async (event) => { const response = { statusCode: 200, body: JSON.stringify('Hello from the ' + event.routeKey + ' route!'), }; return response; }; APIInvokeLambdaPermission: Type: AWS::Lambda::Permission Properties: FunctionName: !Ref MyLambdaFunction Action: lambda:InvokeFunction Principal: apigateway.amazonaws.com SourceArn: !Sub arn:${AWS::Partition}:execute-api:${AWS::Region}:${AWS::AccountId}:${MyAPI}/$default/$default FunctionExecutionRole: Type: AWS::IAM::Role Properties: AssumeRolePolicyDocument: Version: '2012-10-17' Statement: - Effect: Allow Principal: Service: - lambda.amazonaws.com Action: - 'sts:AssumeRole' ManagedPolicyArns: - arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole UserPool: Type: AWS::Cognito::UserPool Properties: UserPoolName: http-api-user-pool AutoVerifiedAttributes: - email Schema: - Name: name AttributeDataType: String Mutable: true Required: true - Name: email AttributeDataType: String Mutable: false Required: true AppClient: Type: AWS::Cognito::UserPoolClient Properties: AllowedOAuthFlows: - implicit AllowedOAuthScopes: - aws.cognito.signin.user.admin - email - openid - profile AllowedOAuthFlowsUserPoolClient: true ClientName: api-app-client CallbackURLs: - !Sub https://${MyAPI}.execute-api.${AWS::Region}.amazonaws.com ExplicitAuthFlows: - ALLOW_USER_PASSWORD_AUTH - ALLOW_REFRESH_TOKEN_AUTH UserPoolId: !Ref UserPool SupportedIdentityProviders: - COGNITO HostedUI: Type: AWS::Cognito::UserPoolDomain Properties: Domain: !Join - '-' - - !Ref MyAPI - !Ref AppClient UserPoolId: !Ref UserPool Outputs: SignupURL: Value: !Sub https://${HostedUI}.auth.${AWS::Region}.amazoncognito.com/login?client_id=${AppClient}&response_type=token&scope=email+profile&redirect_uri=https://${MyAPI}.execute-api.${AWS::Region}.amazonaws.com

AWSTemplateFormatVersion: '2010-09-09' Description: | Example HTTP API with a JWT authorizer. This template includes an Amazon Cognito user pool as the issuer for the JWT authorizer and an Amazon Cognito app client as the audience for the authorizer. The outputs include a URL for an Amazon Cognito hosted UI where clients can sign up and sign in to receive a JWT. After a client signs in, the client is redirected to your HTTP API with an access token in the URL. To invoke the API with the access token, change the '#' in the URL to a '?' to use the token as a query string parameter. Resources: MyAPI: Type: AWS::ApiGatewayV2::Api Properties: Description: Example HTTP API Name: api-with-auth ProtocolType: HTTP Target: !GetAtt MyLambdaFunction.Arn DefaultRouteOverrides: Type: AWS::ApiGatewayV2::ApiGatewayManagedOverrides Properties: ApiId: !Ref MyAPI Route: AuthorizationType: JWT AuthorizerId: !Ref JWTAuthorizer JWTAuthorizer: Type: AWS::ApiGatewayV2::Authorizer Properties: ApiId: !Ref MyAPI AuthorizerType: JWT IdentitySource: - '$request.querystring.access_token' JwtConfiguration: Audience: - !Ref AppClient Issuer: !Sub https://cognito-idp.${AWS::Region}.amazonaws.com/${UserPool} Name: test-jwt-authorizer MyLambdaFunction: Type: AWS::Lambda::Function Properties: Runtime: nodejs18.x Role: !GetAtt FunctionExecutionRole.Arn Handler: index.handler Code: ZipFile: | exports.handler = async (event) => { const response = { statusCode: 200, body: JSON.stringify('Hello from the ' + event.routeKey + ' route!'), }; return response; }; APIInvokeLambdaPermission: Type: AWS::Lambda::Permission Properties: FunctionName: !Ref MyLambdaFunction Action: lambda:InvokeFunction Principal: apigateway.amazonaws.com SourceArn: !Sub arn:${AWS::Partition}:execute-api:${AWS::Region}:${AWS::AccountId}:${MyAPI}/$default/$default FunctionExecutionRole: Type: AWS::IAM::Role Properties: AssumeRolePolicyDocument: Version: '2012-10-17' Statement: - Effect: Allow Principal: Service: - lambda.amazonaws.com Action: - 'sts:AssumeRole' ManagedPolicyArns: - arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole UserPool: Type: AWS::Cognito::UserPool Properties: UserPoolName: http-api-user-pool AutoVerifiedAttributes: - email Schema: - Name: name AttributeDataType: String Mutable: true Required: true - Name: email AttributeDataType: String Mutable: false Required: true AppClient: Type: AWS::Cognito::UserPoolClient Properties: AllowedOAuthFlows: - implicit AllowedOAuthScopes: - aws.cognito.signin.user.admin - email - openid - profile AllowedOAuthFlowsUserPoolClient: true ClientName: api-app-client CallbackURLs: - !Sub https://${MyAPI}.execute-api.${AWS::Region}.amazonaws.com ExplicitAuthFlows: - ALLOW_USER_PASSWORD_AUTH - ALLOW_REFRESH_TOKEN_AUTH UserPoolId: !Ref UserPool SupportedIdentityProviders: - COGNITO HostedUI: Type: AWS::Cognito::UserPoolDomain Properties: Domain: !Join - '-' - - !Ref MyAPI - !Ref AppClient UserPoolId: !Ref UserPool Outputs: SignupURL: Value: !Sub https://${HostedUI}.auth.${AWS::Region}.amazoncognito.com/login?client_id=${AppClient}&response_type=token&scope=email+profile&redirect_uri=https://${MyAPI}.execute-api.${AWS::Region}.amazonaws.com

Perbarui rute untuk menggunakan otorisasi JWT

Anda dapat menggunakan konsol, SDK AWS CLI, atau AWS SDK untuk memperbarui rute untuk menggunakan otorisasi JWT.

Perbarui rute untuk menggunakan otorisasi JWT dengan menggunakan konsol

Langkah-langkah berikut menunjukkan cara memperbarui rute untuk menggunakan otorisasi JWT menggunakan konsol.

Untuk membuat otorisasi JWT menggunakan konsol
  1. Masuk ke konsol API Gateway di https://console.aws.amazon.com/apigateway.

  2. Pilih API HTTP.

  3. Di panel navigasi utama, pilih Otorisasi.

  4. Pilih metode, lalu pilih otorisasi Anda dari menu tarik-turun, dan pilih Lampirkan otorisasi.

Perbarui rute untuk menggunakan otorisasi JWT dengan menggunakan AWS CLI

Perintah update-route berikut memperbarui rute untuk menggunakan otorisasi JWT:

aws apigatewayv2 update-route \ --api-id api-id \ --route-id route-id \ --authorization-type JWT \ --authorizer-id authorizer-id \ --authorization-scopes user.email
PrivasiSyarat situsPreferensi cookie
© 2025, Amazon Web Services, Inc. atau afiliasinya. Semua hak dilindungi undang-undang.