Giter VIP home page Giter VIP logo

github-cognito-openid-wrapper's Introduction

GitHub OpenID Connect Wrapper for Cognito

Build, lint, test Maintainability Test Coverage Known Vulnerabilities License

All Contributors

Do you want to add GitHub as an OIDC (OpenID Connect) provider to an AWS Cognito User Pool? Have you run in to trouble because GitHub only provides OAuth2.0 endpoints, and doesn't support OpenID Connect?

This project allows you to wrap your GitHub OAuth App in an OpenID Connect layer, allowing you to use it with AWS Cognito.

Here are some questions you may immediately have:

  • Why does Cognito not support federation with OAuth? Because OAuth provides no standard way of requesting user identity data. (see the background section below for more details).

  • Why has no one written a shim to wrap general OAuth implementations with an OpenID Connect layer? Because OAuth provides no standard way of requesting user identity data, any shim must be custom written for the particular OAuth implementation that's wrapped.

  • GitHub is very popular, has someone written this specific custom wrapper before? As far as I can tell, if it has been written, it has not been open sourced. Until now!

Project overview

When deployed, this project sits between Cognito and GitHub:

Overview

This allows you to use GitHub as an OpenID Identity Provider (IdP) for federation with a Cognito User Pool.

The project implements everything needed by the OIDC User Pool IdP authentication flow used by Cognito.

It implements the following endpoints from the OpenID Connect Core Spec:

  • Authorization - used to start the authorisation process (spec)
  • Token - used to exchange an authorisation code for an access and ID token (spec)
  • UserInfo - used to exchange an access token for information about the user (spec)
  • jwks - used to describe the keys used to sign ID tokens (implied by spec)

It also implements the following OpenID Connect Discovery endpoint:

  • Configuration - used to discover configuration of this OpenID implementation's endpoints and capabilities. (spec)

Out of the box, you can deploy it as a CloudFormation stack, or run it as a web server with node.

An attempt to deploy with CDK is available in the following archived construct: cdk-user-pool-identity-provider-github.

Getting Started

This project is intended to be deployed as a series of lambda functions alongside an API Gateway. This means it's easy to use in conjunction with Cognito, and should be cheap to host and run.

You can also deploy it as a http server running as a node app. This is useful for testing, exposing it to Cognito using something like ngrok.

1: Setup

