0

我想通过 api 对用户进行身份验证,当用户名和密码正确时,它会返回一个令牌并使用 ngStorage 存储在本地存储中,但我阅读了一些文章,认为在 localStorage 上保存令牌并不安全,他们参考了将其存储到 cookies Http。如何将令牌存储在 cookie Http 上,它是否安全,或者是否有更好的方法来处理令牌身份验证

$scope.loginUser = function(){
    $http({
      method: 'POST',
      url: 'ourdomain.com/api/token',
      headers: 
      {
          'Content-type': 'application/x-www-form-urlencoded',
      },
      data: 
      'UserName=' + $scope.username + 
      '&Password=' + $scope.password 
      }).success(function(data, status) {
               $localStorage.token = data;
               console.log(data);
      })
      .error(function(data, status) {
          console.log("Error");
      });
}
4

2 回答 2

2

对于 cookie,用户可以禁用 cookie。

这个链接可以解释你基于令牌与基于 Cookie

https://auth0.com/blog/2014/01/07/angularjs-authentication-with-cookies-vs-token/

这是localStorage、sessionStorage、session和cookies 之间的区别:localStorage、sessionStorage、session和cookies有什么区别?

于 2016-04-29T14:39:04.970 回答
1

我强烈建议您使用stallizer:https ://github.com/sahat/satellizer

使用电子邮件和密码登录

客户:在登录表单中输入您的电子邮件和密码。

客户:在表单提交时,使用电子邮件和密码调用 $auth.login()。

客户端:向 /auth/login 发送 POST 请求。服务器:检查电子邮件是否存在,如果不存在 - 返回 401。

服务器:检查密码是否正确,如果不正确 - 返回 401。

服务器:创建 JSON Web Token 并将其发送回客户端。

客户端:解析令牌并将其保存到本地存储以供页面重新加载后的后续使用。

var user = {
  email: $scope.email,
  password: $scope.password
};

$auth.login(user)
  .then(function(response) {
    // Redirect user here after a successful log in.
  })
  .catch(function(response) {
    // Handle errors here, such as displaying a notification
    // for invalid email and/or password.
  });


// Controller
$scope.isAuthenticated = function() {
  return $auth.isAuthenticated();
};

<!-- Template -->
<ul ng-if="!isAuthenticated()">
  <li><a href="/login">Login</a></li>
  <li><a href="/signup">Sign up</a></li>
</ul>
<ul ng-if="isAuthenticated()">
  <li><a href="/logout">Logout</a></li>
</ul>
于 2016-04-29T14:39:00.507 回答