https://github.com/awslabs/cognito-at-edge

Serverless authentication solution to protect your website or Amplify application

https://github.com/awslabs/cognito-at-edge

Science Score: 13.0%

This score indicates how likely this project is to be science-related based on various indicators:

  • CITATION.cff file
  • codemeta.json file
    Found codemeta.json file
  • .zenodo.json file
  • DOI references
  • Academic publication links
  • Committers with academic emails
  • Institutional organization owner
  • JOSS paper metadata
  • Scientific vocabulary similarity
    Low similarity (12.7%) to scientific vocabulary
Last synced: 11 months ago · JSON representation

Repository

Serverless authentication solution to protect your website or Amplify application

Basic Info
  • Host: GitHub
  • Owner: awslabs
  • License: apache-2.0
  • Language: TypeScript
  • Default Branch: main
  • Homepage:
  • Size: 546 KB
Statistics
  • Stars: 217
  • Watchers: 7
  • Forks: 58
  • Open Issues: 35
  • Releases: 14
Created over 6 years ago · Last pushed over 1 year ago
Metadata Files
Readme Changelog Contributing License Code of conduct

README.md

Cognito@Edge

Cognito authentication made easy to protect your website with CloudFront and Lambda@Edge.

This Node.js package helps you verify that users making requests to a CloudFront distribution are authenticated using a Cognito user pool. It achieves that by looking at the cookies included in the request and, if the requester is not authenticated, it will redirect then to the user pool's login page.

Architecture

Alternatives

This package allows you to easily parse and verify Cognito cookies in a Lambda@Edge function. If you want full control over the configuration of AWS resources (CloudFront, Cognito, Lambda@Edge...), this is the solution for you.

If you want to try it out easily or to quickstart a new project, we recommend having a look at the cognito-at-edge-federated-ui-sample repository. It allows you to configure and deploy a sample application which uses Cognito@Edge in a few CLI commands.

If you need more configuration options (e.g. bring your own user pool or CloudFront distribution), you may want to use this Serverless Application Repository application (GitHub) which provides a complete Auth@Edge solution. It does not use Cognito@Edge, but provides similar functionality.

Getting started

How To Install

The preferred way to install the AWS cognito-at-edge for Node.js is to use the npm package manager for Node.js. Simply type the following into a terminal window:

shell npm install cognito-at-edge

Usage

To use the package, you must create a Lambda@Edge function and associate it with the CloudFront distribution's viewer request events.

Within your Lambda@Edge function, you can import and use the Authenticator class as shown here:

``` js const { Authenticator } = require('cognito-at-edge');

const authenticator = new Authenticator({ // Replace these parameter values with those of your own environment region: 'us-east-1', // user pool region userPoolId: 'us-east-1_tyo1a1FHH', // user pool ID userPoolAppId: '63gcbm2jmskokurt5ku9fhejc6', // user pool app client ID userPoolDomain: 'domain.auth.us-east-1.amazoncognito.com', // user pool domain });

exports.handler = async (request) => authenticator.handle(request); ```

For an explanation of the interactions between CloudFront, Cognito and Lambda@Edge, we recommend reading this AWS blog article which describe the required architecture to authenticate requests in CloudFront with Cognito.

Reference - Authenticator Class