You will need to:

  • Create a Cognito User Pool (instructions).
  • Configure App Integration for your User Pool (instructions). Note down the domain name.
  • Create a GitHub OAuth App (instructions, with the following settings:
    • Authorization callback URL: https://<Your Cognito Domain>/oauth2/idpresponse
    • Note down the Client ID and secret

(If you use GitHub Enterprise, you need the API & Login URL. This is usually https://<GitHub Enterprise Host>/api/v3 and https://<GitHub Enterprise Host>.)

Next you need to decide if you'd like to deploy with lambda/API Gateway (follow Step 2a), or as a node server (follow Step 2b)

2a: Deployment with lambda and API Gateway

  • Install the aws and sam CLIs from AWS:

  • Run aws configure and set appropriate access keys etc

  • Set environment variables for the OAuth App client/secret, callback url, stack name, etc:

     cp example-config.sh config.sh
     vim config.sh # Or whatever your favourite editor is
    
  • Run npm install and npm run deploy

  • Note down the DNS of the deployed API Gateway (available in the AWS console).

2b: Running the node server

  • Set environment variables for the OAuth App client/secret, callback url, and port to run the server on:

     cp example-config.sh config.sh
     vim config.sh # Or whatever your favourite editor is
    
  • Source the config file:

  source config.sh
  • Run npm run start to fire up an auto-refreshing development build of the server (production deployment is out of scope for this repository, but you can expose it using something like ngrok for easy development and testing with Cognito).

3: Finalise Cognito configuration

  • Configure the OIDC integration in AWS console for Cognito (described below, but following these instructions). The following settings are required:
    • Client ID: The GitHub Client ID above
    • Authorize scope: openid read:user user:email
    • Issuer: https://<Your API Gateway DNS name>/${Stage_Name} or https://<your webserver>/ (for the node server).
    • If you have deployed the web app: Run discovery (big blue button next to Issuer).
    • If you have deployed the lambda/Gateway: For some reason, Cognito is unable to do OpenID Discovery. You will need to configure the endpoints manually. They are:
      • Authorization endpoint: https://<Your API Gateway DNS name>/${Stage_Name}/authorize
      • Token endpoint: https://<Your API Gateway DNS name>/${Stage_Name}/token
      • Userinfo endpoint: https://<Your API Gateway DNS name>/${Stage_Name}/userinfo
      • JWKS uri: https://<Your API Gateway DNS name>/${Stage_Name}/.well-known/jwks.json
  • Configure the Attribute Mapping in the AWS console:

Attribute mapping

  • Ensure that your new provider is enabled under Enabled Identity Providers on the App Client Settings screen under App Integration.

That's it! If you need to redeploy the lambda/API gateway solution, all you need to do is run npm run deploy again.

Logging

This shim also supports logging with Winston. By default, all logging goes to STDOUT. Beware that if you set the log level to DEBUG, then sensitive user information may be logged.

If you're using the node server, you can also use Splunk for logging. Environment variables configuring splunk are commented in example-config.sh. The Splunk HEC URL and access token are required, and you can also set the source, sourcetype & index for all logged events.

The details

Background

There are two important concepts for identity federation:

  • Authentication: Is this user who they say they are?
  • Authorisation: Is the user allowed to use a particular resource?

OAuth

OAuth2.0 is an authorisation framework, used for determining whether a user is allowed to access a resource (like private user profile data). In order to do this, it's usually necessary for authentication of the user to happen before authorisation.

This means that most OAuth2.0 implementations (including GitHub) include authentication in a step of the authorisation process. For all practical purposes, most OAuth2.0 implementations (including GitHub)can be thought of as providing both authorisation and authentication.

Below is a diagram of the authentication code flow for OAuth:

OAuth flow

(The solid lines are http requests from the browser, and then dashed lines are back-channel requests).

As you can see in the diagram, a drawback of OAuth is that it provides no standard way of finding out user data such as name, avatar picture, email address(es), etc. This is one of the problems that is solved by OpenID.

OpenID Connect

To provide a standard way of learning about users, OpenID Connect is an identity layer built on top of OAuth2.0. It extends the token endpoint from OAuth to include an ID Token alongside the access token, and provides a userinfo endpoint, where information describing the authenticated user can be accessed.

OpenID Connect

OpenID Connect describes a standard way to get user data, and is therefore a good choice for identity federation.

A custom shim for GitHub

This project provides the OpenID shim to wrap GitHub's OAuth implementation, by combining the two diagrams:

GitHub Shim

The userinfo request is handled by joining two GitHub API requests: /user and /user/emails.

You can compare this workflow to the documented Cognito workflow here

Code layout

├── scripts             # Bash scripts for deployment and key generation
├── src                 # Source code
│    ├── __mocks__      # Mock private key data for tests
│    └── connectors     # Common code for both lambda and web handlers
│         ├── lambda    # AWS lambda handlers
│         │    └── util # Helper functions for lambdas
│         └── web       # Express.js webserver (useful for local deployment)
├── docs                # Documentation images
├── config              # Configuration for tests
├── dist-web            # Dist folder for web server deployment
└-- dist-lambda         # Dist folder for lambda deployment

npm targets

  • build and build-dist: create packages in the dist-lambda folder (for the lambda deployment) and the dist-web folder (for the node web server).
  • test: Run unit tests with Jest
  • lint: Run eslint to check code style
  • test-dev: Run unit tests continuously, watching the file system for changes (useful for development)
  • deploy: This script builds the project, then creates and deploys the cloudformation stack with the API gateway and the endpoints as lambdas

Scripts

  • scripts/create-key.sh: If the private key is missing, generate a new one. This is run as a preinstall script before npm install
  • scripts/deploy.sh: This is the deploy part of npm run deploy. It uploads the dist folder to S3, and then creates the cloudformation stack that contains the API gateway and lambdas

Tests

Tests are provided with Jest using chai's expect, included by a shim based on this blog post.

Pact consumer tests for the GitHub API connection are provided in src/github.pact.test.js. There is currently no provider validation performed.

Private key

The private key used to make ID tokens is stored in ./jwtRS256.key once scripts/create-key.sh is run (either manually, or as part of npm install). You may optionally replace it with your own key - if you do this, you will need to redeploy.

Missing features

This is a near-complete implementation of OpenID Connect Core. However, since the focus was on enabling Cognito's authentication flow, you may run in to some missing features if you wish to use it with a different client.

Missing Connect Core Features:

  • Private key rotation (spec)
  • Refresh tokens (spec)
  • Passing request parameters as JWTs (spec)

If you don't know what these things are, you are probably ok to use this project.

Missing non-core features:

A full OpenID implementation would also include:

Known issues

See the issue tracker for an up to date list.

Extending

This section contains pointers if you would like to extend this shim.

Using other OAuth providers

If you want to use a provider other than GitHub, you'll need to change the contents of userinfo in src/openid.js.

Using a custom GitHub location

If you're using an on-site GitHub install, you will need to change the API endpoints used when the github object is initialised.

Including additional user information

If you want to include custom claims based on other GitHub data, you can extend userinfo in src/openid.js. You may need to add extra API client calls in src/github.js

Contributing

Contributions are welcome, especially for the missing features! Pull requests and issues are very welcome.

FAQ

How do I use this to implement Cognito logins in my app?

Login requests from your app go directly to Cognito, rather than this shim. This is because the shim sits only between Cognito and GitHub, not between your app and GitHub. See the Cognito app integration instructions for more details.

Can I use this shim to connect to GitHub directly from another OpenID client?

Yes. This implementation isn't complete, as it focusses exclusively on Cognito's requirements. However, it does follow the OpenID spec, and is complete enough to be able to use it as an OpenID connect provider. See the missing features section above for one or two caveats.

How do I contact you to tell you that I built something cool with this code?

If you build anything cool, ping me @JonesTim on twitter (or open an issue if you have any problems).

This is so useful! How can I thank you?

If you'd like to support the work that I have done (and will do) maintaining this project, you can consider sponsoring me on github

License

BSD 3-Clause License

Contributors ✨

Although I've done most of the work on this project, I wasn't the only person who has contributed. Here is a list of everyone who has contributed to this project (emoji key):


Timothy Jones

💻 📖 🚧 💬 🚇

Beth Skurrie

🤔

Sebastian J.

💻 🚇

Danny Douglass

💻

Livnoni

💻

Benjamin Follis

🚇

Carl Youngblood

🚇

c.p.

🚇

David Lee

🚇

Christophe Bougère

💻 📖

Mike Fogel

📖

This project follows the all-contributors specification. Contributions of any kind welcome!

github-cognito-openid-wrapper's People

Contributors

bfuculsion avatar cayblood avatar christophebougere avatar daldei avatar dannydouglass avatar dehli avatar dependabot[bot] avatar derjust avatar jannikkeye avatar livnoni avatar mfogel avatar snyk-bot avatar tijwelch avatar timothyjones avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

github-cognito-openid-wrapper's Issues

Bit uncomprehensive setup instructions

Hello,

first I must admit I am not node developer and I am just following setup instructions in the README. I've setup user Pool, GitHub application and update config.sh. I am trying to deploy this project via API Gateway and Lambda. First thing that strikes me is that it is not mentioned in section 2a to source config.sh like in 2b. Is it not necessary ? Either way I still end up when running npm run deploy with following errors. Either as it is said that it is not a problem with npm I can't find out what I am doing wrong.

OS : OS X
aws-cli/1.16.212 Python/3.7.5 Darwin/18.7.0 botocore/1.12.204
SAM CLI, version 0.35.0
NPM 6.12.1

----------------|----------|----------|----------|----------|-------------------|

File % Stmts % Branch % Funcs % Lines Uncovered Line #s
All files 83.91 30.77 86.96 83.33
src 85.9 43.75 86.96 85.33
config.js 100 100 100 100
crypto.js 66.67 100 0 66.67 11,18,23,24
github.js 70.83 25 87.5 70.83 ... 24,25,30,31,34
helpers.js 100 100 100 100
openid.js 100 100 100 100
src/connectors 66.67 10 100 66.67
logger.js 66.67 10 100 66.67 16,18,27
---------------- ---------- ---------- ---------- ---------- -------------------

Test Suites: 1 failed, 2 passed, 3 total
Tests: 10 failed, 10 passed, 20 total
Snapshots: 0 total
Time: 1.763s
Ran all test suites.
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] test: jest --runInBand --coverage
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] test script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR! /Users/lolejar/.npm/_logs/2019-12-04T09_36_00_880Z-debug.log
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] prebuild-dist: npm run lint && npm run test
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] prebuild-dist script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR! /Users/lolejar/.npm/_logs/2019-12-04T09_36_00_898Z-debug.log
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] predeploy: npm run build-dist
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] predeploy script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR! /Users/lolejar/.npm/_logs/2019-12-04T09_36_00_916Z-debug.log

