繁体   English   中英

基于令牌的Angular身份验证

[英]Token based Authentication with Angular

我想通过api对用户进行身份验证,当用户名和密码正确时,它会返回一个令牌,并使用ngStorage存储在本地存储中,但我读到一些文章说,将令牌存储在localStorage上并不安全,他们提到了将其存储到cookie 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");
      });
}

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

该链接可以为您解释基于令牌和基于Cookie的情况

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

这就是localStorage,sessionStorage,会话和cookie 之间的区别:localStorage,sessionStorage,会话和cookie之间有什么区别?

我热烈建议您使用Stallizer: https : //github.com/sahat/satellizer

用电子邮件和密码登录

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

客户:在表单上提交带有电子邮件和密码的呼叫$ auth.login()。

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

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

服务器:创建一个JSON Web令牌并将其发送回客户端。

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

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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM