ホームページ > ウェブフロントエンド > jsチュートリアル > node.jsアプリケーションのパスポート認証

node.jsアプリケーションのパスポート認証

William Shakespeare
リリース: 2025-02-15 09:39:12
オリジナル
408 人が閲覧しました

Passport Authentication for Node.js Applications

このチュートリアルは、人気のある認証ミドルウェアであるPassport.jsを使用して、node.js WebアプリケーションでFacebookとGitHub認証を示しています。 パスポートは、OAuthとOpenID Connect Integrationを簡素化します

重要な概念:

    passport.js:
  • a node.jsさまざまなプロバイダー(Facebook、github、Googleなど)との認証を合理化するミドルウェア。 express.js:
  • node.jsのWebアプリケーションフレームワークは、アプリケーションの構造を構築してルーティングを処理するために使用されます。
  • oauth 2.0:FacebookとGithubが使用する承認フレームワーク。
  • 戦略:パスポートは、各プロバイダーに戦略を使用します(例:
  • )。
  • アプリケーションのセットアップ:passport-facebookpassport-github

プロジェクトの初期化:プロジェクトディレクトリを作成し、node.jsプロジェクトを初期化します:

  1. htmlセットアップ:

    プロジェクトルート:
    mkdir AuthApp
    cd AuthApp
    npm init -y
    ログイン後にコピー
  2. を作成します
  3. auth.html依存関係をインストール:

    expressとパスポートをインストール:
    <!DOCTYPE html>
    <html>
    <head>
      <title>Node.js OAuth</title>
    </head>
    <body>
      <a href="https://www.php.cn/link/cc1d70ad9d0ce820738dc9ffc4053a76">Sign in with Facebook</a><br><br>
      <a href="https://www.php.cn/link/899a13400527fd3b12105ec17a67dbac">Sign in with GitHub</a>
    </body>
    </html>
    ログイン後にコピー
  4. Express App:

    Create
    npm install express passport --save
    ログイン後にコピー
  5. アプリ()を実行し、HTMLを表示しますを確認します。アプリを停止します(index.js)。

    const express = require('express');
    const app = express();
    const port = process.env.PORT || 3000;
    
    app.get('/', (req, res) => res.sendFile('auth.html', { root: __dirname }));
    app.listen(port, () => console.log(`App listening on port ${port}`));
    ログイン後にコピー

    node index.jshttp://localhost:3000パスポート構成:Ctrl C

プロバイダー戦略のインストール:FacebookとGitHubの戦略をインストール:

  1. パスポートのセットアップ

    npm install passport-facebook passport-github --save
    ログイン後にコピー
  2. index.jsfacebook認証:

    const passport = require('passport');
    app.use(passport.initialize());
    app.use(passport.session());
    
    app.get('/success', (req, res) => res.send("Successfully logged in!"));
    app.get('/error', (req, res) => res.send("Error logging in."));
    
    passport.serializeUser((user, done) => done(null, user));
    passport.deserializeUser((user, done) => done(null, user));
    ログイン後にコピー

Facebookアプリを作成する:Facebookの指示に従って、新しいアプリを作成し、

  1. Facebook戦略の構成App IDApp Secret

  2. Facebookアプリの有効なOAUTHリダイレクトURIを

    index.js

    github認証:
    const FacebookStrategy = require('passport-facebook').Strategy;
    const FACEBOOK_APP_ID = 'YOUR_FACEBOOK_APP_ID'; // Replace with your App ID
    const FACEBOOK_APP_SECRET = 'YOUR_FACEBOOK_APP_SECRET'; // Replace with your App Secret
    
    passport.use(new FacebookStrategy({
        clientID: FACEBOOK_APP_ID,
        clientSecret: FACEBOOK_APP_SECRET,
        callbackURL: "https://www.php.cn/link/cc1d70ad9d0ce820738dc9ffc4053a76/callback",
        profileFields: ['id', 'displayName', 'photos', 'email'] //Optional: Specify fields to retrieve
    }, (accessToken, refreshToken, profile, done) => {
        done(null, profile);
    }));
    
    app.get('https://www.php.cn/link/cc1d70ad9d0ce820738dc9ffc4053a76', passport.authenticate('facebook'));
    app.get('https://www.php.cn/link/cc1d70ad9d0ce820738dc9ffc4053a76/callback',
        passport.authenticate('facebook', { failureRedirect: '/error' }),
        (req, res) => res.redirect('/success')
    );
    ログイン後にコピー

    http://localhost:3000https://www.php.cn/link/cc1d70ad9d0ce820738dc9ffc4053a76/callback

githubアプリを作成する:

新しいgithubアプリを作成して、

を取得します
  1. Client IDClient Secretでgithub戦略を構成します

  2. githubアプリの承認コールバックURLを
  3. に設定します index.js

    アプリケーションを実行します:
    const GitHubStrategy = require('passport-github').Strategy;
    const GITHUB_CLIENT_ID = 'YOUR_GITHUB_CLIENT_ID'; // Replace with your Client ID
    const GITHUB_CLIENT_SECRET = 'YOUR_GITHUB_CLIENT_SECRET'; // Replace with your Client Secret
    
    passport.use(new GitHubStrategy({
        clientID: GITHUB_CLIENT_ID,
        clientSecret: GITHUB_CLIENT_SECRET,
        callbackURL: "https://www.php.cn/link/899a13400527fd3b12105ec17a67dbac/callback"
    }, (accessToken, refreshToken, profile, done) => {
        done(null, profile);
    }));
    
    app.get('https://www.php.cn/link/899a13400527fd3b12105ec17a67dbac', passport.authenticate('github'));
    app.get('https://www.php.cn/link/899a13400527fd3b12105ec17a67dbac/callback',
        passport.authenticate('github', { failureRedirect: '/error' }),
        (req, res) => res.redirect('/success')
    );
    ログイン後にコピー

    サーバー()を起動し、FacebookおよびGitHubログインリンクをテストします。 node index.jsルートは、認証の成功を示します。 プレースホルダーIDと秘密を実際の値に置き換えることを忘れないでください。 これは、基本的なフレームワークを提供します。 生産対応のアプリケーションには、データベースでのエラー処理とユーザーの永続性が必要です。

以上がnode.jsアプリケーションのパスポート認証の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
著者別の最新記事
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート