跳到主内容

在 Nuxt 应用中实现用户登录

本指南介绍如何为 Nuxt 应用添加 Casdoor 登录功能,以及如何防止未登录用户访问受保护的路由。步骤与 Next.js 指南 类似。


学习目标​

  • 在 Nuxt 应用中初始化 casdoor-js-sdk。
  • 将用户重定向到 Casdoor 登录页面并处理回调。
  • 使用 Nuxt 中间件保护路由。

前提条件​

示例代码​


配置 SDK​

  1. 安装 casdoor-js-sdk:

    npm install casdoor-js-sdk
    # or: yarn add casdoor-js-sdk
  2. 定义 SDK 的配置。所有设置均为字符串且为必填项。

    ParameterRequiredDescription
    serverUrlYesCasdoor server URL (e.g. http://localhost:8000).
    clientIdYesApplication client ID.
    clientSecretYesApplication client secret.
    organizationNameYesOrganization name.
    appNameYesApplication name.
    redirectPathYesCallback path (e.g. /callback).
    const sdkConfig = {
    serverUrl: "https://door.casdoor.com",
    clientId: "294b09fbc17f95daf2fe",
    clientSecret: "dd8982f7046ccba1bbd7851d5c1ece4e52bf039d",
    organizationName: "casbin",
    appName: "app-vue-python-example",
    redirectPath: "/callback",
    };

    将 serverUrl、clientId 和 clientSecret 替换为您自己的 Casdoor 实例和应用的值。

  3. 在 Casdoor 管理控制台中,将您的应用的回调 URL(例如 http://localhost:8080/callback)添加到该应用的 Redirect URLs 中。

用户登录​

  1. 将用户发送到 Casdoor 登录页面:

    const CasdoorSDK = new Sdk(sdkConfig);
    CasdoorSDK.signin_redirect();
  2. 用户登录后,Casdoor 会携带授权码重定向到 redirectPath。在该页面上,用授权码交换访问令牌,读取用户信息,并将用户信息存储在 cookie 中:

    CasdoorSDK.exchangeForAccessToken()
    .then((res) => {
    if (res && res.access_token) {
    return CasdoorSDK.getUserInfo(res.access_token);
    }
    })
    .then((res) => {
    Cookies.set("casdoorUser", JSON.stringify(res));
    });

有关 SDK 的其他功能,请参阅 使用 Casdoor SDK 让用户登录。

使用中间件保护路由​

Nuxt 中间件 在路由渲染前运行,并可执行重定向操作。

  1. 在middleware目录中创建一个.js或.ts文件。 The file name is the name of the middleware: myMiddleware.js defines myMiddleware.

    const protectedRoutes = ["/profile"];

    export default function ({ route, redirect }) {
    if (protectedRoutes.includes(route.path)) {
    redirect('/login');
    }
    }
  2. 在 nuxt.config.js 中启用中间件:

    export default {
    router: {
    middleware: ['myMiddleware'] // your middleware name
    },
    }
  3. 在中间件中,将包含 casdoorUser cookie 的请求视为已登录,并将其他所有请求从受保护的路由重定向开:

    import Cookies from "js-cookie";

    const protectedRoutes = ["/profile"];

    export default function ({ route, redirect }) {
    const casdoorUserCookie = Cookies.get('casdoorUser');
    const isAuthenticated = !!casdoorUserCookie;

    if (!isAuthenticated && protectedRoutes.includes(route.path)) {
    redirect('/login');
    }
    }

另请参阅​