首页 > 解决方案 > Nuxt Auth:检查路由是否受保护?

问题描述

使用Nuxt-Auth,是否有官方方法可以检查路由是否受保护(即需要登录)?

在一些示例中间件中,执行“路由”的控制台日志会显示一个大型 JSON 有效负载,其中提到了middleware: 'auth'. 但是,这种方法有多可靠?如果 JSON 结构将来发生变化怎么办?

export default function({ $auth, route }) {

    // This returns 'auth' for protected routes; undefined for unprotected routes.
    // But how reliable is this method? The JSON structure could change in the future.
    console.log(route.matched[0].components.default.options.middleware)

}

标签: nuxt.jsnuxt-auth

解决方案


我找到了适合我的解决方案。也许它会帮助你。auth-next/runtime.js 文件中有一个函数。我已将其复制到我的文件中

function routeOption(route, key, value) {
  return route.matched.some((m) => {
    if (process.client) {
      return Object.values(m.components).some((component) => component.options && component.options[key] === value)
    } else {
      return Object.values(m.components).some((component) => Object.values(component._Ctor).some((ctor) => ctor.options && ctor.options[key] === value))
    }
  })
}

然后你可以这样使用它:

console.log('Auth not required: ', routeOption(ctx.route, 'auth', false))


推荐阅读