令牌数据

在请求的生命周期中,你可以通过访问 req.user 来获取已配置存储在 JWT 中的数据。用户对象会自动附加到请求中。

定义令牌数据

你可以通过在认证集合的字段上设置 saveToJWT 属性,来指定哪些数据会被编码到 Cookie/JWT 令牌中。

import type { CollectionConfig } from 'payload'

export const Users: CollectionConfig = {
  slug: 'users',
  auth: true,
  fields: [
    {
      // 该字段会被存储在 JWT 中
      saveToJWT: true,
      type: 'select',
      name: 'role',
      options: ['super-admin', 'user'],
    },
    {
      // 整个对象会被存储在 JWT 中
      // tab 字段也可以实现同样功能!
      saveToJWT: true,
      type: 'group',
      name: 'group1',
      fields: [
        {
          type: 'text',
          name: 'includeField',
        },
        {
          // 该字段不会包含在 JWT 中
          saveToJWT: false,
          type: 'text',
          name: 'omitField',
        },
      ],
    },
    {
      type: 'group',
      name: 'group2',
      fields: [
        {
          // 该字段会被存储在 JWT 中
          // 但会存储在顶层
          saveToJWT: true,
          type: 'text',
          name: 'includeField',
        },
        {
          type: 'text',
          name: 'omitField',
        },
      ],
    },
  ],
}

提示:

如果你想使用字段 name 以外的其他键名,可以将 saveToJWT 定义为字符串。

使用令牌数据

这在编写依赖于用户定义字段的钩子访问控制时特别有用。

import type { CollectionConfig } from 'payload'

export const Invoices: CollectionConfig = {
  slug: 'invoices',
  access: {
    read: ({ req, data }) => {
      if (!req?.user) return false
      // highlight-start
      if ({ req.user?.role === 'super-admin'}) {
        return true
      }
      // highlight-end
      return data.owner === req.user.id
    }
  }
  fields: [
    {
      name: 'owner',
      relationTo: 'users'
    },
    // ... other fields
  ],
}