Question: Can the auth flow to GitHub be initiated without the Cognito Hosted UI?

Hi

We've got the flow setup which is great - thanks heaps for open sourcing this!!

Only thing is the UX is kinda sucky with the Cognito Hosted UI. We also already have a custom login flow using React and aws sdk calls.

Given the shim is behind the scenes, can the auth flow to GitHub via the shim be initiated using an sdk call from our React app?

Thanks!

Ben

GitHub Error - 400 error getting token

:(

...

I'm hoping it's just a reconfiguration problem, but it doesn't look as so.

Apparently, the call to GitHub gets successfully executed, the actual login to GitHub is successful, but when the callback gets, done it seems, it fails miserably with the error in the title -> "GitHub Error - 400 error getting token" from Cognito.

I've compared the response from a provider that works (Google) and this one (GitHub), and noticed that the /oauth2/idpresponse URL differs a bit.

Specifically, Google exports these parameters in the URL: code,state,scope,authuser,prompt
While, GitHub only exports: code,state

I don't know if it's relevant or not, but this is the only thing I could find.

Do you guys have any clues or any ideas in which directions to look at?

PS: The wrapper was deployed with ApiGateway/Lambda logic.

Failed to provide user info: Request failed with status code 403

I want to start by saying, thanks for sharing!

So here is my issue.

Cognito is getting a 403 on the /userinfo endpoint so I am assuming the Bearer token is invalid for some reason. Is this a common misconfiguration issue maybe on my part?

The state attribute is also undefined there but since the state is optional I think that's ok.

Here are the relevant debug logs with sensitive values <retracted>.

edit

I think this is also relevant, and is weird since I'm getting the sub from Github in the claim.

error_description=username+attribute+mapping+required&error=invalid_request

Also Ngrok is returing 400 back to the Cognito client but that's probably because the wrapper doesn't resolve correctly because of the 403.

debug: Signing payload {"iss":"https://<retracted>","aud":"<retracted>"}
debug: Resolved token response: {"access_token":"<retracted>","expires_in":28800,"refresh_token":"<retracted>"}
debug: Token for (<retracted>, undefined, <retracted>) provided
info: Providing access to JWKS: {"keys":[{"alg":"RS256","kid":"jwtRS256","kty":"RSA","n":"<retracted>","e":"AQAB"}]}
error: Failed to provide user info: Request failed with status code 403
debug: Checking response: [Circular]
debug: Fetched user details: {"login":"<retracted>","id":<retracted>,"node_id":"<retracted>","avatar_url":"<retracted>","gravatar_id":"","url":"https://api.github.com/users/<retracted>","html_url":"https://github.com/<retracted>","followers_url":"https://api.github.com/users/<retracted>/followers","following_url":"https://api.github.com/users/<retracted>/following{/other_user}","gists_url":"https://api.github.com/users/<retracted>/gists{/gist_id}","starred_url":"https://api.github.com/users/<retracted>/starred{/owner}{/repo}","subscriptions_url":"https://api.github.com/users/<retracted>/subscriptions","organizations_url":"https://api.github.com/users/<retracted>/orgs","repos_url":"https://api.github.com/users/<retracted>/repos","events_url":"https://api.github.com/users/<retracted>/events{/privacy}","received_events_url":"https://api.github.com/users/<retracted>/received_events","type":"User","site_admin":false,"name":"<retracted>","company":"<retracted> <retracted> ","blog":"http://github.com/<retracted>","location":"<retracted>","email":"<retracted>","hireable":true,"bio":null,"twitter_username":"<retracted>","public_repos":77,"public_gists":12,"followers":12,"following":17,"created_at":"2013-01-01T10:44:40Z","updated_at":"2021-02-07T21:49:19Z"}
debug: Resolved claims: {"sub":"<retracted>","name":"<retracted>","preferred_username":"<retracted>","profile":"https://github.com/<retracted>","picture":"https://avatars.githubusercontent.com/u/<retracted>?v=4","website":"http://github.com/<retracted>","updated_at":1612734559}
error: Failed to provide user info: Request failed with status code 403
debug: Checking response: [Circular]
debug: Fetched user details: {"login":"<retracted>","id":<retracted>,"node_id":"<retracted>","avatar_url":"https://avatars.githubusercontent.com/u/<retracted>?v=4","gravatar_id":"","url":"https://api.github.com/users/<retracted>","html_url":"https://github.com/<retracted>","followers_url":"https://api.github.com/users/<retracted>/followers","following_url":"https://api.github.com/users/<retracted>/following{/other_user}","gists_url":"https://api.github.com/users/<retracted>/gists{/gist_id}","starred_url":"https://api.github.com/users/<retracted>/starred{/owner}{/repo}","subscriptions_url":"https://api.github.com/users/<retracted>/subscriptions","organizations_url":"https://api.github.com/users/<retracted>/orgs","repos_url":"https://api.github.com/users/<retracted>/repos","events_url":"https://api.github.com/users/<retracted>/events{/privacy}","received_events_url":"https://api.github.com/users/<retracted>/received_events","type":"User","site_admin":false,"name":"Jón Levy","company":"@ruv-ohf @andesorg ","blog":"http://github.com/<retracted>","location":"<retracted>","email":"<retracted>","hireable":true,"bio":null,"twitter_username":"<retracted>","public_repos":77,"public_gists":12,"followers":12,"following":17,"created_at":"2013-01-01T10:44:40Z","updated_at":"2021-02-07T21:49:19Z"}
debug: Resolved claims: {"sub":"<retracted>","name":"<retracted>","preferred_username":"<retracted>","profile":"https://github.com/<retracted>","picture":"https://avatars.githubusercontent.com/u/<retracted>?v=4","website":"http://github.com/<retracted>","updated_at":1612734559}

image

image

deploy fails if bucket exists

If the bucket in config.sh already exists (either first time or during a update/redeploy) then deploy fails.
This is fixed by adding "|| true" to the end of the "aws s3 mb" commande

I may get around to fixing both this and #4 and submit a PR,
And by the way THANK YOU -- !~ THIS IS AWESOME IN SO MANY WAYS

HTTP 500 error from GitHub when user is not logged in and 2FA is enabled

When I am not logged in github in another window (session) I get 500 (Looks like something went wrong!) page instead of Authorization / Login page.

Originally posted by @lolejar in #23 (comment)

There's an issue with GitHub where it rejects the state sent by Cognito when 2FA is enabled and the user is not logged in. We did a fair bit of testing and couldn't figure out exactly what the issue was - but we think it is to do with the length of the state parameter provided by Cognito.

You can work around this by generating your own (shorter) state token and sending them on to GitHub - but if you do this, the shim needs to maintain state, and there's an extra step where GitHub redirects back to the shim, which redirects back to Cognito.

A colleague has a private fork of this repo which maintains a mapping of the Cognito states, using a dynamo DB table to do this. I'd like to look at merging it in, but I'm in two minds, because it's adding a fair bit of extra resources (and therefore impacts cost and scalability) in order to work around a GitHub bug.

Discussion welcome

CDK as a deployment alternative

Hey @TimothyJones! Thank you so much for making this, it made my life a lot simpler connecting Cognito with GitHub OAuth!

I prefer to use CDK to model AWS stacks for deployment and made this as an alternative to SAM: https://github.com/pcholakov/github-cognito-openid-wrapper/tree/cdk. I was curious if you might be interested in getting it incorporated upstream? I built the stack in TypeScript purely out of inertia but it could also be easily done in pure JavaScript to be more in keeping with the rest of your project. I feel that a CDK stack makes the solution a bit more composable for more consumers than the current SAM template. Feel free to say no, just thought I'd mention it :-)

Thanks again for sharing the project!

Dev chore: Add prettier check and autoformat target

Now that this repo is getting a few contributors, it would be good to:

  1. build in a formatting check to ensure the code is formatted with prettier
  2. Add an easy target for running the prettier formatter.

The format command is probably:

prettier --config .prettierrc --write "src/**/*.js"

Thoughts on how to update some custom claims coming from GitHub after the initial authorization in the OIDC flow

Hello,

Thank you for this amazing library! I am using it successfully in a personal project.
I have a question and I was wondering if you could provide me with your thoughts on how to deal with the following:
(this is more of a Cognito question rather than a question for your wrapper, but I thought I'd give it a shot 🙏)

I have made some changes to this library to fetch some more information from the GitHub API and pass it to Cognito as a custom claim. This is information about which installations of a GitHub application the GitHub user has access to. Every now and then, however, those installations might change as the user might uninstall that particular GitHub application from their GitHub account. Is there a way I can tell Cognito to perform the whole OIDC flow again with Github and this javascript library (deployed as AWS lambdas) that sit between the two? Does Cognito ever check with Github/this Shim again after the first time?

Is this approach correct or am I possibly missing something more fundamental here?

Thanks in advance!

Authenticating With GitHub MFA

Hi Timothy

We're pretty much all up and running! Thanks again for contributing this project - it has helped us save time.

We have a scenario that has come up during testing where the authn flow for an account that has MFA enabled in GitHub returns a 500 after the creds are entered but before the token entry dialog is displayed. Both of these pages are hosted by GitHub. Authn flow works if MFA is not enabled on GitHub account. And we can login directly to GitHub outside of the SSO context with GitHub MFA enabled.

Here is the HAR export:

https://www.dropbox.com/s/p7nx2306ep3fbv4/github.com.har?dl=0

It's a long shot but is it possible that the shim is crafting an authn request to GitHub such that if MFA is involved in the flow github rejects the authn?

Cheers

Ben

Need troubleshooting recommendations after successful? install

I've been able to follow your installation instructions successfully. After setting this up, deploying the lambda stack and API gateway, creating a new OIDC provider for it, creating a new Cognito app client, setting my github shim as its identity provider, and configuring an AWS Amplify app to use this app client for its auth, I'm currently getting the following error when trying to log in with my github username and password:

Unable to verify secret hash for client <app_client_id>

Hoping you might help answer a few questions:

  • What settings do I need to activate on my cognito app client? Do I need to set Callback URL(s), Sign out URL(s)? Do I need to check any allowed OAuth flows? How about OAuth scopes?
  • Does this handle 2FA?
  • Are there any additional logs where I could find more detail about failed login attempts to try to troubleshoot further?

Question: Deployment with Serverless framework

Thanks for your work on the project. As a frequent Serverless framework user, I'd like to get your POV if an (additional) deployment method via Serverless would make sense. If yes, I think I could create a serverless.yml for this project within a PR.

Way to add GitHub OAuth scopes

Hi there thank you for this great wrapper! I am using a custom attribute to capture the GitHub access token, and I was wondering if there was a way to specify additional GitHub OAuth Scopes? The wrapper is currently requesting limited scopes to gather basic info like email, but in my case I need a bit more, is there any way to specify additional GitHub specific scopes like repo etc?

Getting username attribute mapping required error

I took a pull of the workaround-2fa-bug branch and ended up resolving the invalid state issue that i was facing by storing the state mapping in a dynamodb table. But after we send the state and authenticate code to cognito hosted domain I get the username attribute mapping required error even though I have already configured that in the attribute mapping section.

Cognito giving us error back invalid response token

Hi @TimothyJones ,

This is question ,it's not error related to this shim,just want to know if you have some insight about it.

When our OAuth application return code back to Cognito , oauth2/idpresponse end point.
We are getting error
http://localhost:8080/?error_description=Bad+token+response%3A+HTTP%2F1.1+400+Bad+Request%2C+entity%3A+Failure%3A+%27Request+failed+with+status+code+400%27&error=invalid_request

Let me know if have any idea about this.
Thank You
Sampada K.

Could this wrapper be used with NetlifyCMS?

Netlify CMS uses Github to store documents. It has Git Gateway to authenticate it to Git providers. I am wondering whether if we have a web app that is authenticated via Cognito as the identity provider to use NetlifyCMS, do we have to configure git-gateway to use this openid-wrapper? Has anyone tried this before?

How to develop/test locally

Hi

Thanks so much for sharing this. I followed your Readme and got it working incredibly easily.

I now want to adapt this to connect to LinkedIn. I see maybe someone tired here already but I think this is unfinished, I couldn't get it to work anyway.

My question is how do you locally develop this. Because at the moment I am deploying to lambda every time I want to check my changes and it is a very slow way of working.

Is there a way I can replicate what cognito is doing on my local machine so I can test using the local node server (running with npm run start).

Thanks a lot,

Bad id_token issuer

I am using the lambda based deployment, and in Cognito, I had to manually provide the OpenID endpoints.

One of the endpoints to provide is the issuer URL. Here, the documentation states:

Issuer: https://<Your API Gateway DNS name>/${Stage_Name} or https://<your webserver>/ (for the node server).

However, I would get an error at the end of the Oauth flow:

Bad id_token issuer https://<Your API Gateway DNS name>

It seems that for the issuer URL, the endpoint to specify is:

https://<Your API Gateway DNS name>

There's no Stage_name to be provided here.

And that seemed to do the trick.

github accounts with 2FA fail

@TimothyJones greetings! first off, thanks for the hard work on open sourcing this repo. I'm interested in providing support after getting a working example up and running in quick time thanks to this repo (i'll connect with a proposal i'm building in the near future).

in the meantime...one issue i'm running into is that github users with two-factor authentication enabled are unable to sign in. this is the result after entering (correct) credentials into the cognito-initiated github auth flow:

image
i've verified with a different github user account with two-factor disabled, and things work as expected. i already have our cognito user pool working with google, but this is my first attempt at an openid cognito provider.

have you run into this issue before? i've been digging most of the day, however have not had much luck. thanks in advance for any help you can offer!

Can I use the access token to access the GitHub API?

Hi @TimothyJones, thank you for share your code.

I successfully installed shim on my AWS account and I can log in to my application through registered GitHub App. My question is that - how can I get access to GitHub API, for example, to get a list of repositories or make a commit? I tried to use the access token and id token from Cognito User without luck.

I'm using aws-amplify library for login with hosted UI:

import { Auth, Hub } from 'aws-amplify';
import { CognitoUser } from '@aws-amplify/auth';
const axios = require('axios');
//...

Hub.listen('auth', async ({ payload: { event, data } }) => {
    switch (event) {
        case 'cognitoHostedUI':
            this.successAuth();
            const cognitoUser: CognitoUser = await Auth.currentAuthenticatedUser();
            const session = await Auth.currentSession();
            const token = session.getIdToken();
            let axios_req = {
                method: 'get',
                url: 'https://api.github.com/user',
                headers: {
                    'Accept': 'application/json',
                    'Content-Type': 'application/json',
                    'Authorization': `token ${token}`
                }
            };
            axios(axios_req).then(res => {
                console.log('SUCCESS:', res);
                return res;
            }, err => {
                console.log('ERROR:', err);
            });
            break;
    }
});

The response always 401 Unauthorized:

{
  "message": "Bad credentials",
  "documentation_url": "https://developer.github.com/v3"
}

Thank you in advance,
Sergey.

Undefined GITHUB_API_URL and GITHUB_LOGIN_URL

Hii Team
I have used this package to configure github with Cognito. I have deployed the package in my local and have publically exposed it using Ngrok.
In the src/github.js file, the following 2 parameters are not defined in the config.sh file (Because a comment, in the config.sh file, states that it is only required for github enterprises). Can you please help with the place where these parameters are required to be defined because I have currently hard coded these 2 parameters as follow, on line no 12 and 13 of github.js file.

apiBaseUrl = "https://api.github.com"
loginBaseUrl = "https://github.com"

Can you please help me with the same?

Using cognito /logout endpoint not initiating new authn handshake with GitHub

Hi Timothy,

So the token integration is working well for us 🥳 with the authorize endpoint.

I'm now testing the clearing of the session via the /logout Cognito endpoint. My scenario is as follows:

  1. Logout of GitHub
  2. Call the /logout Cognito endpoint
  3. Call the /oauth/authorize Cognito endpoint

My expectation is that I should be presented with the GitHub authentication screen but I am getting the access and id tokens back again without authentication.

I have spoken to AWS and screen shared with them. Their suggestion was to speak with you. Is it possible the shim is caching the id token and returning it instead of initiating the sign in flow with GitHub? Clutching at straws...

I can talk to our CTO about some airpairing if you're available and OK with signing an NDA? Where are you based?

Thanks again for your help

Ben

Autodiscovery issue

I fixed the issue with the autodiscovery by moving the jwks.json endpoint into the /.well-known path, similar to the OpenIdDiscovery endpoint.

Error in local server env

Hi @TimothyJones, thank you for share your code.

I'm follow 2b scenario

below is my configuration

I'm using local env, so I removed /Prod

odic-config

cognito-app-config

And I add some code in routes.js

app.get('/', (req, res) => {
    res.send(`
<html>
<head>
</head>
<body>
<div>
  <a href="https://github.com/login/oauth/authorize?client_id=[GITHUB_APP_CLIENT_ID]&scope=openid read:user user:email">login</a>
</div>
</body>
`)
  }

but I saw error

oidc-error

As far as I know, state is optional. am I wrong?

Can you some advice me?

sam deploy missing RegionParameter

running npm run deploy, there is an error when running sam deploy.
There needs be an additional parameter overide RegionParameter=$REGION, or a default set in the template.

Manually running the failed command with the region argument appears to work
(not tested yet, but the stack did run)

sam deploy --region us-west-2 --template-file /moji/github-cognito-openid-wrapper/scripts/../serverless-output.yml --stack-name xxxx --parameter-overrides GitHubClientIdParameter=xxx GitHubClientSecretParameter=xxxx CognitoRedirectUriParameter=xxxx RegionParameter=$REGION --capabilities CAPABILITY_IAM

How can I limit GitHub authentication only for users in my GitHub organization

Hello, I would like to use GitHub user accounts and authenticate that user through Cognito. I have installed shim and it works so that GitHub users could authenticate via their GitHub accounts. I would like to limit users who can get authentication via GitHub by limiting them to my organization only. Is it possible? if so, could you please give advice on how to archive that?

Add support for refresh tokens

Nice work! Whats the challenge with implementing the refresh token? I'm assuming Github provides this and its just a need to intercept the request and proxy? If there are no technical challenges you are aware of I will have a stab!?

Logging to splunk not an option from lambda

PR #19 added an option to log to splunk. This option doesn't currently work from lambda deployments, because:

  1. The environment variables are not passed through in template.yml
  2. I'm not sure if any other lambda permissions would need to be added to allow the lambdas to access splunk (I don't use it myself).

Allow configuration of log level

The log level is currently hard-coded in logger.js. An improvement would be to allow this to be configured without code changes.

The approach used in #17 is nice, where the deployment stage and SLS_DEBUG state can also inform the log level.

Token endpoint does not verify client secret

The /token endpoint currently proxies all requests to GitHub's /login/oauth/access_token API. It forwards the code and state supplied by the requestor and augments the GitHub request with the GITHUB_CLIENT_SECRET -- the original requestor doesn't need to know the client secret at all!

That means I could get an access token if I can sniff someone's authorization code. This seems to be a security hole that at the very least deserves to be documented in bold letters. I believe this means that the security of the "authorization code flow" is effectively degraded to that of the "implicit flow".

Could this be fixed by removing the GITHUB_CLIENT_SECRET variable from the shim altogether and instead requiring that the service provider (i.e. Cognito) provides it?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.