【问题标题】:Token based Authentication with Angular使用 Angular 进行基于令牌的身份验证
【发布时间】:2016-08-24 18:07:19
【问题描述】:

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

【问题讨论】:

标签: angularjs local-storage token http-token-authentication angular-cookies


【解决方案1】:

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

此链接可以解释您基于令牌与基于 Cookie

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

这是 localStorage、sessionStorage、session 和 cookies 之间的区别: What is the difference between localStorage, sessionStorage, session and cookies?

【讨论】:

    【解决方案2】:

    强烈建议你使用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>
    

    【讨论】:

    • 我可以在我的 api 中使用它吗?我可以看到clientID,clientID是什么?另外我认为它使用其他社交网络登录,但不使用我自己的登录 API
    • 例如响应对 /auth/login 的 POST 请求。而不是 ourdomain.com/api/token
    • 什么是clientID,它是关于什么的?
    • 如果您想使用外部身份验证提供程序,例如 Facebook,但这不是您的情况
    • 我读到auth0,它似乎是一个在线用户管理系统,这不是我想要的
    猜你喜欢
    • 1970-01-01
    • 2016-02-21
    • 2018-03-20
    • 1970-01-01
    • 1970-01-01
    • 2020-04-13
    • 2016-09-14
    • 1970-01-01
    • 2021-01-25
    相关资源
    最近更新 更多