「労働者が自分の仕事をうまくやりたいなら、まず自分の道具を研ぎ澄まさなければなりません。」 - 孔子、「論語。陸霊公」
表紙 > プログラミング > Express JS と React JS unsing jwt による認証

Express JS と React JS unsing jwt による認証

2024 年 11 月 1 日に公開
ブラウズ:833

Authentication with express js and react js unsing jwt

フロントエンドで React.js、バックエンドで Express.js を使用して認証システムを作成するには、以下を実装する必要があります。

  • フロントエンド (Pulsy を使用した React.js): ログインとログアウトを処理し、ユーザー認証状態を維持し、トークンを永続化します。
  • バックエンド (Express.js): 認証エンドポイントを提供します (ログイン、ログアウト、ユーザー検証など)。

ステップ 1: バックエンド (Express.js) のセットアップ

ユーザー認証とトークン生成を処理するバックエンドから始めましょう。

必要なパッケージをインストールする


npm install express bcryptjs jsonwebtoken cors


バックエンド コード (Express.js)

認証ロジックを処理するための authController.js ファイルを作成します:


// authController.js
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');

// Mock user data (in production, you would use a real database)
const users = [
  {
    id: 1,
    username: 'john',
    password: '$2a$10$O1s8iLKRLPbPqhc1uTquLO.xODTC1U/Z8xGoEDU6/Dc0PAQ3MkCKy', // hashed password for 'password123'
  },
];

// JWT Secret
const JWT_SECRET = 'supersecretkey';

exports.login = (req, res) => {
  const { username, password } = req.body;

  const user = users.find((u) => u.username === username);

  if (!user) {
    return res.status(401).json({ error: 'Invalid credentials' });
  }

  bcrypt.compare(password, user.password, (err, isMatch) => {
    if (isMatch) {
      // Create a token
      const token = jwt.sign({ id: user.id, username: user.username }, JWT_SECRET, { expiresIn: '1h' });
      return res.json({ token });
    } else {
      return res.status(401).json({ error: 'Invalid credentials' });
    }
  });
};

exports.validateToken = (req, res) => {
  const token = req.header('Authorization').replace('Bearer ', '');

  if (!token) {
    return res.status(401).json({ error: 'No token provided' });
  }

  try {
    const decoded = jwt.verify(token, JWT_SECRET);
    res.json({ user: { id: decoded.id, username: decoded.username } });
  } catch (err) {
    res.status(401).json({ error: 'Invalid token' });
  }
};


次に、Express をセットアップするためのメインの server.js ファイルを作成します:


// server.js
const express = require('express');
const cors = require('cors');
const { login, validateToken } = require('./authController');

const app = express();
app.use(express.json());
app.use(cors());

// Authentication routes
app.post('/api/login', login);
app.get('/api/validate', validateToken);

// Start the server
const PORT = 5000;
app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
});


  • POST /api/login: ユーザーを認証し、JWT トークンを返します。
  • GET /api/validate: トークンを検証し、ユーザー情報を返します。

ステップ 2: フロントエンド (Pulsy を使用した React.js)

次に、React.jsPulsy を使用して、認証状態を処理するフロントエンドをセットアップしましょう。

必要なパッケージをインストールする


npm install axios pulsy


Pulsy ストアのセットアップ

認証状態をグローバルに管理するための Pulsy ストアを作成します。


// authStore.js
import { createStore, addMiddleware } from 'pulsy';
import axios from 'axios';

// Create a store to hold the user and token
createStore('auth', {
  user: null,
  token: null,
}, { persist: true }); // Persist the auth state in localStorage

// Middleware to add Authorization header for authenticated requests
addMiddleware('auth', (nextValue, prevValue, storeName) => {
  if (nextValue.token) {
    axios.defaults.headers.common['Authorization'] = `Bearer ${nextValue.token}`;
  } else {
    delete axios.defaults.headers.common['Authorization'];
  }
  return nextValue;
});


このストアは認証状態 (ユーザーとトークン) を保持し、認証されたリクエストに対して Authorization ヘッダーを自動的に適用します。

認証機能

ログインおよび検証リクエストを処理するヘルパー関数を作成します:


