If you are using the default options, setting up JWT auth for your Feathers app is as simple as the below example. Note: You must set up the
body-parser module before setting up
var feathers = ;var hooks = ;var bodyParser = ;var feathersPassportJwt = ;var mongooseService = ;var app =// Configure feathers-passport-jwt
Authenticated REST requests must have an
Authorization header in the format
'Bearer <token>', where the is the JWT token. For example:
In order to authenticate a Websocket connection, you must first obtain a token using an Ajax request to your
loginEndpoint. You then include that token in the request. The example below is for Socket.io, but the same
query key can be passed to Primus.
In the above example, the
transports key is only needed if you for some reason need to force the browser to only use websockets. The
forceNew key is only needed if you have previously connected an unauthenticated Websocket connection and you now want to start an authenticated request.
The following options are available:
- secret required - The secret used to create encrypted tokens.
- userEndpoint - The api endpoint used to look up the user service. The default is
- loginEndpoint - The url for posting the username and password during login. The default is
- usernameField The database field containing the username on the user service. The default is
- passwordField The database field containing the password on the user service. The default is
- loginError - The message to return for invalid login. Default is 'Invalid login.'
- jwtOptions - Used to customize the configuration for the jsonwebtoken library. See the API
- jwtOptions.expiresIn - The number of seconds until the token expires. Default is 36000 (10 hours).
- strategy - Allows you to pass a custom strategy to use for local auth. The default strategy should fit most projects.
- passport (default:
require('passport')) - The passport module
The following shows a commented example for an application using local authentication with a Feathers user service:
var feathers = ;var passport = ;var hooks = ;var memory = ;var bodyParser = ;var feathersPassportJwt = ;var hashPassword = feathersPassportJwthashPassword;// Initialize the applicationvar app =// Needed for parsing bodies (login)// Configure feathers-passport-jwt// Initialize a user service// A simple Todos service that we can used for testing;var userService = app;// Add a hook to the user service that automatically replaces// the password with a hash of the password before saving it.userService;// Create a user that we can use to log inuserService;app;
login.html with an HTML form that allows to log our user in:
- Initial release
Copyright (c) 2015 Marshall Thompson
Licensed under the MIT license.