メインコンテンツにスキップ

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 にリダイレクトします。そのページで、コードをアクセストークンと交換し、ユーザー情報を読み取り、クッキーに保存します:

    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 ファイルを作成します。ファイル名がミドルウェアの名前になります。例えば、myMiddleware.js は 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 クッキーを持つリクエストをサインイン済みとして扱い、その他のすべてのリクエストを保護されたルートからリダイレクトします:

    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');
    }
    }

関連項目​