【问题标题】:Using a JSON user object for Authentication in AngularJS在 AngularJS 中使用 JSON 用户对象进行身份验证
【发布时间】:2023-04-03 06:52:01
【问题描述】:

所以我有一个关于身份验证的问题,并且一直想知道其他人如何处理这种情况。我目前正在运行一个基于 Rails API 构建的 Angular 应用程序。

到目前为止,对于身份验证,我有一个表单向 Rails 端发送一个帖子,该表单将用户登录,然后在成功时将它们发送回 Angular 应用程序。设置 cookie 并且用户登录后,我就可以访问 user.json 文件,该文件包含人们可能期望的所有用户信息(ID、用户名、角色、权限等)。由于验证都发生在 Rails 上,如果用户注销,则此信息将被删除。所以这两个状态看起来是这样的……

已登录

{
id: 99384,
name: "Username",
url: "//www.test.com/profiles/Username",
timezone: null,
rights: [ ],
roles: [
"admin"
],
}

退出

{
error: "You need to login or join before continuing."
}

到目前为止,我已经看到了数百万种为 Angular 进行身份验证的不同方法,但似乎没有任何方法适合这种方法。所以我的问题是,由于服务器正在处理所有验证,有没有办法检查他们的 user.json 文件是否为空(显示错误消息)以及是否将 Angular 应用程序发送到 Rails 登录页面?当我可以将所有内容都基于 JSON 文件时,真的有任何必要搞乱 Cookie、令牌等吗?

【问题讨论】:

    标签: ruby-on-rails json angularjs authentication


    【解决方案1】:

    您已经在使用 cookie - 服务器正在设置它们。你所做的是一种相当标准的做事方式。

    要检查 json 文件,您可以在控制器中执行类似于此存根显示的操作:

    app.controller('AppControl', function($scope, $http, $location){
    
        // Get the JSON file.
    
        $http.get('/path/to/json/file')
    
        .then(response){
    
          if(response.data.error){
            // redirect to login
            $location.path('login');
    
          }
    
          else{
    
            $scope.user = response.data;
            // your app code here.
    
          }
    
        })
    
        .catch(function (error){
          // unable to reach the json file - handle this.
        });
    
    });
    

    当然,你真的应该把它移到服务中,这样你就可以重复使用它,并且缓存数据,而不是每次更改路由/页面时都获取用户,但这会给你一个模糊的概念。

    编辑示例工厂:

    .factory('User', function( $http ){
    
      // Create a user object - this is ultimately what the factory will return.
      // it's a singleton, so there will only ever by one instance of it.
      var user = {};
    
      // NOTE: I am assigning the "then" function of the login promise to 
      // "whenLoggedIn" - your controller code is then very easy to read.
      user.whenLoggedIn = $http.get('user.json')
    
        .then(function(response){
    
          // Check to see if there is an error.
          if (response.data.error !== undefined) {
            // You could be more thorough with this check to determine the 
            // correct action (examine the error)
            user.loggedIn = false;
    
          }
    
          else {
            // the user is logged in
            user.loggedIn = true;
            user.details = response.data;
    
            return user;
    
          }        
        }).then; // <-- make sure you understand why that .then is there.
    
      return user;
    
    })
    

    在控制器中的使用

    .controller('ExampleController', function($scope, User){
    
      // It's handy to have the user on the scope - you can use it in your markup
      // like I have with ng-show on index.html.
      $scope.User = User;
    
      // Do stuff only if the user is loggedin.
      // See how neat this is because of the use of the .then function
      User.whenLoggedIn( function (user){
    
        console.log(user.details.name + " is logged in");
    
      });
    
    
    });
    

    因为它在作用域上,我们可以在 html 中这样做:

    <body ng-controller="ExampleController">
      <h1 ng-show="User.loggedIn == null">Logging in..</h1>
      <h1 ng-show="User.loggedIn == true">Logged in as {{ User.details.name }}</h1>
      <h1 ng-show="User.loggedIn == false">Not logged in</h1>
    </body>
    

    这是一个example on plunker,它正在工作。

    注意以下几点:

    • 如果用户已经/已经登录,当你以后注入服务时,它不会再次检查文件。您可以在服务上创建其他方法来重新检查文件,并将用户注销、重新登录等。我将由您决定。

    • 还有其他方法可以做到这一点 - 这只是一种可能的选择!

    • 这可能很明显,但总是值得一提。您需要主要处理服务器端的身份验证和安全性。客户端只是用户体验,并确保用户不会看到混乱或冲突的屏幕。

    【讨论】:

    • 非常感谢!所以据我了解,我并没有真正使用 ngCookies 来验证登录状态,因为我真的不需要?另外,您提到将其用作服务;这将如何影响在某些页面上我不关心用户是否登录但在其他页面上我需要检查身份验证的事实?我是否将此服务注入 UI-Router?这有什么例子吗?抱歉所有问题....
    • 没问题 - 如果有帮助,请点赞/接受 :)。您没有使用ngCookies,不,您不需要 - 只需在服务器端执行此操作即可。对于服务部分 - 将服务器注入需要身份验证的页面的控制器中。在你做任何事情之前检查用户,如果用户没有被填充,做你的重定向。
    • 还不能投票 :( 但我会接受。最后一个问题,然后我就不说了。就如何设置示例控制器而言,工厂将如何设置? 到目前为止,我刚刚建立了简单的工厂来提取 JSON 信息并在控制器中显示。P.S. 非常感谢帮助新人......
    • 更新了一个示例工厂。这确实是最低要求 - 但希望它能给您一个正确的起点。
    • 真正令人惊叹的帮助 Ed。非常感谢!
    猜你喜欢
    • 2016-04-13
    • 2014-01-14
    • 1970-01-01
    • 2013-03-11
    • 2017-05-09
    • 1970-01-01
    • 1970-01-01
    • 2012-09-29
    • 1970-01-01
    相关资源
    最近更新 更多