简体   繁体   中英

How connect client to server with feathers js authentication?

this is my server.js:

app.use('/users', {
    find(params) {
      return Promise.resolve(Users);
    }
  });
  app.service('authentication').hooks({
  before: {
    create: [
      auth.hooks.authenticate(['local', 'jwt'])
    ]
  }
});
app.service('users').hooks({
  before: {
    create: [
      local.hooks.hashPassword()
    ]
  }
});
/////////////////
app.post('/login', auth.express.authenticate('local', { successRedirect: '/app', failureRedirect: '/login' }));

app.get('/app', (req, res, next) => {
  res.json({ success: true });
});

app.get('/login', (req, res, next) => {
  res.json({ success: false });
});
//////////////

please who can help me if i have an error in my code ? and what i should do in my file in frontend ? I work with reactjs.

There are few ways of connecting clients with feathersjs auth.

The easest way ( React/ Angular /... ) without using particular libraries:

Do a post request to the auth url : http://Your_url:port/authentication .

Body :

{ email: email, password: password, strategy: "local" }

If your request success, you will get a response with an accessToken . So, you should save that token and use it to access protected routes.

IMPORTANT : using "email" attr, because its the default auth attr. You can configure it as you wish.

Hope this helps!

In feathersjs having default authentication(login) api something like this.

Url: http://localhost:8080/authentication

method: Post

Body: {"strategy": "local","email":"admin@xyz.com","password":"admin123"}

Than you will get Token which you expected.

response:

{
    "accessToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6ImFjY2VzcyIsInR5cGUiOiJhY2Nlc3MifQ.eyJ1c2VySWQiOjEsImFjY291bnRJZCI6MSwiaWF0IjoxNTE",
    "code": 200,
    "authentication": "user login successful"
}

After that add this token to all other api calls in Headers Authorization equal to token.

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM