身份验证的Node.js应用与Angular.js和iOS客户端 [英] Authentication for Node.js App with Angular.js and iOS Clients

查看:160
本文介绍了身份验证的Node.js应用与Angular.js和iOS客户端的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图尽量多看不同的答案和岗位越好,但我仍然无法在适合我的需求的解决方案相当安定。我试图找出最好的(最有效的,但大多是比较安全)的方式来处理用户身份验证,登录等。

I've tried to read as many different answers and posts as possible, but I still can't quite settle on a solution that fits my needs. I'm trying to work out the best (most efficient, but mostly more secure) way to handle user authentication, log in, etc.

我有一个Node.js的服务器上,防爆preSS运行;我有一个Angular.js web应用程序;我有一个iOS应用。我揭露与前preSS / Node.js的一个RESTful API。

I have a Node.js server, running on Express; I have an Angular.js web app; and I have an iOS app. I expose a RESTful API with Express/Node.js.

的第一件事情我看书上说使用cookie,并存储在服务器端的会话ID /登入凭证(哈希)和客户端(散列的)。客户端会传递这个ID对每个请求,服务器就能把它,分析它,并相应地处理请求。这并不觉得REST风格的(不是一个巨大的问题),但更重要的是,我会重复我的API:一个用于用户名/密码认证(例如​​,通过卷曲完成),另一个是基于Cookie的身份验证(例如我的web应用程序)?

The first things I read said to use cookies, and to store a session id/login token on the server side (hashed) and on the client side (unhashed). The client would transfer this id with each request, the server would hash it, parse it and process the request accordingly. This does not feel RESTful (not a huge issue), but more importantly, would I have to duplicate my API: one for username/password authentication (e.g. done via curl) and one for cookie-based authentication (e.g. my web app)?

本的另一个问题:如果我已经从一个用户,例如多个连接,我会做他们在两个浏览器,iPhone和iPad的登录。我将其会话ID的存储需要,现在是一个数组?

Another problem with this: what I would do if I had multiple connections from the one user, e.g. they're logged in in two browsers, an iPhone and an iPad. Would my storage of their session ids need to now be an array?

接下来的想法是使用HTTP基本身份验证(使用SSL),这似乎很容易,但不推荐,因为你需要每个请求传输用户名和密码。如果我是用HTTP基本验证这样做,我会再在Cookie中存储(或HTML本地存储)允许记住我功能的用户名和密码?或者可以我结合两种:使用HTTP基本认证实际请求(发布一个新的职位等),并只使用存储在cookie中的初始日志序列中的会话ID /还记得我的方面

The next idea was to use HTTP Basic Auth (with SSL), which seems easy enough, but is not recommended because you need to transfer a username and password with each request. If I were to do it with HTTP Basic Auth, would I then store the username and password in cookies (or HTML local storage) to allow for 'Remember Me' functionality? Or could I combine the two: use HTTP Basic Auth for the actual requests (post a new post, etc.) and just use a session id stored in a cookie for the initial log in sequence/remember me aspects?

时发送会话ID不仅仅是传送用户的密码更安全?怎么样?
会话ID是将表面上充当密码,所以对我来说它发射将具有相同的安全问题作为发射密码。

Is transmitting a session id more secure than just transmitting the user's password? How? The session id is going to act ostensibly as a password, so to me transmitting it would have the same security issues as transmitting a password.

基本认证似乎在所有平台上,这是理想的支持。主要缺点似乎需要与每个请求传输客户端身份验证数据。有没有办法来缓解这个问题?

Basic Auth seems to be supported across all platforms, which is ideal. The main downside seems to be needing to transfer client authentication data with each request. Is there a way to mitigate this issue?

OAuth的似乎是大材小用我的需要。我想我会失去做卷曲的命令来测试我的API的能力。如何在OAuth的饼干方法的改进?

OAuth seems like overkill for my needs. I think I would lose the ability to do curl commands to test my API. How is OAuth an improvement over the cookies method?

正如你可能会说,我可有点糊涂了各种信息,所以如果你有一组很好的链接,适用于这种情况下,我喜欢阅读。我试图找到一个适合在所有平台上,但仍是尽可能安全的解决方案。另外,如果我有我的任何术语错了,请大家指正,因为它会使寻找我来说更容易。

As you can probably tell, I'm a little confused by the diverse information available, so if you have a set of good links—applicable to this scenario—I would love to read them. I'm trying to find a solution that fits across all platforms, but is still as secure as possible. Also, if I have any of my terminology wrong, please correct me because it will make searching easier for me.

感谢。

我一直在思考这个问题,我已经有了一个主意。请告诉我,如果这是哑巴/不安全/任何意见,因为我不知道它的好。

I've been thinking about this problem, and I've had an idea. Please tell me if this is dumb/insecure/any feedback, because I'm not sure if it's good.

当用户登录时,我们生成一个随机的会话ID(咸鱼等)。这的可选的会话ID被发送到客户端,客户端可以(在cookie中例如)存储,如果他们选择;会话ID是存储在数据库中。

When the user logs in, we generate a random session id (salted etc.). This optional session id is sent to the client, which the client can store (e.g. in cookies) if they choose; the session id is stored in the database.

此会话ID然后任选与每个请求的是HTTP认证头或查询字符串或客户端可以只发送,如果他们想要的用户名和密码(这给了我们我们的常规REST发API)。在服务器端,我们首先检查会话ID参数,如果它不是present,我们检查用户名/密码。如果没有是否有错误。

This session id is then optionally sent with each request as either an HTTP Authentication header or query string, or the client can just send the username and password if they want (which gives us our regular REST API). At the server end, we check first for a session id parameter, if it's not present, we check for username/password. If neither are there—error.