Authenticator(params)

  • params Object Authenticator parameters:
    • region string Cognito UserPool region (eg: us-east-1)
    • userPoolId string Cognito UserPool ID (eg: us-east-1_tyo1a1FHH)
    • userPoolAppId string Cognito UserPool Application ID (eg: 63gcbm2jmskokurt5ku9fhejc6)
    • userPoolAppSecret string (Optional) Cognito UserPool Application Secret (eg: oh470px2i0uvy4i2ha6sju0vxe4ata9ol3m63ufhs2t8yytwjn7p)
    • userPoolDomain string Cognito UserPool domain (eg: your-domain.auth.us-east-1.amazoncognito.com)
    • cookieExpirationDays number (Optional) Number of day to set cookies expiration date, default to 365 days (eg: 365). It's recommended to set this value to match refreshTokenValidity parameter of the pool client.
    • disableCookieDomain boolean (Optional) Sets domain attribute in cookies, defaults to false (eg: false)
    • httpOnly boolean (Optional) Forbids JavaScript from accessing the cookies, defaults to false (eg: false). Note, if this is set to true, the cookies will not be accessible to Amplify auth if you are using it client side.
    • sameSite Strict | Lax | None (Optional) Allows you to declare if your cookie should be restricted to a first-party or same-site context (eg: SameSite=None).
    • parseAuthPath string (Optional) URI path used as redirect target after successful Cognito authentication (eg: /oauth2/idpresponse), defaults to the web domain root. Needs to be a path that is handled by the library. When using this parameter, you should also provide a value for cookiePath to ensure your cookies are available for the right paths.
    • cookiePath string (Optional) Sets Path attribute in cookies
    • cookieDomain string (Optional) Sets the domain name used for the token cookies
    • cookieSettingsOverrides object (Optional) Cookie settings overrides for different token cookies -- idToken, accessToken and refreshToken
    • idToken CookieSettings (Optional) Setting overrides to use for idToken
      • expirationDays number (Optional) Number of day to set cookies expiration date, default to 365 days (eg: 365). It's recommended to set this value to match refreshTokenValidity parameter of the pool client.
      • path string (Optional) Sets Path attribute in cookies
      • httpOnly boolean (Optional) Forbids JavaScript from accessing the cookies, defaults to false (eg: false). Note, if this is set to true, the cookies will not be accessible to Amplify auth if you are using it client side.
      • sameSite Strict | Lax | None (Optional) Allows you to declare if your cookie should be restricted to a first-party or same-site context (eg: SameSite=None).
    • accessToken CookieSettings (Optional) Setting overrides to use for accessToken
    • refreshToken CookieSettings (Optional) Setting overrides to use for refreshToken
    • logoutConfiguration object (Optional) Enables logout functionality
    • logoutUri string URI path, which when matched with request, logs user out by revoking tokens and clearing cookies
    • logoutRedirectUri string The URI to which the user is redirected to after logging them out
    • csrfProtection object (Optional) Enables CSRF protection
    • nonceSigningSecret string Secret used for signing nonce cookies
    • logLevel string (Optional) Logging level. Default: 'silent'. One of 'fatal', 'error', 'warn', 'info', 'debug', 'trace' or 'silent'.

This is the class constructor.

handle(request)

Use it as your Lambda Handler. It will authenticate each query.

js const authenticator = new Authenticator( ... ); exports.handler = async (request) => authenticator.handle(request);

Authentication Gateway Setup

This library can also be used in an authentication gateway setup. If you have a frontend client application that uses AWS Cognito for authentication, it fetches and stores authentication tokens in the browser. Depending on where the tokens are stored in the browser (localStorage, cookies, sessionStorage), they may susceptible to token theft and XSS (Cross-Site Scripting). In order to mitigate this risk, a set of Lambda@Edge handlers can be deployed on a CloudFront distribution which act as an authentication gateway intermediary between the frontend app and Cognito. These handlers will authenticate and fetch tokens on the frontend's behalf and set them as Secure; HttpOnly tokens inside the browser, thereby restricting access to other scripts in the app.

Handlers 1. handleSignIn (Can be mapped to /signIn in Cloudfront setup): Redirect users to Cognito's authorize endpoint after replacing redirect uri with its own -- for instance, /parseAuth. 1. handleParseAuth (Can be mapped to /parseAuth): Exchange Cognito's OAuth code for tokens. Store tokens in browser as HttpOnly cookies 1. handleRefreshToken (Can be mapped to /refreshToken): Refresh idToken and accessToken using refreshToken 1. handleSignOut (Can be mapped to /signOut): Revoke tokens, clear cookies and redirect user to the URL supplied

```js // signIn Lambda Handler const authenticator = new Authenticator( ... ); exports.handler = async (request) => authenticator.handleSignIn(request);

// Similar setup for parseAuth, refreshToken and signOut handlers ```

Getting Help

The best way to interact with our team is through GitHub. You can open an issue and choose from one of our templates for bug reports, feature requests or question.

Contributing

We welcome community contributions and pull requests. See CONTRIBUTING.md for information on how to set up a development environment and submit code.

License

This project is licensed under the Apache License, Version 2.0, see LICENSE.txt and NOTICE.txt for more information.

Owner

  • Name: Amazon Web Services - Labs
  • Login: awslabs
  • Kind: organization
  • Location: Seattle, WA

AWS Labs

GitHub Events

Total
  • Issues event: 6
  • Watch event: 25
  • Issue comment event: 3
  • Push event: 1
  • Pull request event: 5
  • Pull request review event: 1
  • Fork event: 4
  • Create event: 1
Last Year
  • Issues event: 6
  • Watch event: 25
  • Issue comment event: 3
  • Push event: 1
  • Pull request event: 5
  • Pull request review event: 1
  • Fork event: 4
  • Create event: 1

Committers

Last synced: about 3 years ago

All Time
  • Total Commits: 31
  • Total Committers: 19
  • Avg Commits per committer: 1.632
  • Development Distribution Score (DDS): 0.871
Past Year
  • Commits: 9
  • Committers: 7
  • Avg Commits per committer: 1.286
  • Development Distribution Score (DDS): 0.778
