【问题标题】:Link AccessToken to a user in Loopback将 AccessToken 链接到 Loopback 中的用户
【发布时间】:2020-03-29 22:41:13
【问题描述】:

我想为访问令牌添加一个自定义属性 (expireAt),以便 MongoDB 使用它在过期时自动删除过期的访问令牌。

在使用AccessToken 模型创建访问令牌时添加自定义属性效果很好:

const ttl = 600;

const expireAt = new Date();
expireAt.setSeconds(expireAt.getSeconds() + ttl);

const token = await AccessToken.create({ ttl, expireAt });

但是,当我想为用户创建访问令牌时,我无法在创建令牌时添加自定义属性exprieAt,所以我先创建,然后更新它:

const ttl = 600;

const expireAt = new Date();
expireAt.setSeconds(expireAt.getSeconds() + ttl);

// Create the access token for the user
const token = await user.createAccessToken(options);
// Update token to set the custom date and time to expire
token.expireAt = expireAt;
token.save();

// Return the token together with the user data
return Object.assign({}, token.toJSON(), { user });

有没有一种方法可以为具有自定义属性的用户创建令牌(使用实例方法或模型方法都可以),而无需执行两个步骤 - 创建和更新?

【问题讨论】:

    标签: access-token strongloop loopback


    【解决方案1】:

    因此,AccessToken 模型似乎通过userId 属性与用户建立了关系(参考:https://github.com/strongloop/loopback/blob/master/common/models/access-token.json#L27)。

    {
      "name": "AccessToken",
      "properties": {
        "id": {
          "type": "string",
          "id": true
        },
        "ttl": {
          "type": "number",
          "ttl": true,
          "default": 1209600,
          "description": "time to live in seconds (2 weeks by default)"
        },
        "scopes": {
          "type": ["string"],
          "description": "Array of scopes granted to this access token."
        },
        "created": {
          "type": "Date",
          "defaultFn": "now"
        }
      },
      "relations": {
        "user": {
          "type": "belongsTo",
          "model": "User",
          "foreignKey": "userId"
        }
      },
      "acls": [
        {
          "principalType": "ROLE",
          "principalId": "$everyone",
          "permission": "DENY"
        }
      ]
    }
    

    要将令牌链接到用户,我们只需要传入值userId

    AccessToken.create({ ttl, expireAt, userId });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多