Sådan sikres mikroservices på AWS med Cognito, API Gateway og Lambda

Håndtering af godkendelse er smertefuldt. Men de fleste applikationer skal godkende brugere og kontrollere, hvilke ressourcer de kan få adgang til. Selvom mikroservices vokser i popularitet, kan de tilføje kompleksitet. Du skal sikre både brugerens handlinger og interaktionen mellem tjenester.

AWS tilbyder nogle gode byggesten til mikroservicearkitektur. Men ligesom møbler fra IKEA skal du samle stykkerne selv. Plus instruktionerne er ikke særlig gode.

Vi bygger en simpel applikation og konfigurerer AWS til at godkende en bruger og sikre en mikroservice.

TL; DR (for utålmodige)

Arbejdsdemonstration: //auth-api-demo.firebaseapp.com/ (bruger: demouseradgangskode:demoPASS123)

GitHub Repo : //github.com/csepulv/auth-api-demo

Basisbrugssag / antagelse: Der er to grupper af ressourcer - a) dem, der har brug for en godkendt bruger, og b) dem, der ikke gør det.

Vi bruger

  • AWS Lambda, API Gateway og Cognito
  • Claudia.js (til opbygning af vores API)
  • Reager (for vores webklient)

For dem der læser til slutningen, er der nogle godbidder.

Nu, for detaljerne.

Konceptuel applikationsmodel

Demoprogrammet implementerer følgende model.

  • En bruger logger ind på et program og får et godkendelsestoken
  • AWS bruger dette token til at verificere identitet og godkende brugeranmodninger om beskyttede ressourcer
  • App Gateway opretter en virtuel voldgrav mellem brugere og applikationsressourcer

AWS-tjenester

Hvis du er ny hos AWS, er der den officielle AWS-startvejledningsportal. Udemy har også et gratis kursus, AWS Essentials.

Du skal have adgang til en AWS-konto. Du kan tilmelde dig AWS gratis niveau.

AWS Lambda

Mens EC2 er en af ​​de mest populære AWS-muligheder, tror jeg, at Lambda er bedre egnet til mikrotjenester. EC2-forekomster er virtuelle maskiner. Du er ansvarlig for alt fra operativsystemet til al den software, det kører. Lambda er en funktion som en servicemodel. Der er ingen server klargøring eller implementering; du skriver din servicelogik.

For mere info henvises til AWS Lambda-dokumenterne.

Men der er en rynke med Lambdas. De kan ikke nås direkte af en applikationsbruger. Lambdas har brug for udløsere, der påberåber sig Lambda-funktionen. Dette kan være en meddelelse i kø eller i vores tilfælde en API-gatewayanmodning.

AWS API Gateway

En API-gateway giver en voldgrav omkring dine applikationstjenester. Det kan logge brugeraktivitet, godkende anmodninger og håndhæve brugspolitikker (som satsbegrænsning). (AWS API Gateway-dokumenterne er en god reference.)

AWS Cognito

AWS Cognito er en brugeradministration, godkendelse og adgangskontroltjeneste. Desværre kan alle funktioner og konfigurationer til tider være forvirrende. (Som om sikkerhed og godkendelse nogensinde var let.?) Vi vil fokusere på kerneelementerne i Cognito for at sikre vores API.

Opsætning af applikation og miljø

Opskriften på vores demo-applikation er:

  1. I AWS Cognito skal du oprette en brugerpool (med en klientapplikation) og en Federated Identity Pool.
  2. Opret en brugsplan og API-nøgle i AWS API Gateway
  3. Brug og brug Claudia JS til at opbygge og implementere en simpel AWS Lambda-baseret API.
  4. Opdater AWS IAM-rolle for at give godkendte brugere adgang til beskyttede API-metoder
  5. Opret en enkelt side app (SPA) ved hjælp af create-react-app. Det bruger AWS Cognito og foretager underskrevne (og godkendte) API-anmodninger

Den detaljerede AWS-opsætning er i aws-setup.md, i demo GitHub repo. Vi fremhæver aspekter af opsætningen og forklarer, hvordan ting fungerer.

AWS Cognito

Brugerpulje, klientapplikation og domænenavn

Vi opretter en brugerpulje med standardindstillingerne. Detaljer og skærmbilleder:

  • Brugerpulje
  • Klientapplikation
  • Domænenavn

Federated Identity Pool