// authService.js
import { setStoreValue } from 'pulsy';
import axios from 'axios';

const API_URL = 'http://localhost:5000/api';

export const login = async (username, password) => {
  try {
    const response = await axios.post(`${API_URL}/login`, { username, password });
    const { token } = response.data;

    // Set token and user info in Pulsy store
    setStoreValue('auth', { token, user: { username } });

    return true;
  } catch (error) {
    console.error('Login failed', error);
    return false;
  }
};

export const validateToken = async () => {
  try {
    const response = await axios.get(`${API_URL}/validate`);
    const user = response.data.user;

    // Update the store with the user info
    setStoreValue('auth', { user, token: localStorage.getItem('auth_token') });
    return true;
  } catch (error) {
    console.error('Token validation failed', error);
    return false;
  }
};

export const logout = () => {
  setStoreValue('auth', { user: null, token: null });
  localStorage.removeItem('pulsy_auth');
};


ステップ 3: 認証コンポーネントを作成する

次に、ログイン ビューと認証されたビュー用の React コンポーネントを作成しましょう。

ログインコンポーネント


// Login.js
import React, { useState } from 'react';
import { login } from './authService';

const Login = () => {
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const [error, setError] = useState('');

  const handleLogin = async (e) => {
    e.preventDefault();
    const success = await login(username, password);
    if (!success) {
      setError('Invalid credentials. Try again.');
    }
  };

  return (
    

Login

setUsername(e.target.value)} placeholder="Username" required /> setPassword(e.target.value)} placeholder="Password" required />
{error &&

{error}

}
); }; export default Login;

認証されたコンポーネント


// Dashboard.js
import React from 'react';
import { usePulsy } from 'pulsy';
import { logout } from './authService';

const Dashboard = () => {
  const [auth] = usePulsy('auth');

  const handleLogout = () => {
    logout();
    window.location.reload(); // Simple page refresh to redirect to login
  };

  return (
    

Welcome, {auth.user.username}!

); }; export default Dashboard;

ステップ 4: アプリコンポーネント

App.js コンポーネントでは、ユーザーが認証されているかどうかを確認し、条件付きでログインまたはダッシュボードをレンダリングする必要があります。


// App.js
import React, { useEffect } from 'react';
import { usePulsy } from 'pulsy';
import { validateToken } from './authService';
import Login from './Login';
import Dashboard from './Dashboard';

function App() {
  const [auth] = usePulsy('auth');

  useEffect(() => {
    // Check token validity on app load
    if (auth.token) {
      validateToken();
    }
  }, [auth.token]);

  return (
    
{auth.user ? : }
); } export default App;

ステップ 5: アプリケーションを実行する

バックエンドフロントエンドの両方が設定されたので、アプリケーションを実行できます。

  1. Express サーバーを起動します:

   node server.js


  1. React フロントエンドを開始します:

   npm start


両方が実行されたら:

  • http://localhost:3000 にアクセスすると、ログイン ページが表示されます。
  • ログイン後、認証トークンが保存され、ダッシュボードにリダイレクトされます。
  • トークンが有効な場合はログインしたままになります。トークンが有効でない場合は、ログイン ページにリダイレクトされます。

まとめ

この例では、Pulsy を Express.js API を利用した React 認証システムと統合する方法を示します。 Pulsy は、セッション間での認証トークンとユーザー データの永続化など、認証のグローバル状態の管理に役立ち、強力で使いやすい状態管理ツールになります。

リリースステートメント この記事は次の場所に転載されています: https://dev.to/ng_dream_3e53e6a868268e4d/authentication-with-express-js-and-react-js-unsing-jwt-4nbp?1 侵害がある場合は、[email protected] までご連絡ください。それを削除するには
最新のチュートリアル もっと>

免責事項: 提供されるすべてのリソースの一部はインターネットからのものです。お客様の著作権またはその他の権利および利益の侵害がある場合は、詳細な理由を説明し、著作権または権利および利益の証拠を提出して、電子メール [email protected] に送信してください。 できるだけ早く対応させていただきます。

Copyright© 2022 湘ICP备2022001581号-3