Sails.js API Passport.js身份验证 [英] Sails.js API passport.js authentication

查看:144
本文介绍了Sails.js API Passport.js身份验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在Sails.js中开发API后端.

I am trying to develop an API backend in Sails.js.

我需要的最基本的东西是身份验证.

The most basic thing which I require is authentication.

这样,我找到了sails-generate-auth生成器,我已经按照列出的所有步骤进行操作 sails-generate-auth .

With that, I found the sails-generate-auth generator, I have followed all the steps listed at sails-generate-auth .

现在,当我访问http://localhost:1337/register时,我会看到一个简单的注册表格,登录时也是如此,登录后,我在浏览器中看到一个设置为sails.sid的cookie.

Now, when I access http://localhost:1337/register, I see a simple registration form, same goes for login, and after logging in, I see a cookie set in my browser as sails.sid.

检查AuthController.js后,我发现它已为服务器渲染视图编写.

After inspecting the AuthController.js I see that it has been written for server rendered views.

如何修改controller/sailsApp,使其支持基于API的身份验证.

How should I modify the controller/sailsApp so that it supports API based authentication.

我理想地希望拥有:

  1. 通过邮寄接受用户名和密码的注册路线 内容类型为application/json.

  1. A register route which would accept username and password via post with content type application/json.

登录路径,该路径将接受用户名和密码 内容类型application/json并返回带有承载令牌的令牌,以便前端应用程序可以在下次发出请求时将其添加到其标头中.

Login route which would accept username and password with content-type application/json and return with a bearer token so that the frontend app can add it to its header the next time it makes a request.

auth ACL下的所有其他路由,将检查承载是否 令牌已存在并已验证.

All other routes under an auth ACL which would check if the bearer token is present and is verified.

推荐答案

在您的AuthController回调函数中,将其替换为:

In your AuthController callback function replace this:

res.redirect('/');

与此:

console.log(user);
var userID = user.id;
Passport.find({user: userID}, function(err, items){
    if(err) return err;

    console.log(items[0].accessToken);
    // Make sure you dont give them any sensetive data
    res.json({userData: user, token: items[0].accessToken});
});
// Upon successful login, send the user to the homepage were req.user
//res.redirect('/');

现在,当客户端发送登录/注册请求时,服务器将以JSON响应进行响应.确保您在其他Sails应用程序操作中请求令牌.

Now when the client sends a login/register request the server will response with a JSON response. Make sure you request the token on your other sails app actions.

这篇关于Sails.js API Passport.js身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