身份验证在不应该返回“401(未经授权)”时返回

2024-05-29

我第一次设置身份验证功能,在用户登录后得到了一些意外的结果。一位同事给了我一个具有工作身份验证的应用程序,以模仿我的应用程序,看起来我所做的一切都是正确的。

我在前端使用 AngularJS,在后端框架使用 SailsJS,并且护照JS http://passportjs.org/身份验证中间件。

我的源代码(目前)是公开存储的...后端 API 位于 Github 上(API GitHub https://github.com/djlovegrind/smallChange-API),前端代码可以在这里找到(前端 Github https://github.com/djlovegrind/smallChange-dashboard)

基本上发生的事情是用户

  1. 点击登录按钮,触发此功能

    login: function (credentials) {
        return baseAuth.customPOST(credentials, 'login').then(function (user) {
            $log.debug('User logged in: ', user);
            isAuthenticated = true;
            return user;
        });
    },
    
  2. 该 customPOST 的控制器逻辑是这样的

    login: function (req, res, next) {
       passport.authenticate('local', function (err, user, info) {
           if (err) { return res.json(err); }
           else if (user) {
               req.logIn(user, function (err) {
                   if (err) { return res.json(err); }
                   return res.json(user);
               });
           } else { return res.json(400, info); }
    
       })(req, res);
    
    },
    
  3. 在那一步中,护照应该做它的事情并登录用户

    passport.use(new LocalStrategy({ usernameField: 'email', passwordField: 'password' },
    function(email, password, next) {
       User.findOne({ email: email })
           .exec(function (err, user) {
               if (err) { return next(err); }
               if (user) {
                    if (user.activated) {
                    bcrypt.compare(password, user.password, function (err, valid) {
                        if (err) { next(err); }
                        if (valid) {
                            return next(null, user, { message: 'Logged In' });
                        } else { return next(null, false, { message: 'Incorrect password'}); }
                    });
                } else { next(null, false, { message: 'User is not activated. Please contact admins.'}); }
            } else { next(null, false, { message: 'Could not find user with email ' + email }); }
        });
       }
     ));
    

在控制台中,我总是知道这是成功的。

控制台显示:

User logged in:  Object {firstName: "John", lastName: "Doe", email: "[email protected] /cdn-cgi/l/email-protection", activated: true, isUser: true…}
  1. 然后,我对发生的事情的理解变得有点模糊。我知道应用程序然后会尝试查看用户是否经过身份验证。 IsAuthenticated 被触发,在 AngularJS 中看起来像这样:

    isAuthenticated: function (force) {
        var deferred = $q.defer();
    
        if (isAuthenticated && currentUser) {
            deferred.resolve(currentUser);
        } else {
            return baseAuth.customGET('authenticated').then(function (user) {
                deferred.resolve(currentUser);
                isAuthenticated = true;
                currentUser = user;
                return user;
            });
        }
    
        return deferred.promise;
    }
    
  2. 它在后端 UserController 中执行此操作

    isAuthenticated: function (req, res) {
       if (req.isAuthenticated() && req.user.isUser) { return res.json(req.user); }
       else { return res.send(401); }
    },
    

然后就失败了:(GET http://localhost:1337/user/authenticated 401 (Unauthorized)req.isAuthenticated 和 req.user.isUser 均未通过。我把它们分开来单独测试,但它们都不是真的。 “isUser”是我默认为 true 的值,因此对于数据库中的每个用户都应该为 true。 req.isAuthenticated 也失败,我不完全理解。

有人对我的问题有一些见解吗?我在这里做错了什么?


如果您的前端应用程序与后端应用程序具有不同的来源AJAX 请求不会包含会话 cookie https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS#Requests_with_credentials and req.isAuthenticated()永远不会返回 true。

使用 withCredentials 选项强制执行。

$http({ withCredentials: true, ... })

看起来 Restangular 使用相同的选项:

https://github.com/mgonto/restangular#setdefaulthttpfields https://github.com/mgonto/restangular#setdefaulthttpfields

https://docs.angularjs.org/api/ng/service/$http#usage https://docs.angularjs.org/api/ng/service/%24http#usage

编辑:您还应该检查服务器端配置 http://sailsjs.org/documentation/anatomy/my-app/config/cors-js正如 idbehold 所指出的


正如 Matan 所建议的,您确实应该尝试一下服务器端的 sails-generate-auth 生成器。

https://github.com/sails101/even-more-passport https://github.com/sails101/even-more-passport

https://github.com/kasperisager/sails-generate-auth https://github.com/kasperisager/sails-generate-auth

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

身份验证在不应该返回“401(未经授权)”时返回 的相关文章

  • 来自heroku的https请求

    我想通过 https 协议从 vk com api 获取数据 像这样 var https require https https get https api vk com method users get access token glob
  • Node.js 多线程程序

    我编写了一个 node js 脚本来从交易所获取一些价格 它看起来像这样 async function main async function func var start time performance now for let rout
  • 使用node+express解压POST正文

    我有一个简单的节点应用程序 应该从客户端写入指标 客户端以 json 格式发送指标 并用 python 的 zlib 模块压缩 我试图添加一个中间件来在快速 bodyParse 发生之前解压缩请求帖子 我的中间件就是express默认提供的
  • NodeJS MySQL - 如何知道连接是否释放

    我正在开发 NodeJS MySQL Web API 我在用mysql https www npmjs com package mysqlnpm 模块 我想知道连接是否已释放 是否有任何函数或变量 喜欢 if connection isRe
  • 角度2:语法错误:意外的标记<(...)

    我知道 这个问题已经被问过 但我找不到适合我的特定情况的解决方案 我无法理解错误的真正原因 我有一个运行良好的 angularjs2 应用程序 现在我想导入marked图书馆 我做了什么 npm install marked tsd ins
  • 如何在nodejs中处理xhr blob post

    客户端代码 var xhr new XMLHttpRequest xhr open POST frame true xhr send blob 服务器代码 app use bodyParser urlencoded extended fal
  • 将最新的 terser-webpack-plugin 与 Webpack5 一起使用

    根据这个链接 简洁的文档 https webpack js org plugins terser webpack plugin terseroptions如果您使用最新的 Webpack 5 则无需安装 Terser 插件 因为它已包含在
  • 对于向 XSS 漏洞开放 JWT,我应该有多担心?

    我正在构建一个 Node js Web 应用程序 该应用程序使用用于 GUI 的 React 和由 Apollo 提供的 graphQL 用于连接到 AWS 上的 RDS MySQL 实例的后端 我正在对用户进行身份验证 然后返回 JWT
  • Passport-Local 和 deSerializeUser 问题的简单身份验证

    阅读此处有关如何在 Passport 流程中反序列化和序列化用户工作的精彩描述后 了解护照序列化反序列化 https stackoverflow com questions 27637609 understanding passport s
  • 映射警告时反应唯一键

    我对反应还很陌生 我面临着一个无法解决的问题 这是我的反应组件 import React from react import Header from Header import ContestPreview from ContestPrev
  • 是否可以调试当前正在运行的生产节点应用程序?

    在本地我通过运行进行调试node debug并使用node inspector工具 节点检查器必须在后台运行 然后我将浏览器指向 并非所有浏览器都可以工作 Chrome 可以 http 127 0 0 1 8080 debug port 5
  • 我无法在项目中使用节点波本威士忌

    我尝试对 scss 文件使用 npm 模块 波本威士忌 我收到以下错误 with function var paths Array prototype slice call arguments return concat apply bou
  • 从 .NET 应用程序登录 Windows

    我认为它应该是一个Windows服务 当给定某些条件时 它应该执行登录到机器的操作 机器将在 登录屏幕 中检查网络服务 以了解登录时应使用的用户名和密码 这可以吗 我不想要 自动登录 Windows 功能 Thanks AFAIK 无法完成
  • 不使用 data-* 前缀的自定义 HTML 属性是否有效? [关闭]

    就目前情况而言 这个问题不太适合我们的问答形式 我们希望答案得到事实 参考资料或专业知识的支持 但这个问题可能会引发辩论 争论 民意调查或扩展讨论 如果您觉得这个问题可以改进并可能重新开放 访问帮助中心 help reopen questi
  • Angular UI Grid - 将图像导出为 pdf

    我想将图像添加到 pdf 的标题中 我正在尝试添加已转换为 base64 的图像以导出 Pdf 标题 scope gmGrid exporterPdfHeader margin 30 5 30 15 table widths body MC
  • Angular 资源测试:$httpBackend.flush() 导致意外请求

    我想测试 angularjs 资源 use strict AddressService provides functionality to use address resource in easy way This is an exampl
  • 为什么 NodeJS 不支持 String.prototype.replaceAll?

    这个字符串方法存在于 browserland 中 但不存在于 Node 中 为什么不 它既不是全新的 也不是异国情调的 replaceAll is part of ECMA 262 src https tc39 es ecma262 sec
  • 量角器中的“$”选择器

    我见过很多这样的例子 selector 我也在用这个 那么这又是什么 变量确实如此 这是我从量角器得到的docs https angular github io protractor api view ElementFinder proto
  • 将输入包装在角度指令中

    我的想法是将输入包装到自定义指令中 以保证整个网站的外观和行为一致 我还想包装 bootstrap ui 的日期选择器和下拉菜单 此外 该指令应该处理验证并显示工具提示 HTML 应该看起来像这样
  • 如何摆脱 Devise 上的电子邮件正则表达式消息?

    我在用着设计令牌认证 https github com lynndylanhurley devise token authgem 每次我在 Rails 4 2 5 应用程序中运行测试套件时 我都会收到来自 Devise 的弃用警告 弃用警告

随机推荐