项目作者: jeanlescure

项目描述 :
Simple session SSO library to log in with Google, Github, Facebook, or a custom OAuth2 implementation
高级语言: TypeScript
项目地址: git://github.com/jeanlescure/session-sso.git
创建时间: 2020-11-02T16:48:09Z
项目社区:https://github.com/jeanlescure/session-sso

开源协议:

下载


Session SSO Logo depicting a cloud with a fingerprint connected to colored dots representing the multiple SSO providers that are supported by this package

Session SSO

Tests

Add this package to your back-end API in order to easily authenticate with Google, Facebook, Github,
or even your custom OAuth2 handled by this same library.

Open source notice

This project is open to updates by its users, I ensure that PRs are relevant to the community.
In other words, if you find a bug or want a new feature, please help us by becoming one of the
contributors ✌️ ! See the contributing section

Like this module? ❤

Please consider:

New to Single Sign On (SSO) integrations?

We suggest taking a look at the STRATEGY.md document before moving forward here.

How to get started using this module?

  1. import SessionSSO from 'session-sso';
  2. const sso = new SessionSSO({
  3. // facebook dev credentials
  4. appId: 'oHPrt6...',
  5. appSecret: 'O9GGmv3KHJ...',
  6. // github dev credentials
  7. clientId: 'wf3s6u...',
  8. clientSecret: 'AxDmXUPUnH...',
  9. });
  10. // note: google doesn't need dev credentials for SSO verification,
  11. // just on front-end to generate the initial OAuth token
  12. const verifyGoogleResult = await sso.verifySSO({
  13. provider: 'google',
  14. authKey: 'ey0PweGlS1FG...', // token returned by `googleUser.getAuthResponse().id_token`
  15. });
  16. const verifyFacebookResult = await sso.verifySSO({
  17. provider: 'facebook',
  18. authKey: 'EF25LPJCBAT...', // token returned by `FB.getLoginStatus()` => `response.authResponse.accessToken`
  19. });
  20. const verifyGithubResult = await sso.verifySSO({
  21. provider: 'github',
  22. authKey: 'c12fa85efae0236c034b', // auth code placed in url when redirected back from https://github.com/login/oauth/authorize
  23. });
  24. console.log(verifyGoogleResult); // { "email": "user-email-address@gmail.com" }
  25. console.log(verifyFacebookResult); // { "email": "user-email-address@gmail.com" }
  26. console.log(verifyGithubResult); // { "email": "user-email-address@gmail.com" }

By default the library will fetch the user’s email since it’s the most common default scope used by
Google, Facebook, and GitHub’s tokens.

If your provider allows you to fetch other scopes with your Client/Dev credentials, then you can
override which user properties are returned by verifySSO by passing the a string[] using the
retrieveProperties option like so:

  1. await sso.verifySSO({
  2. provider: 'google',
  3. authKey: 'eyS1FG0PweGl...',
  4. retrieveProperties: [
  5. 'email',
  6. 'email_verified',
  7. 'given_name',
  8. 'family_name',
  9. 'locale',
  10. ]
  11. });
  12. // would return:
  13. // {
  14. // payload: {
  15. // "email": "kahless@t-kuv.ma",
  16. // "email_verified": true,
  17. // "given_name": "Kahless",
  18. // "family_name": "-",
  19. // "locale": "tlh"
  20. // }
  21. // }

You can also set these scopes when instantiating:

  1. const sso = new SessionSSO({
  2. // ...
  3. retrieveProperties: [
  4. //...
  5. ],
  6. });

Note: Doing it this way affects all providers, so make sure all of them have the same naming conventions.

Create your own Custom SSO Provider

The custom SSO flow was inspired by Google’s.

First a user would send their authorization data (i.e. username, passowrd, etc), from here, it’s up
to you to generate an authorization promise:

  1. const authorizationPromise = async () => {
  2. // your top secret authorization sauce here
  3. // ...
  4. // if auth fails
  5. throw new Error('You cannot pass!');
  6. // if auth succeeds
  7. return {
  8. iss: Math.floor(Date.now() / 1000), // issue date as Epoch number (seconds since 1970)
  9. exp: Math.floor(Date.now() / 1000) + (60 * 60), // expiration date (1 hour later in this case)
  10. email: 'user-email-address@gmail.com',
  11. // ...
  12. };
  13. };

then proceed to produce another promise, this time for the private keys in JSON format:

  1. const privateKeyPromise: Promise<PEMKeyPromisePayload> = fetch(
  2. 'https://your.static.website/certs.priv.json',
  3. ).then((res) => res.json()).then((jpems) => {
  4. // `res` is a JSON with PEM keys:
  5. // {
  6. // "nnI9yCyGPq3r5zmurEVr05uf": "-----BEGIN RSA PRIVATE KEY-----\nMIIEow...",
  7. // "y7I9IXxvGBEOhc9CuBcHIklK": "-----BEGIN RSA PRIVATE KEY-----\nMIIEps..."
  8. // }
  9. //
  10. // For a full example of what this should look like visit: https://www.googleapis.com/oauth2/v1/certs
  11. // Make it hard for bad actors to reverse-engineer PEM keys by using more than one, randomly
  12. const randomKeyId = Object.keys(jpems).sort(() => Math.random() - 0.5)[0];
  13. return {
  14. kid: randomKeyId,
  15. pem: jpems[randomKeyId],
  16. };
  17. });

finally send your front-end the resulting authentication token:

  1. const {
  2. payload: {
  3. token, // <== send this
  4. },
  5. } = await sso.generateSSO({
  6. authorizationPromise,
  7. privateKeyPromise,
  8. });

now any front-end using your authentication end-point can verify that the token hasn’t been forged
by sending it back to your API where you do will do a very similar check as with google, facebook, and github:

  1. // This is the only extra step. With google, facebook, and github we already know where the verification
  2. // comes from, so we baked it in; but here you get to set your own rule as to where to
  3. const publicKeyPromise: Promise<PEMKeyPromisePayload> = fetch(
  4. 'https://your.static.website/certs.json',
  5. ).then((res) => res.json());
  6. const verifyCustomResult = await sso.verifySSO({
  7. publicKeyPromise,
  8. authKey: token as string,
  9. });

Error handling

Both verifySSO and generateSSO promises will return an object with only one property,
either payload or error.

On success, both verifySSO and generateSSO will resolve with an object with the payload
property, for example:

  1. {
  2. payload: {
  3. //...
  4. }
  5. }

On error, both verifySSO and generateSSO will reject with an object with the error property,
for example:

  1. {
  2. error: "..."
  3. }

Note: the value of the error property is a string.

🚨 Where to place this library in your code/API (or “I’m new to SSO, and confused”)

We’ve provided a handy and easy to understand explanation of a proper SSO strategy and where this
library is meant to be used, just take a look at the STRATEGY.md document.

Contributing

Yes, thank you! This plugin is community-driven, most of its features are from different authors.
Please update the docs and tests and add your name to the package.json file.

Contributors ✨

Thanks goes to these wonderful people (emoji key):







Jean Lescure

🚧 💻 📓 ⚠️ 💡 📖

Diana Lescure

📖 👀 🎨



License

Copyright (c) 2020-Present Session SSO Contributors.

Licensed under the Apache License 2.0.