认证返回"401(未授权)".什么时候不应该 [英] Authentication is returning "401 (Unauthorized)" when it shouldn't

查看:147
本文介绍了认证返回"401(未授权)".什么时候不应该的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我第一次设置身份验证功能,并且在用户登录后得到了一些意想不到的结果.一位同事给了我一个具有有效身份验证的应用程序,以便在此之后为我的应用程序建模.做的是正确的.

I am setting up an authentication functionality for my first time and am getting some unexpected results after a user has been logged in. A colleague has given me an application with working authentication to model my application after and it seems like everything I have done is correct.

我在前端,SailsJS后端框架和 PassportJS 身份验证中间件上使用AngularJS.

I am using AngularJS on the front-end, SailsJS back-end framework, and PassportJS authentication middleware.

(目前)我的来源已公开存储...后端API位于Github上( API Github ),并在此处找到前端代码(前端Github )

My source is (for now) stored publicly... the backend API is on Github here (API Github) and the front-end code is found here (Front-End Github)

基本上发生的是用户

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

  1. Hits the login button, which triggers this function

login: function (credentials) {
    return baseAuth.customPOST(credentials, 'login').then(function (user) {
        $log.debug('User logged in: ', user);
        isAuthenticated = true;
        return user;
    });
},

  • 该customPOST的控制器逻辑是

  • The controller logic for that customPOST is this

    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);
    
    },
    

  • 在这一步中,护照应该做它的事情并登录用户

  • In that step, passport should do its thing and login the user

    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 }); }
        });
       }
     ));
    

  • 在控制台中,我总是得到成功的提示.

    In the console, I always get that this is successful.

    控制台显示:

    User logged in:  Object {firstName: "John", lastName: "Doe", email: "john_doe@work.com", activated: true, isUser: true…}
    

    1. 然后,我对所发生的事情的理解有些模糊.我知道应用程序然后尝试查看用户是否已通过身份验证. IsAuthenticated被触发,在AngularJS中看起来像这样:

    1. Then, my understanding of what happens gets kind of fuzzy. I know the application then tries to see if the user is authenticated. IsAuthenticated gets triggered, which looks like this in 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;
    }
    

  • 它将在后端UserController中执行此操作

  • It hits this action in the backend 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的值,并且是因此,对数据库中的每个用户来说都是如此.req.isAuthenticated也会失败,我不完全理解.

    Then it fails :( GET http://localhost:1337/user/authenticated 401 (Unauthorized) Neither req.isAuthenticated nor req.user.isUser pass. I have separated them out to individually test and neither of them are true. "isUser" is a value I default to true and is so it should be true for every single user in the db. req.isAuthenticated also fails, which I don't entirely understand.

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

    Anyone have some insight into my problem? What I have I done wrong here?

    推荐答案

    如果您的前端应用程序与后端应用程序具有不同的来源

    If your frontend application has as a different origin than your backend application the AJAX requests will not include the session cookie and req.isAuthenticated() will never returns true.

    使用withCredentials选项将其强制.

    Use the withCredentials options to force it.

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

    Restangular似乎使用相同的选项:

    It seems that Restangular uses the same options:

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

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

    您还应该检查服务器端配置正如idbehold指出的那样

    You should also check the server side configuration as pointed out by idbehold

    按照Matan的建议,您应该真正尝试一下服务器端的sails-generate-auth生成器.

    As suggested by Matan, you should really give a try to the sails-generate-auth generator on the server side.

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

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

    这篇关于认证返回"401(未授权)".什么时候不应该的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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