使用用户模型环回时出现401错误

Getting 401 error in loopback with User Model

本文关键字:错误 用户 模型      更新时间:2023-09-26

我在另一个DB中有超过5k个用户的列表,并且我想迁移环回DB中的所有用户,存在许多重复的用户,因此我正在检查用户是否存在,然后我正在更新用户,否则我正在创建新用户。我已经为此写了一个脚本。它的工作很好,但在更新第一个用户后,环回开始抛出错误401未经授权,如果我执行GET用户详细信息API。即使我已经允许未经身份验证的用户访问更新,创建与ACL属性,但它不工作与此以及。

我已经扩展了User模型。

谁能给点光?帮助将不胜感激!

谢谢

LoopBack的默认acl比您定义的更具体,因此您的acl在结束时不起作用。@authenticated和@unauthenticated ALLOW规则没有优先于DENY all规则。但是自定义角色可以,并且在框架中使用自定义ADMINISTRATOR角色是正确的方法。

  1. 需要为指定用户创建Role
  2. 使用角色映射模型将该角色映射给用户。

步骤1和步骤2可以用这个引导脚本完成(例如:App/server/boot/create-admin-user.js):

module.exports = function(app) {
  var User = app.models.ExtendedUser;
  var Role = app.models.Role;
  var RoleMapping = app.models.RoleMapping;
  User.findOrCreate({ where: { username: 'admin', email: 'admin@admin.com' } },
  {
    username: 'admin', 
    email: 'admin@admin.com', 
    password: 'admin123'
  }, 
  function(err, user) {
      if (err) return console.log(err);
      // Create the admin role
      Role.findOrCreate({where: { name: 'ADMINISTRATOR' }},
        { name: 'ADMINISTRATOR' }, 
        function(err, role) {
          if (err) return debug(err);
          console.log("Role Created: " + role.name);     
          // Assign admin role
          RoleMapping.findOrCreate({where: { roleId: role.id, principalId: user.id }},
            { roleId: role.id, principalId: user.id, principalType: RoleMapping.USER }, 
            function(err, roleMapping) {
              if (err) return console.log(err);
              console.log("ADMINISTRATOR Role assigned to " + user.username);
            });        
        });
    });
};
  • ExtendedUser模型中创建ACL表项,允许角色ADMINISTRATOR写:
  • ' ' '

    {
      "name": "ExtendedUser",
      "base": "User",
      /* ... */
      "acls": [
        {
          "accessType": "READ",
          "principalType": "ROLE",
          "principalId": "$authenticated",
          "permission": "ALLOW"
        },
        {
          "accessType": "WRITE",
          "principalType": "ROLE",
          "principalId": "ADMINISTRATOR",
          "permission": "ALLOW"
        }
      ]
    }