Det kan være lidt forvirrende, at vi har brug for både en User Pool og en Federated Identity Pool. Ashan Fernando har en ret god forklaring i dette indlæg. Enkelt sagt,

  • Brugerpuljer giver en bruger adgang til en applikation. Dette er ligesom tjenester såsom Auth0.
  • En Federated Identity Pool giver adgang til AWS-ressourcer.

Ved at kombinere de to puljer kan vores applikation godkende en bruger, og AWS tildeler midlertidige legitimationsoplysninger. Disse legitimationsoplysninger giver brugeren adgang til AWS-ressourcer. IAM-rollen, der er konfigureret i Identity Pool, angiver rettighederne til de midlertidige legitimationsoplysninger.

Den detaljerede opsætning af Federated Identity Pool er her.

AWS API Gateway

Jeg foreslår, at du opretter en brugsplan til vores API. Selvom det ikke er et krav, er det en god praksis, da AWS-omkostninger kan ”løbe væk”, hvis du ikke er forsigtig. Vi opretter en brugsplan , navngivet api-auth-demoog indstillet en gas- og burst-hastighed og en daglig kvote for API-opkald. Vi opretter også en API-nøgle, som webklientapplikationen bruger. (Fuld opsætningsoplysninger er her.)

Vi er færdige med hovedparten af ​​vores AWS-opsætning. Vi skriver nu vores Lambda-funktioner og bygger derefter vores React-webapplikation.

AWS Lambda and Claudia JS

We will write our Lambda functions using Node.js. Claudia.js will deploy our Lambdas and configure the API Gateway. (As a note, the Serverless framework provides similar functionality.)

We only need a simple API for our example. We’ll create two API methods (i.e. very simple microservices): one for authenticated users and one for guests.

We’ll use the Claudia API Builder, which lets multiple routes map to a single lambda. The routing mechanism is similar to routing in frameworks such as Express.js.

 const ApiBuilder = require("claudia-api-builder"); const api = new ApiBuilder(); api.get("/no-auth",request => { return {message: "Open for All!"}; }, { apiKeyRequired: true } ); api.get("/require-auth", request => { return {message: "You're past the velvet rope!"}; }, { apiKeyRequired: true, authorizationType: "AWS_IAM" } ); module.exports = api; view rawapi.js hosted with ❤ by GitHub

We’ll use the Claudia.js command line to deploy the API to AWS.

claudia create --region us-west-2 --api-module api --name auth-api-demo

NOTE: Any changes to api.js will need to be re-deployed. Useclaudia update...

API Keys and Auth

In api.js, {apiKeyRequired: true} indicates that API requests require an API key. {authorizationType: 'AWS_IAM'} configures the API Gateway to authorize using AWS IAM. The underlying authentication mechanism is not obvious. The AWS docs outline the approach, but a summary is:

  • when a user signs in, Cognito will issue tokens for temporary credentials (obtained via STS).
  • for protected resources, the application needs to sign requests using these credentials
  • AWS decodes and verifies the signature
  • if the signature is valid, the API Gateway dispatches the request

There are other authorization methods available. The Claudia.js docs outline how to specify other methods. (The corresponding AWS docs are here.)

AWS IAM Roles for Authenticated Users

We need to edit the privileges for the IAM roles for authenticated users. We need to allow invoking the API Gateway method we created.

We need the ARN of the API Gateway. Go to the API Gateway console and find the API Gateway resource/method.

  • Copy the ARN
  • Go to the IAM console and find the Authenticated role created during the Cognito Federated Identity Pool setup
  • add an Inline Policy as below
  • Specify the copied ARN for the API Gateway resource in the policy.

Authenticated users can now invoke our protected API methods.

Service to Service Access Control

The Cognito setup will allow a user to invoke an API method. But this method invocation is a trigger for a Lambda function. The Lambda function executes within the context of a different IAM role. It is no longer a direct user request, but an AWS service to service interaction. IAM roles provide access control for this interaction.

Claudia.JS created the IAM role for the Lambda function. (You can also manually create this role and specify its identifier to Claudia.JS via the --role parameter. Details are here.)

If our Lambda function needs access to other AWS resources, we will need to update the Lambda’s IAM role and provide these privileges. This might be an RDS database, for example.

AWS has always used IAM to configure service to service access control. It is a well developed and well-documented model. It will probably be your primary mechanism for access control between microservices (within AWS). There might be cases where you need to augment or replace it, but I would start with IAM.

