npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@whollacsek/feathers-authentication

v1.1.3

Published

Add Authentication to your FeathersJS app.

Downloads

2

Readme

feathers-authentication

Build Status Code Climate Test Coverage Dependency Status Download Status Slack Status

Add Authentication to your FeathersJS app.

feathers-authentication adds shared PassportJS authentication for Feathers HTTP REST and WebSocket transports using JSON Web Tokens.

Installation

npm install feathers-authentication@pre --save

Documentation

API

This module contains:

  1. The main entry function
  2. A single authenticate hook
  3. The authentication service
  4. Socket listeners
  5. Express middleware
  6. A Passport adapter for Feathers

Hooks

feathers-authentication only includes a single hook. This bundled authenticate hook is used to register an array of one or more authentication strategies on a service method.

Note: Most of the time you should be registering this on your /authentication service. Without it you can hit the authentication service and generate a JWT accessToken without authentication (ie. anonymous authentication).

app.service('authentication').hooks({
  before: {
    create: [
      // You can chain multiple strategies
      auth.hooks.authenticate(['jwt', 'local']),
    ],
    remove: [
      auth.hooks.authenticate('jwt')
    ]
  }
});

The hooks that were once bundled with this module are now located at feathers-legacy-authentication-hooks. They are completely compatible but are deprecated and will not be supported by the core team going forward.

Express Middleware

Just like hooks there is an authenticate middleware. It is used the exact same way you would the regular Passport express middleware.

app.post('/login', auth.express.authenticate('local', { successRedirect: '/app', failureRedirect: '/login' }));

These other middleware are included and exposed but typically you don't need to worry about them:

  • emitEvents - emit login and logout events
  • exposeCookies - expose cookies to Feathers so they are available to hooks and services
  • exposeHeaders - expose headers to Feathers so they are available to hooks and services
  • failureRedirect - support redirecting on auth failure. Only triggered if hook.redirect is set.
  • successRedirect - support redirecting on auth success. Only triggered if hook.redirect is set.
  • setCookie - support setting the JWT access token in a cookie. Only enabled if cookies are enabled.

Default Options

The following default options will be mixed in with your global auth object from your config file. It will set the mixed options back on to the app so that they are available at any time by calling app.get('auth'). They can all be overridden and are depended upon by some of the authentication plugins.

{
  path: '/authentication', // the authentication service path
  header: 'Authorization', // the header to use when using JWT auth
  entity: 'user', // the entity that will be added to the request, socket, and hook.params. (ie. req.user, socket.user, hook.params.user)
  service: 'users', // the service to look up the entity
  passReqToCallback: true, // whether the request object should be passed to the strategies `verify` function
  session: false, // whether to use sessions
  cookie: {
    enabled: false, // whether the cookie should be enabled
    name: 'feathers-jwt', // the cookie name
    httpOnly: false, // whether the cookie should not be available to client side JavaScript
    secure: true // whether cookies should only be available over HTTPS
  },
  jwt: {
    header: { typ: 'access' }, // by default is an access token but can be any type
    audience: 'https://yourdomain.com', // The resource server where the token is processed
    subject: 'anonymous', // Typically the entity id associated with the JWT
    issuer: 'feathers', // The issuing server, application or resource
    algorithm: 'HS256', // the algorithm to use
    expiresIn: '1d' // the access token expiry
  }
}

Complementary Plugins

The following plugins are complementary but entirely optional:

Migrating to 1.x

Refer to the migration guide.

Complete Example

Here's an example of a Feathers server that uses feathers-authentication for local auth. You can try it out on your own machine by running the example.

Note: This does NOT implement any authorization. Use feathers-permissions for that.

const feathers = require('feathers');
const rest = require('feathers-rest');
const socketio = require('feathers-socketio');
const hooks = require('feathers-hooks');
const memory = require('feathers-memory');
const bodyParser = require('body-parser');
const errors = require('feathers-errors');
const errorHandler = require('feathers-errors/handler');
const local = require('feathers-authentication-local');
const jwt = require('feathers-authentication-jwt');
const auth = require('feathers-authentication');

const app = feathers();
app.configure(rest())
  .configure(socketio())
  .configure(hooks())
  .use(bodyParser.json())
  .use(bodyParser.urlencoded({ extended: true }))
  .configure(auth({ secret: 'supersecret' }))
  .configure(local())
  .configure(jwt())
  .use('/users', memory())
  .use('/', feathers.static(__dirname + '/public'))
  .use(errorHandler());

app.service('authentication').hooks({
  before: {
    create: [
      // You can chain multiple strategies
      auth.hooks.authenticate(['jwt', 'local'])
    ],
    remove: [
      auth.hooks.authenticate('jwt')
    ]
  }
});

// Add a hook to the user service that automatically replaces
// the password with a hash of the password before saving it.
app.service('users').hooks({
  before: {
    find: [
      auth.hooks.authenticate('jwt')
    ],
    create: [
      local.hooks.hashPassword({ passwordField: 'password' })
    ]
  }
});

const port = 3030;
let server = app.listen(port);
server.on('listening', function() {
  console.log(`Feathers application started on localhost:${port}`);
});

Client use

You can use the client in the Browser, in NodeJS and in React Native.

import io from 'socket.io-client';
import feathers from 'feathers/client';
import hooks from 'feathers-hooks';
import socketio from 'feathers-socketio/client';
import localstorage from 'feathers-localstorage';
import authentication from 'feathers-authentication-client';

const socket = io('http://localhost:3030/');
const app = feathers()
  .configure(socketio(socket)) // you could use Primus or REST instead
  .configure(hooks())
  .configure(authentication({ storage: window.localStorage }));

app.authenticate({
  strategy: 'local',
  email: '[email protected]',
  password: 'admin'
}).then(function(result){
  console.log('Authenticated!', result);
}).catch(function(error){
  console.error('Error authenticating!', error);
});

License

Copyright (c) 2016

Licensed under the MIT license.