页面鉴权

本模块有一些默认的鉴权行为,可以通过配置修改默认的鉴权行为。

默认行为

模块具有以下默认的鉴权行为:

🤔 下方流程图中的内容较多,看完一定有一些疑惑,但请别担心,你只需要先了解模块的大致工作流程即可,通过后面的介绍你将明白这一切。

配置全局鉴权

在上面的流程图当中,我们注意到有调用 XXX 钩子的逻辑,这些逻辑默认没有被实现,但可以通过实现 Hook 的方式来实现,方式如下:

export default defineNuxtPlugin({
  // 必须配置此项
  enforce: "pre",
  hooks: {
    /**
     * 前置认证钩子
     * @param options 选项
     * @param result 跳转 | null
     * @description 返回值为 null 时继续路由守卫
     * @description 返回值为 undefined 时终止路由守卫
     * @description 注意:不写返回值时默认返回 undefined
     */
    "fast-auth:before-auth": (options, result) => {},
    /**
     * 无需认证
     * @param options 选项
     * @param result 跳转 | null
     * @description 返回值为 null 时继续路由守卫
     * @description 返回值为 undefined 时终止路由守卫
     * @description 注意:不写返回值时默认返回 undefined
     */
    "fast-auth:auth-through": (options, result) => {},
    /**
     * 需要认证但未登录
     * @param options 选项
     * @param result 跳转 | null
     * @description 返回值为 null 时继续路由守卫
     * @description 返回值为 undefined 时终止路由守卫
     * @description 注意:不写返回值时默认返回 undefined
     */
    "fast-auth:auth-anonymous": (options, result) => {},
    /**
     * 需要鉴权且已通过
     * @param options 选项
     * @param result 跳转 | null
     * @description 返回值为 null 时继续路由守卫
     * @description 返回值为 undefined 时终止路由守卫
     * @description 注意:不写返回值时默认返回 undefined
     */
    "fast-auth:auth-passed": (options, result) => {},
    /**
     * 需要鉴权但未通过
     * @param options 选项
     * @param result 跳转 | null
     * @description 返回值为 null 时继续路由守卫
     * @description 返回值为 undefined 时终止路由守卫
     * @description 注意:不写返回值时默认返回 undefined
     */
    "fast-auth:auth-failed": (options, result) => {},
    /**
     * 后置认证钩子
     * @param options 选项
     * @param result 跳转 | null
     * @description 返回值为 null 时继续路由守卫
     * @description 返回值为 undefined 时终止路由守卫
     * @description 注意:不写返回值时默认返回 undefined
     */
    "fast-auth:after-auth": (options, result) => {},
  },
});

配置页面鉴权

在上面的流程图当中,我们注意到有以下几个判断 页面是否需要鉴权页面是否已配置重定向匿名用户页面是否已配置重定向有权用户页面是否已配置重定向无权用户,这些判断的依据来源于以下页面配置:

definePageMeta({
  auth: {
    /**
     * 需要的权限
     * @default false
     */
    auth: [
      "|",
      {
        type: "role",
        value: "admin",
      },
      {
        type: "per",
        value: "users:view",
      },
      // per 的简写
      "users:add",
    ],
    /**
     * 重定向配置
     */
    redirect: {
      /**
       * 未登录重定向
       * @description 未登录重定向
       * @default true
       */
      anonymous: "/auth",
      /**
       * 鉴权通过重定向
       * @description 鉴权通过重定向
       * @default false
       */
      passed: "/admin",
      /**
       * 鉴权失败重定向
       * @description 鉴权失败重定向
       * @default true
       */
      failed: "/auth",
    },
  },
});