We can now build the web application for our users.

React Web Application

I am going to build a React single page web application (SPA). A Vue.js or Angular application would work too. For the client application, there are two significant components: AWS Amplify and the aws4 module.

AWS Amplify provides easy integration with AWS Cognito. aws4 is a popular library for signing AWS requests using AWS Request Signatures Version 4. AWS used signed requests for protected resources (i.e. authorized user requests).

Returning to the web client, we’ll use create-react-app. I won't outline the steps, as they are well documented on the create-react-app home page, and there are numerous online tutorials. (I've even written a few. )

For authentication, we need to do some state management. The example application doesn’t use any framework, but in a real application I’d suggest Mobx (or Redux.)

In the demo application, auth-store.js manages the user authentication state. This consists of the user's authentication state and credentials. These are used to

  • render different components and styles for authenticated vs. guest user
  • sign requests for protected API methods

While AWS Amplify manages much of the AWS Cognito integration, there is some work for us to do.

Determining Auth State from AWS Amplify

AWS Amplify’s documentation is good in some areas and deficient in others. I suggest reading the Authentication section of the Amplify documentation. This describes theAuth component, which interacts with Cognito.

However, there are still some aspects that the documentation doesn’t clearly address. AWS Amplify doesn’t make it easy to know the authentication state. (A discussion of this complexity is here.) Amplify configures itself asynchronously, without a callback. But there is an aws-amplify class that can help.

The Hub class in the aws-amplify module behaves like an event emitter. We care about two events: configured and cognitoHostedUI.

After the AWS Amplify configures the Auth component, it emits the configured event. Our application can then inquire about the current user's authentication status. This is useful when our application is being loaded, for example.

While using the application, we need to know if the authentication state changes. There is a sign-in event, but it isn't the event we want, as our demo application uses OAuth and the Cognito Hosted UI. The sign-in event is used in a custom sign-in/up screen or when using the built-in Amplify React UI. For OAuth, Amplify dispatches the cognitoHostedUI event after a completed OAuth sign-in flow.

Signing Requests

The current user will have credentials issued by AWS Cognito. These contain an access id, a secret key, and a session key. These are available by calling Auth.currentCredentials() in aws-amplify. For API methods authorized by IAM, you need to sign the request using AWS V4 Request Signatures. Thankfully, the aws4 module handles the complexities of generating these signatures.

In api-client.js,

 import aws4 from "aws4"; const apiHost = process.env.REACT_APP_API_HOST; const apiKey = process.env.REACT_APP_API_KEY; const region = process.env.REACT_APP_REGION; export async function authenticatedCall(authStore) { const opts = { method: "GET", service: "execute-api", region: region, path: "/latest/require-auth", host: apiHost, headers: { "x-api-key": apiKey }, url: `//${apiHost}/latest/require-auth` }; const credentials = await authStore.getCredentials(); const { accessKeyId, secretAccessKey, sessionToken } = credentials; const request = aws4.sign(opts, { accessKeyId, secretAccessKey, sessionToken }); delete request.headers.Host; const response = await fetch(opts.url, { headers: request.headers }); if (response.ok) { return await response.json(); } else return { message: response.statusText }; } export async function noAuthCall(authStore) { const response = await fetch(`//${apiHost}/latest/no-auth`, { headers: { "x-api-key": apiKey } }); return await response.json(); } view rawapi-client.js hosted with ❤ by GitHub

Demo

We can finally run npm start and run the app! When we first arrive at the application, we are a guest (unauthenticated user). You can also go to //auth-api-demo.firebaseapp.com/ to try it out.

We can access unprotected methods.

But if we try to access a protected resource, it will fail.

But if we sign in, we can access the protected resources.

Click Sign In and use demouser with password of demoPASS123.

We can now click the Req. Auth button to access a protected API method.

Whew! We had to configure multiple services and digest a lot of information. But we now have an application that is a model for authenticating microservices on AWS.

Now What?

This article’s approach is “all-in” on AWS. This was a deliberate choice, to show how the various AWS pieces fit together to solve a common need, namely auth. There are alternatives to methods in this article, and I outline a few here.

And for those who stayed with me to the end, I have some parting gifts.

  • In the demo repo, there is a script for automating the AWS setup. Its README has the details for running it.
  • resources-cheatsheet.md has the specific links for relevant AWS, Claudia.js, etc. documentation.

Thanks for reading!