[]
        
(Showing Draft Content)

ユーザー認証と権限

このトピックでは、js-collaboration で ユーザー認証 と メッセージ権限検証 を実装する方法を説明します。ユーザーの識別情報は ミドルウェア を使用して検証し、メッセージを受信した際に権限をチェックして、オペレーションを許可するかどうかを判定します。

サマリー

js-collaboration は、トークン検証による認証と、メッセージ単位の権限制御を実装します。これにより、次を実現します。

  • 認証済みのクライアントのみがサーバーとの接続を確立します。

  • メッセージ処理の権限はポリシーに基づいて適用されます。

主なポイント:

  • 認証: トークンによってユーザーの識別情報を検証し、クライアントが正当なユーザーであることを確認します。

  • 権限検証: ユーザー情報を保存および取得することで、メッセージの権限制御を実現します。

この例のトークン検証と権限検証は、デモ目的のみです。実運用のアプリケーションでは、業務要件に基づいて、より安全で複雑な検証メカニズムの実装をご検討ください。

ワークフロー

クライアント

  1. ユーザーがログインしてトークンを取得します。

  2. クライアントは client.connect() を通じて、トークンを auth パラメータとしてサーバーに渡します。

  3. サーバーはトークンを受け取り、検証を行います。認証に成功した場合、クライアントはサーバーとの接続を確立します。認証に失敗した場合は、認証失敗のメッセージが返されます。

サーバー

  1. サーバーは server.use のミドルウェアを通じて、クライアントが渡したトークンを取得して検証します。

  2. 認証に成功した場合、サーバーはユーザー情報を connection.tags に保存し、クライアントが後続の操作(例: メッセージ送信)を実行できるようにします。

  3. 認証に失敗した場合、サーバーはエラーメッセージを返し、クライアントはそのメッセージを受信します。

クライアント側: 認証情報の送信

フロントエンドでは、接続確立時にトークンを auth パラメータとしてサーバーに渡す必要があります。以下は、クライアント側で認証情報を送信する例です。

フロントエンドは client.connect() メソッドを使用して、認証用のトークンをサーバーに渡します。

import { Client } from '@mescius/js-collaboration-client';

// ログインのシミュレーション
async function login(username, password) {
    const response = await fetch('http://localhost:8080/login', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({ username, password })
    });
    const result = await response.json();
    if (result.success) {
        return result.token;
    } else {
        throw new Error(result.message);
    }
}

// トークンの取得
const userToken = await login('reader1', 'read123');

// クライアントインスタンスを作成してルームに接続
const client = new Client('ws://localhost:8080');
const connection = client.connect('room123', {
    auth: {
        token: userToken
    }
});

コードの説明

  • クライアントは、認証のために userToken を auth パラメータとしてサーバーに渡します。

  • サーバーはミドルウェアでトークンを検証し、検証結果に基づいて接続を許可または拒否します。

サーバー側: 認証とメッセージ権限

サーバー側では、ミドルウェアを使用してクライアントから渡されたトークンを検証し、検証済みのユーザー情報に基づいて関連するオペレーションを実行します。

  • connect ミドルウェアでは、クライアントから渡されたトークンを取得して検証し、ユーザー情報を connection.tags に保存します。

  • message ミドルウェアでは、connection.tags からユーザー情報を取得し、権限チェックを行います。

import express from 'express';
import { createServer } from 'http';
import { Server } from '@mescius/js-collaboration';
import jwt from 'jsonwebtoken';

const app = express();
const httpServer = createServer(app);
const server = new Server({ httpServer });

app.use(express.json());

// JWT の秘密鍵
const JWT_SECRET = 'your-secret-key-here';

// ユーザーデータベースのシミュレーション
const users = new Map([
    ['admin1', { username: 'admin1', password: 'admin123', role: 'admin' }],
    ['reader1', { username: 'reader1', password: 'reader123', role: 'reader' }],
    ['editor1', { username: 'editor1', password: 'editor123', role: 'editor' }]
]);

// ログインルート
app.post('/login', (req, res) => {
    const { username, password } = req.body;

    const user = users.get(username);
    if (!user || user.password !== password) {
        return res.status(401).json({
            success: false,
            message: 'Invalid username or password'
        });
    }

    const token = jwt.sign(
        { username: user.username, role: user.role },
        JWT_SECRET
    );

    res.json({
        success: true,
        token,
        user: { username: user.username, role: user.role }
    });
});

server.use('connect', async (context, next) => {
    const token = context.connection.auth?.token;

    if (!token) {
        await next('No token provided');
        return;
    }

    try {
        const decoded = jwt.verify(token, JWT_SECRET);
        const user = {
            username: decoded.username,
            role: decoded.role
        };
        context.connection.tags.set('user', user);
        console.log(`User authenticated: ${user.username} (${user.role})`);
        await next();
    } catch {
        await next('Invalid token');
    }
});

server.use('message', async ({ connection }, next) => {
    const user = connection.tags.get('user');
    if (user.role === 'admin' || user.role === 'editor') {
        await next();
    } else {
        await next('no edit permission');
    }
});

// サーバーの起動
httpServer.listen(8080);

コードの説明

  • 認証検証: connect ミドルウェアでは、クライアントから渡されたトークンを context.connection.auth?.token から取得して検証します。検証に成功した場合、ユーザー情報を取得して connection.tags に保存します。

  • 権限検証: message ミドルウェアでは、保存済みのユーザー情報を context.connection.tags.get('user') から取得し、ユーザーのロールに基づいてメッセージ権限検証を行います。