Top Committers
Name Email Commits
Jean de Kernier j****r@a****m 4
Pedro Muñoz 9****a@u****m 3
Hugo David-Boyet h****b@a****m 3
Jean de K j****r@g****m 2
Otto Kruse o****s@a****l 2
borisfba b****a@a****u 2
piotrekwitkowski p****1@g****m 2
borisfba b****a@a****m 2
Franz f****t@g****m 1
Coltin Kifer c****9@g****m 1
Isaac Neale 4****2@u****m 1
Emma M e****r@n****m 1
Tim Bakkum 8****m@u****m 1
akhudiakov97 a****7@g****m 1
yoavya y****a@g****m 1
Jay Wheeler w****j@a****m 1
Amazon GitHub Automation 5****o@u****m 1
Doug Lampe 9****g@u****m 1
Jeni Rainer 8****n@u****m 1
Committer Domains (Top 20 + Academic)

Issues and Pull Requests

Last synced: 12 months ago

All Time
  • Total issues: 55
  • Total pull requests: 53
  • Average time to close issues: about 2 months
  • Average time to close pull requests: 20 days
  • Total issue authors: 43
  • Total pull request authors: 27
  • Average comments per issue: 2.2
  • Average comments per pull request: 0.72
  • Merged pull requests: 43
  • Bot issues: 0
  • Bot pull requests: 7
Past Year
  • Issues: 6
  • Pull requests: 8
  • Average time to close issues: N/A
  • Average time to close pull requests: about 3 hours
  • Issue authors: 5
  • Pull request authors: 4
  • Average comments per issue: 0.0
  • Average comments per pull request: 0.0
  • Merged pull requests: 7
  • Bot issues: 0
  • Bot pull requests: 4
Top Authors
Issue Authors
  • nagendrakumar02 (4)
  • jeandek (4)
  • vikas-reddy (3)
  • ckifer (2)
  • swt2c (2)
  • George-Saad (2)
  • jwwheeleriv (1)
  • AbhiPartha (1)
  • chbk (1)
  • johfer (1)
  • trevorrea (1)
  • vaunus (1)
  • edas-smith (1)
  • eddie-atkinson (1)
  • karthikvadla (1)
Pull Request Authors
  • jeandek (17)
  • dependabot[bot] (10)
  • borisfba (6)
  • pedromgarcia (3)
  • mishabruml (2)
  • ckifer (2)
  • fknittel (2)
  • dza89 (2)
  • elliotsegler (2)
  • ottokruse (2)
  • ncarchar (2)
  • piotrekwitkowski (2)
  • trevorrea (1)
  • tolya-dotcom (1)
  • jwwheeleriv (1)
Top Labels
Issue Labels
feature-request (7) bug (5) question (2) wontfix (2) release-summary (2) documentation (1) no-changelog (1)
Pull Request Labels
no-changelog (18) dependencies (11) bug (10) added-feature (8) ci (2)

Packages

  • Total packages: 2
  • Total downloads:
    • npm 31,356 last-month
  • Total dependent packages: 2
    (may contain duplicates)
  • Total dependent repositories: 4
    (may contain duplicates)
  • Total versions: 15
  • Total maintainers: 5
npmjs.org: cognito-at-edge

Cognito authentication made easy to protect your website with CloudFront and Lambda@Edge.

  • Versions: 14
  • Dependent Packages: 1
  • Dependent Repositories: 4
  • Downloads: 31,351 Last month
Rankings
Downloads: 1.3%
Forks count: 4.0%
Stargazers count: 4.6%
Dependent repos count: 5.6%
Average: 7.3%
Dependent packages count: 20.9%
Last synced: 12 months ago
npmjs.org: @louislarry/cognito-at-edge

Cognito authentication made easy to protect your website with CloudFront and Lambda@Edge.

  • Versions: 1
  • Dependent Packages: 1
  • Dependent Repositories: 0
  • Downloads: 5 Last month
Rankings
Forks count: 5.5%
Stargazers count: 7.6%
Dependent packages count: 16.2%
Average: 21.2%
Dependent repos count: 25.3%
Downloads: 51.2%
Maintainers (1)
Last synced: 12 months ago

Dependencies

package.json npm
  • @types/aws-lambda ^8.10.89 development
  • @types/jest ^27.4.0 development
  • @typescript-eslint/eslint-plugin ^5.9.1 development
  • @typescript-eslint/parser ^5.9.1 development
  • eslint ^7.32.0 development
  • jest ^27.4.7 development
  • ts-jest ^27.1.2 development
  • typescript ^4.5.4 development
  • aws-jwt-verify ^2.1.1
  • axios ^0.25.0
  • pino ^6.10.0
.github/workflows/staticChecks.yml actions
  • actions/checkout v4 composite
  • actions/setup-node v4.0.1 composite
package-lock.json npm
  • 457 dependencies