在服务器上,我们检查会话ID是与正确的用户名相关。如果是,我们完成请求。

On the server, we check that the session id is associated with the correct username. If it is, we complete the request.

在用户登录时,都会创建一个新的会话ID或删除当前之一,并在请求的响应到日志发送此。

Every time the user logs in, we create a new session id or delete the current one, and send this with the response to the log in request.

我觉得这让我用常规的REST API,在适当情况下,使用基本身份验证,并保持会话/记得我的功能。它并没有解决多个日志插件的问题,但除此之外,我觉得这种方式应该会的。请让我知道。

I think this lets me use the regular REST API, where appropriate, with Basic Auth, and maintain sessions/remember me functionality. It doesn't solve the multiple log ins issue, but otherwise I think this way should would. Please let me know.

推荐答案

我会用一个基于令牌的认证,您可以在每个请求发送令牌(自动)。你必须登录一次,服务器会为您提供一个令牌,然后可以使用每个请求发送。此令牌将被添加到HTML报头,这样就不必修改每个请求到浏览器。

I would use a token based authentication where you can send a token (automatically) with each request. You'll have to log in once, the server will provide you with a token which you can then use to send with each request. This token will be added to the HTML header, so that you don't have to modify each request to the browser.

您可以设置API中的某些呼叫,让他们总是需要一个道理,而另一些可能不被标记保护。

You can set certain calls in the API so that they always need a token, while others might not be token protected.

有关防爆preSS,您可以使用前preSS-智威汤逊(<一个href=\"https://www.npmjs.org/package/ex$p$pss-jwt\">https://www.npmjs.org/package/ex$p$pss-jwt)

For Express, you can use express-jwt (https://www.npmjs.org/package/express-jwt)

var expressJwt = require('express-jwt');

// Protect the /api routes with JWT
app.use('/api', expressJwt({secret: secret}));

app.use(express.json());
app.use(express.urlencoded());

如果你想验证你可以在你的前preSS服务器创建此功能:

If you want to authenticate you can create this function in your express server:

app.post('/authenticate', function (req, res) {
  //if is invalid, return 401
  if (!(req.body.username === 'john.doe' && req.body.password === 'foobar')) {
    res.send(401, 'Wrong user or password');
    return;
  }

  var profile = {
    first_name: 'John',
    last_name: 'Doe',
    email: 'john@doe.com',
    id: 123
  };

  // We are sending the profile inside the token
  var token = jwt.sign(profile, secret, { expiresInMinutes: 60*5 });

  res.json({ token: token });
});

和受保护的呼叫东西带/ API启动:

And for protected calls something that starts with /api:

app.get('/api/restricted', function (req, res) {
  console.log('user ' + req.user.email + ' is calling /api/restricted');
  res.json({
    name: 'foo'
  });
});

在您的应用角度您可以登录:

In your Angular application you can login with:

$http
      .post('/authenticate', $scope.user)
      .success(function (data, status, headers, config) {
        $window.sessionStorage.token = data.token;
        $scope.message = 'Welcome';
      })
      .error(function (data, status, headers, config) {
        // Erase the token if the user fails to log in
        delete $window.sessionStorage.token;

        // Handle login errors here
        $scope.message = 'Error: Invalid user or password';
      });

和通过创建一个验证拦截器,它会自动与每个请求发送令牌:

And by creating an authentication interceptor, it will automatically send the token with every request:

myApp.factory('authInterceptor', function ($rootScope, $q, $window) {
  return {
    request: function (config) {
      config.headers = config.headers || {};
      if ($window.sessionStorage.token) {
        config.headers.Authorization = 'Bearer ' + $window.sessionStorage.token;
      }
      return config;
    },
    response: function (response) {
      if (response.status === 401) {
        // handle the case where the user is not authenticated
      }
      return response || $q.when(response);
    }
  };
});

myApp.config(function ($httpProvider) {
  $httpProvider.interceptors.push('authInterceptor');
});

如果您有支持不支持本地存储旧的浏览器。你可以像AmplifyJS( http://amplifyjs.com/库交换 $ window.sessionStorage )。放大例如使用任何的localStorage可用。这将翻译成这样的:

If you have to support old browsers which do not support local storage. You can swap the $window.sessionStorage with a library like AmplifyJS (http://amplifyjs.com/). Amplify for example uses whatever localstorage is available. This would translate in something like this:

    if (data.status === 'OK') {
      //Save the data using Amplify.js
      localStorage.save('sessionToken', data.token);
      //This doesn't work on the file protocol or on some older browsers
      //$window.sessionStorage.token = data.token;
      $location.path('/pep');
    }
  }).error(function (error) {
    // Erase the token if the user fails to log in
    localStorage.save('sessionToken', null);
    // Handle login errors here
    $scope.message = 'Error: Invalid user or password';
  });

和我们交换了authintercepter:

And the authintercepter we swap for:

angular.module('myApp.authInterceptor', ['myApp.localStorage']).factory('authInterceptor', [
  '$rootScope',
  '$q',
  'localStorage',
  function ($rootScope, $q, localStorage) {
    return {
      request: function (config) {
        config.headers = config.headers || {};
        config.headers.Authorization = 'Bearer ' + localStorage.retrieve('sessionToken');
        return config;
      },
      response: function (response) {
        if (response.status === 401) {
        }
        return response || $q.when(response);
      }
    };
  }
]);

您可以找到除了在这篇文章中AmplifyJS一切:

You can find everything except AmplifyJS in this article:

<一个href=\"http://blog.auth0.com/2014/01/07/angularjs-authentication-with-cookies-vs-token/\">http://blog.auth0.com/2014/01/07/angularjs-authentication-with-cookies-vs-token/

这篇关于身份验证的Node.js应用与Angular.js和iOS客户端的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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