javascript - Ajax请求cors和cookies步骤

标签 javascript ajax request cors

我在 localhost:1841 有一个客户端前端,在 localhost:9000 有一个后端。

我的身份验证系统使用一对简单的用户名/密码来传递 Json Web token (jwt)。

当我的客户收到 token 时,我要求他使用 javascript 将其保存在 cookie 中。但是当我从我的客户端 (:1841) 向我的服务器 (:9000) 发出 XmlhttpRequest 调用时,请求中没有 cookie。所以我的服务器提供了 401(行为正常)。 我知道这是正常的,由于 SAME-ORIGIN-POLICY,cookie 中没有信息被发送。

我使用 extjs 6 作为客户端,使用 node js 作为服务器。

要在服务器端和客户端配置哪些步骤才能使其正常工作?

在服务器端我已经授权了 cors 请求。 我听说过 httpOnly 吗?但我不知道如何处理它?<​​/p>

从 localhost:1841(extjs 客户端)调用登录:

    Ext.Ajax.request({
        url: 'http://localhost:9000/api/users/authenticate/',
        method: 'POST',
        params: params,
        success: function(response){
            var text = response.responseText;
            var data = Ext.decode(text, true);

            if(data.access_token){
                me.saveToken(data.access_token);
                me.createInterface();
            } else {
                if(data.message){
                    Ext.Msg.alert("Bummer", data.message);
                } else {
                    Ext.Msg.alert("Bummer", "Something went wrong.");
                }
            }
        },

cors 的配置:

cors = require('cors');
...
...
... 
var whitelist = ['http://127.0.0.1:9000', 'http://localhost:8080', 'http://localhost:9000', 'http://127.0.0.1:8080', 'http://localhost:1841', 'http://127.0.0.1:1841']
 var corsOptionsDelegate = function (req, callback) {
    var corsOptions;
     if (whitelist.indexOf(req.header('Origin')) !== -1) {
        corsOptions = { origin: true } // reflect (enable) the requested origin in the CORS response
    }else{
        corsOptions = { origin: false } // disable CORS for this request
 }
    callback(null, corsOptions) // callback expects two parameters: error and options
}
...

module.exports = function(app) {
....
app.use(cors(corsOptionsDelegate));

}

来自客户的其他电话:

Ext.ajax.request({
  url : 'http://localhost:9000/api/users/'
  method : 'POST'
  success: function(response){
        var text = response.responseText;
        var data = Ext.decode(text, true);
        ...
        ...
        }
    },
})

来自服务器的验证:

function isAuthenticated() {
    return compose()
//     Validate jwt
        .use(function (req, res, next) {

            ....
            ....
            console.log(req.headers.authorization);


            validateJwt(req, res, function (err) {

                if (err) {
                    console.log(err.inner.name);
                    if (err.inner.name === "TokenExpiredError") {
                        // client have to request token with his refresh_token
                        return next({"error":err.inner.name});
                    }
                }
                next();
            });

    })
    .use(function (req, res, next) {
        ....

        });
    });

编辑 1:

我在节点中添加了 Set-Cookie 并且 Set-Cookie 出现在响应 header 和来自 DevTools 的预览 cookie 中。但是cookies没有在浏览器中设置。

exports.authenticate = function(req, res, next){
    User.findOne({
        fullName: req.body.username
    }, function(err, user) {
    ....
        if (!user) {
            res.status(401).json({
                success: false,
                message: 'Authentication failed. User not found.'
            });
        } else {
            // Check if password matches

            if(user.authenticate(req.body.password)){
                var access_token = jwt.sign(user, config.secrets.session, {
                    expiresIn: 60 // in seconds
               });

               res.cookie('access_token',access_token);

               res.status(200).json({
                   "success": true,
                   "access_token" : access_token
                   //token: 'JWT ' + token
                   });
            }else{
              ....
            }
        }
    });
}

最佳答案

根据您使用 ExtJS Ajax所以你可以使用 defaultXhrHeader将 token 从客户端发送到服务器端的属性。

Firstly as you are calling authenticate request for getting token. Here you can use ExtJS Cookies for set and get token or cookies.

Ext.Ajax.request({
     url: 'http://localhost:9000/api/users/authenticate/',
     params: params,
     method: 'POST',
     success: function(response, opts) {
         var data = Ext.decode(response.responseText;);
         if (data.access_token) {
             //Set cookie in our client side using Utility class for setting/reading values from browser cookies. 
             Ext.util.Cookies.set('access_token', data.access_token);
         } else {
             if (data.message) {
                 Ext.Msg.alert("Bummer", data.message);
             } else {
                 Ext.Msg.alert("Bummer", "Something went wrong.");
             }
         }
     },
     failure: function(response, opts) {
         console.log('server-side failure with status code ' + response.status);
     }
 });

Now you need to pass same token Ajax request using defaultXhrHeader

这是例子:-

Ext.Ajax.request({
     url: 'http://localhost:9000/api/users/',
     method: 'POST', //As per method acceptance you can use (GET,PUT,DELETE).
     //send cookie sever side using defaultXhrHeader 
     defaultHeaders: {
         'access_token': Ext.util.Cookies.get('access_token'),
         'Content-Type': 'application/json;charset=utf-8'
     },
     success: function(response, opts) {
         var data = Ext.decode(response.responseText;);
         //Put your logic here.
     },
     failure: function(response, opts) {
         console.log('server-side failure with status code ' + response.status);
     }
 });

As you using NodeJs in server side so you can get token from header.

关于javascript - Ajax请求cors和cookies步骤,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46937569/

相关文章:

node.js - 如何将不同请求的响应与nodejs和请求放在同一个文档中?

get - Bittorrent 跟踪器请求

javascript - 在 JavaScript 中格式化 document.write() 的输出

javascript - jQuery 获取 onChange 上的最后一个值

javascript - 在 Express Route 中使用 Multer? (使用 MEANJS)

php - 将 $_session ['username' ] 保存在 ajax 函数中

javascript - 在 beforeSend ajax 上禁用按钮链接

javascript - 如果我在固定的 div 中,则无法检测到滚动到顶部

php - 计算动态添加的表单元素的总和

使用 APIRequestFactory : how to pass "flat" parameter to a view 进行 Django 测试