The @feathersjs/authentication-client module allows you to easily authenticate against a Feathers server. It is not required, but makes it easier to implement authentication in your client by automatically storing and sending the JWT access token and handling re-authenticating when a websocket disconnects.
This module contains:
Setup is done the same as all Feathers plugins, using the configure
method:
const feathers = require('@feathersjs/feathers');
const socketio = require('@feathersjs/socketio-client');
const io = require('socket.io-client');
const auth = require('@feathersjs/authentication-client');
const socket = io('http://api.feathersjs.com');
const app = feathers();
// Setup the transport (Rest, Socket, etc.) here
app.configure(socketio(socket));
// Available options are listed in the "Options" section
app.configure(auth(options))
> The验证客户端(Rest, Socket, Primus…) must have been initialized previously to the authentication plugin.
在配置身份验证时, 以下默认选项将与您传入的设置混合在一起.它会将混合选项设置回应用程序, 以便随时可以通过 app.get('auth') 使用它们.他们都可以被覆盖.
{
header: 'Authorization', // the default authorization header for REST
prefix: '', // if set will add a prefix to the header value. for example if prefix was 'JWT' then the header would be 'Authorization: JWT eyJ0eXAiOiJKV1QiLCJhbGciOi...'
path: '/authentication', // the server-side authentication service path
jwtStrategy: 'jwt', // the name of the JWT authentication strategy
entity: 'user', // the entity you are authenticating (ie. a users)
service: 'users', // the service to look up the entity
cookie: 'feathers-jwt', // the name of the cookie to parse the JWT from when cookies are enabled server side
storageKey: 'feathers-jwt', // the key to store the accessToken in localstorage or AsyncStorage on React Native
storage: undefined // Passing a WebStorage-compatible object to enable automatic storage on the client.
}
To enable storing the JWT make sure to provide a storage when
configuring the plugin. The following storage options are available:
window.localStorage in the browser to use the browsers
localStorage
AsyncStorage for React Native
localForage which helps deal with older browsers and browsers in Incognito / Private Browsing mode.
cookie-storage
uses cookies. It can be useful on devices that don’t support
localStorage.
没有参数的``app.authenticate() - > Promise``将尝试使用``storage``中的JWT进行身份验证.通常调用此方法来显示您的应用程序(成功时)或显示登录页面或重定向到相应的oAuth链接.
app.authenticate().then(() => {
// show application page
}).catch(() => {
// show login page
})
重要
app.authenticate() 当你想在存储时使用令牌时 , **只在应用程序初始化时 **.一旦成功, 所有后续请求将自动发送其身份验证信息.
app.authenticate(options) - > Promise``将尝试通过传递 ``strategy 和其他属性作为凭证来验证Feathers服务器.它将使用客户端上设置的任何传输(@feathersjs/rest-client, @feathersjs/socketio-client 或 @feathersjs/primus-client).
// Authenticate with the local email/password strategy
app.authenticate({
strategy: 'local',
email: 'my@email.com',
password: 'my-password'
}).then(() => {
// Logged in
}).catch(e => {
// Show login page (potentially with `e.message`)
console.error('Authentication error', e);
});
app.authenticate({
strategy: 'jwt',
accessToken: '<the.jwt.token.string>'
}).then(() => {
// JWT authentication successful
}).catch(e => {
console.error('Authentication error', e);
// Show login page
});
data {Object} - of the format {strategy [, ...otherProps]}
strategy {String} - the name of the strategy to be used to
authenticate. Required.
...otherProps {Properties} vary depending on the chosen
strategy. Above is an example of using the jwt strategy. Below
is one for the local strategy.
Removes the JWT accessToken from storage on the client. It also calls the 认证 on the Feathers server.
app.passport contains helper functions to work with the JWT.
Pull the JWT from storage or the cookie. Returns a Promise.
Verify that a JWT is not expired and decode it to get the payload. Returns a Promise.
Synchronously verify that a token has not expired. Returns a Boolean.
On the client authentication events are emitted on the app object whenever a client successfully authenticates or “logs out”. These events are emitted on the client.
如果您的服务器出现故障或客户端失去连接, 当客户端重新获得与服务器的连接时, 它将自动处理尝试重新验证套接字的问题.为了在自动重新身份验证期间处理身份验证失败, 您需要实现以下事件侦听器:
const errorHandler = error => {
app.authenticate({
strategy: 'local',
email: 'admin@feathersjs.com',
password: 'admin'
}).then(response => {
// You are now authenticated again
});
};
// Handle when auth fails during a reconnect or a transport upgrade
app.on('reauthentication-error', errorHandler)
There are 3 hooks. They are really meant for internal use and you shouldn’t need to worry about them very often.
populateAccessToken - Takes the token and puts in on
hooks.params.accessToken in case you need it in one of your
client side services or hooks
populateHeader - Add the accessToken to the authorization header
populateEntity - Experimental. Populate an entity based on the
JWT payload.
Here’s an example of a Feathers client that uses
@feathersjs/authentication-client.
const feathers = require('@feathersjs/feathers');
const rest = require('@feathersjs/rest-client');
const auth = require('@feathersjs/authentication-client');
const superagent = require('superagent');
const localStorage = require('localstorage-memory');
const feathersClient = feathers();
feathersClient.configure(rest('http://localhost:3030').superagent(superagent))
.configure(auth({ storage: localStorage }));
feathersClient.authenticate({
strategy: 'local',
email: 'admin@feathersjs.com',
password: 'admin'
})
.then(response => {
console.log('Authenticated!', response);
return feathersClient.passport.verifyJWT(response.accessToken);
})
.then(payload => {
console.log('JWT Payload', payload);
return feathersClient.service('users').get(payload.userId);
})
.then(user => {
feathersClient.set('user', user);
console.log('User', feathersClient.get('user'));
})
.catch(function(error){
console.error('Error authenticating!', error);
});