Giter Site home page Giter Site logo

tony-kerz / node-openid-client Goto Github PK

View Code? Open in Web Editor NEW

This project forked from panva/node-openid-client

0.0 2.0 0.0 712 KB

OpenID Certified™ Relying Party (RP, Client) implementation for node.js servers. Wide feature coverage including optional specifications and passport strategy is included.

License: MIT License

JavaScript 100.00%

node-openid-client's Introduction

openid-client

build codecov

openid-client is a server side OpenID Relying Party (RP, Client) implementation for Node.js runtime, supports passport.

WARNING: Node.js 12 or higher is required for openid-client@3 and above. For older Node.js versions use openid-client@2.

Implemented specs & features

The following client/RP features from OpenID Connect/OAuth2.0 specifications are implemented by openid-client.

Certification

OpenID Certification
Filip Skokan has certified that openid-client conforms to the RP Basic, RP Implicit, RP Hybrid, RP Config, RP Dynamic and RP Form Post profiles of the OpenID Connect™ protocol.

build

Sponsor

auth0-logo If you want to quickly add OpenID Connect authentication to Node.js apps, feel free to check out Auth0's Node.js SDK and free plan at auth0.com/overview.

Support

If you or your business use openid-client, please consider becoming a Patron so I can continue maintaining it and adding new features carefree. You may also donate one-time via PayPal.

Documentation

The library exposes what are essentially steps necessary to be done by a relying party consuming OpenID Connect Authorization Server responses or wrappers around requests to its endpoints. Aside from a generic OpenID Connect passport strategy it does not expose neither express or koa middlewares. Those can however be built using the exposed API.

Quick start

Discover an Issuer configuration using its published .well-known endpoints

const { Issuer } = require('openid-client');
Issuer.discover('https://accounts.google.com') // => Promise
  .then(function (googleIssuer) {
    console.log('Discovered issuer %s %O', googleIssuer.issuer, googleIssuer.metadata);
  });

Authorization Code Flow

Authorization Code flow is for obtaining Access Tokens (and optionally Refresh Tokens) to use with third party APIs securely as well as Refresh Tokens. In this quick start your application also uses PKCE instead of state parameter for CSRF protection.

Create a Client instance for that issuer's authorization server intended for Authorization Code flow.

See the documentation for full API details.

const client = new googleIssuer.Client({
  client_id: 'zELcpfANLqY7Oqas',
  client_secret: 'TQV5U29k1gHibH5bx1layBo0OSAvAbRT3UYW3EWrSYBB5swxjVfWUa1BS8lqzxG/0v9wruMcrGadany3',
  redirect_uris: ['http://localhost:3000/cb'],
  response_types: ['code'],
  // id_token_signed_response_alg (default "RS256")
  // token_endpoint_auth_method (default "client_secret_basic")
}); // => Client

When you want to have your end-users authorize you need to send them to the issuer's authorization_endpoint. Consult the web framework of your choice on how to redirect but here's how to get the authorization endpoint's URL with parameters already encoded in the query to redirect to.

const { generators } = require('openid-client');
const code_verifier = generators.codeVerifier();
// store the code_verifier in your framework's session mechanism, if it is a cookie based solution
// it should be httpOnly (not readable by javascript) and encrypted.

const code_challenge = generators.codeChallenge(verifier);

client.authorizationUrl({
  scope: 'openid email profile',
  resource: 'https://my.api.example.com/resource/32178',
  code_challenge,
  code_challenge_method: 'S256',
});

When end-users are redirected back to your redirect_uri your application consumes the callback and passes in the code_verifier to include it in the authorization code grant token exchange.

const params = client.callbackParams(req);
client.callback('https://client.example.com/callback', params, { code_verifier }) // => Promise
  .then(function (tokenSet) {
    console.log('received and validated tokens %j', tokenSet);
    console.log('validated ID Token claims %j', tokenSet.claims());
  });

You can then call the userinfo_endpoint.

client.userinfo(access_token) // => Promise
  .then(function (userinfo) {
    console.log('userinfo %j', userinfo);
  });

And later refresh the tokenSet if it had a refresh_token.

client.refresh(refresh_token) // => Promise
  .then(function (tokenSet) {
    console.log('refreshed and validated tokens %j', tokenSet);
    console.log('refreshed ID Token claims %j', tokenSet.claims());
  });

Implicit ID Token Flow

Implicit response_type=id_token flow is perfect for simply authenticating your end-users, assuming the only job you want done is authenticating the user and then relying on your own session mechanism with no need for accessing any third party APIs with an Access Token from the Authorization Server.

Create a Client instance for that issuer's authorization server intended for ID Token implicit flow.

See the documentation for full API details.

const client = new googleIssuer.Client({
  client_id: 'zELcpfANLqY7Oqas',
  redirect_uris: ['http://localhost:3000/cb'],
  response_types: ['id_token'],
  // id_token_signed_response_alg (default "RS256")
}); // => Client

When you want to have your end-users authorize you need to send them to the issuer's authorization_endpoint. Consult the web framework of your choice on how to redirect but here's how to get the authorization endpoint's URL with parameters already encoded in the query to redirect to.

const { generators } = require('openid-client');
const nonce = generators.nonce();
// store the nonce in your framework's session mechanism, if it is a cookie based solution
// it should be httpOnly (not readable by javascript) and encrypted.

client.authorizationUrl({
  scope: 'openid email profile',
  response_mode: 'form_post',
  nonce,
});

When end-users hit back your redirect_uri with a POST (authorization request included form_post response mode) your application consumes the callback and passes the nonce in to include it in the ID Token verification steps.

// assumes req.body is populated from your web framework's body parser
const params = client.callbackParams(req);
client.callback('https://client.example.com/callback', params, { nonce }) // => Promise
  .then(function (tokenSet) {
    console.log('received and validated tokens %j', tokenSet);
    console.log('validated ID Token claims %j', tokenSet.claims());
  });

FAQ

Semver?

Yes. Everything that's documented is subject to Semantic Versioning 2.0.0. The rest is to be considered private API and is subject to change between any versions.

How do I use it outside of Node.js

It is only built for Node.js environment.

How do I use it older Node.js versions

Use openid-client@2 release line, but be sure to check its documentation as there were breaking changes between versions 2 and 3.

What's new in 3.x?

  • Simplified API which consumes a lot of the common configuration issues
  • New documentation
  • Added support for mutual-TLS client authentication
  • Added support for any additional token exchange parameters to support specifications such as Resource Indicators
  • Typed errors
  • Coming soon™ - Typescript definitions

How to make the client send client_id and client_secret in the body?

See Client Authentication Methods.

node-openid-client's People

Contributors

panva avatar oladon avatar tayloa45 avatar briangammon avatar davidgtonge avatar kgraney avatar madarche avatar thecodeite avatar tetchel avatar urossmolnik avatar

Watchers

James Cloos avatar tony kerz avatar

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.