Code Monkey home page Code Monkey logo

passport-webauthn's Introduction

passport-fido2-webauthn

Passport strategy for authenticating with Web Authentication.

This module lets you authenticate using WebAuthn in your Node.js applications. By plugging into Passport, WebAuthn-based sign in can be easily and unobtrusively integrated into any application or framework that supports Connect-style middleware, including Express.

❤️ Sponsors

Install

$ npm install passport-fido2-webauthn

Usage

The WebAuthn authentication strategy authenticates users using a public key-based credential. The authenticator which stores this credential is typically the user's device or an external security key, either of which may be unlocked using a PIN or biometric.

The strategy takes a verify function as an argument, which accepts id and userHandle as arguments. id identifies a public key credential that has been associated with a user's account. userHandle maps the credential to a specific user account. When authenticating a user, this strategy obtains this information from a WebAuthn assertion.

The verify function is responsible for determining the user to which the account at the OP belongs. Once it has made a determination, it invokes cb with the user record and a public key. The public key is used to cryptographically verify the WebAuthn assertion, thus authenticating the user.

This strategy also takes a register function as an argument, which is called when registering a new credential, and accepts user, id and publicKey as arguments. user represents a specific user account with which to associate the credential. id identifies the public key credential. publicKey is the PEM-encoded public key.

The register function is responsible for associating the new credential with the account. Once complete, it invokes cb with the user record.

Because the verify and register functions are supplied by the application, the app is free to use any database of its choosing. The example below illustrates usage of a SQL database.

var WebAuthnStrategy = require('passport-fido2-webauthn');
var SessionChallengeStore = require('passport-fido2-webauthn').SessionChallengeStore;

var store = new SessionChallengeStore();

passport.use(new WebAuthnStrategy({ store: store },
  function verify(id, userHandle, cb) {
    db.get('SELECT * FROM public_key_credentials WHERE external_id = ?', [ id ], function(err, row) {
      if (err) { return cb(err); }
      if (!row) { return cb(null, false, { message: 'Invalid key. '}); }
      var publicKey = row.public_key;
      db.get('SELECT * FROM users WHERE rowid = ?', [ row.user_id ], function(err, row) {
        if (err) { return cb(err); }
        if (!row) { return cb(null, false, { message: 'Invalid key. '}); }
        if (Buffer.compare(row.handle, userHandle) != 0) {
          return cb(null, false, { message: 'Invalid key. '});
        }
        return cb(null, row, publicKey);
      });
    });
  },
  function register(user, id, publicKey, cb) {
    db.run('INSERT INTO users (username, name, handle) VALUES (?, ?, ?)', [
      user.name,
      user.displayName,
      user.id
    ], function(err) {
      if (err) { return cb(err); }
      var newUser = {
        id: this.lastID,
        username: user.name,
        name: user.displayName
      };
      db.run('INSERT INTO public_key_credentials (user_id, external_id, public_key) VALUES (?, ?, ?)', [
        newUser.id,
        id,
        publicKey
      ], function(err) {
        if (err) { return cb(err); }
        return cb(null, newUser);
      });
    });
  }
));

Define Routes

Two routes are needed in order to allow users to log in with their passkey or security key.

The first route generates a randomized challenge, saves it in the ChallengeStore, and sends it to the client-side JavaScript for it to be included in the authenticator response. This is necessary in order to protect against replay attacks.

router.post('/login/public-key/challenge', function(req, res, next) {
  store.challenge(req, function(err, challenge) {
    if (err) { return next(err); }
    res.json({ challenge: base64url.encode(challenge) });
  });
});

The second route authenticates the authenticator assertion and logs the user in.

router.post('/login/public-key',
  passport.authenticate('webauthn', { failWithError: true }),
  function(req, res, next) {
    res.json({ ok: true });
  },
  function(err, req, res, next) {
    res.json({ ok: false });
  });

Examples

License

The MIT License

Copyright (c) 2019-2022 Jared Hanson <https://www.jaredhanson.me/>

passport-webauthn's People

Contributors

jaredhanson 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

Watchers

 avatar  avatar  avatar

passport-webauthn's Issues

Challenge mismatch due to differing packages used for base64 encoding/decoding

Hi there - this project uses base64url on server-side and on client-side the demo uses base64-arraybuffer (albeit an outdated version). A new version of base64-arraybuffer is at https://github.com/niklasvh/base64-arraybuffer.

We recommend a few things:

Cross domain not working as in specs

First of all, thanks a lot for this plugin. It's awesome to be able to easily bring this security layer into our apps so "easily".

That being said, I'm facing a problem and I think this plugin is not following the specs to the letter: my application has two different subdomains, app.xyz.com for the client and api.xyz.com for the backend. The webauthn specs (https://www.w3.org/TR/webauthn-2/) said that this scenario can work as long as we define an 'RP ID' on the client interaction with the browser to retrieve the challenge and key.

From the docs:

image

but this library is performing an strict equality check between origin and host (or proxied host):

https://github.com/jaredhanson/passport-webauthn/blob/master/lib/strategy.js#L63-L65

and also the RP ID hashes won't match as defined in the code:

https://github.com/jaredhanson/passport-webauthn/blob/master/lib/strategy.js#L106-L108

and here:

https://github.com/jaredhanson/passport-webauthn/blob/master/lib/strategy.js#L181-L183

I will try to raise an MR with the fixes ASAP.

But please, let me know if my assumptions are correct, this is really new to me and was just reading about it because I could not make it work in my production environment.

TypeScript support

Hello,

Would appreciate it if types can be defined for this library as it would be helpful for Node projects written in TypeScript.

Orgin Mismatch Error

working perfect on localhost but when host on some domain eg(account.abc.com) says Orgin Missmatch , I Resolved This Error Tempory Based

replace node_modules/passport-fido2-webauthn/lib/utils.js

exports.originalOrigin = function(req, options) {
options = options || {};
var app = req.app;
if (app && app.get && app.get('trust proxy')) {
options.proxy = true;
}
var trustProxy = options.proxy;

var proto = (req.headers['x-forwarded-proto'] || '').toLowerCase()
  , tls = req.connection.encrypted || (trustProxy && 'https' == proto.split(/\s*,\s*/)[0])
  , host = (trustProxy && req.headers['x-forwarded-host']) || req.headers.host
  , protocol = tls ? 'https' : 'http';
return protocol + '://' + host;

};

TO

exports.originalOrigin = function(req, options) {
const origin = req.get('origin');
return origin;
};

Using client side js (React, SolidJS) with different url not working

First of all, many thanks for this amazing library. I tried the example todos app and it worked like charm.
I am trying to use client side library instead of using the EJS. They will have two different urls.
When trying to do signup, I get the challenge but register is never triggered as a result of which I am not able to store the public key.

I always get 403 forbidden because of this reason. Do you think I am doing something wrong here ?

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.