Passport.js のお勉強

イシュー

  • Passport.js を理解する

参考

authenticate

Authenticate

Authenticating requests is as simple as calling passport.authenticate() and specifying which strategy to employ. authenticate()'s function signature is standard Connect middleware, which makes it convenient to use as route middleware in Express applications.

リクエストを認証することは passport.authenticate()を呼び出びだすことと、使用するstrategy を指定することであり、簡潔です。 authenticate()の関数シグネチャは、標準の接続ミドルウェアであり、Expressアプリケーションのroute middlewareと同じ様に使えて便利です。

app.post('/login',
  passport.authenticate('local'),
  function(req, res) {
    // If this function gets called, authentication was successful.
    // `req.user` contains the authenticated user.
    res.redirect('/users/' + req.user.username);
  });

By default, if authentication fails, Passport will respond with a 401 Unauthorized status, and any additional route handlers will not be invoked. If authentication succeeds, the next handler will be invoked and the req.user property will be set to the authenticated user.

デフォルトでは、認証に失敗した場合、Passportは401(不正なステータス)で応答し、いくつかの後続ルートハンドラが呼び出されません。認証が成功すると、次のハンドラが呼び出され、req.user プロパティに認証されたユーザ情報が設定されます。

Note: Strategies must be configured prior to using them in a route. Continue reading the chapter on configuration for details.

Note: Strategies(の設定)は、route内でそれらを使用する前に設定する必要があります。詳細については、設定に関する章を読んでください。

Redirects

A redirect is commonly issued after authenticating a request.

リダイレクトは、一般的に要求を認証した後に発行されます。

app.post('/login',
  passport.authenticate('local', { successRedirect: '/',
                                   failureRedirect: '/login' }));

In this case, the redirect options override the default behavior. Upon successful authentication, the user will be redirected to the home page. If authentication fails, the user will be redirected back to the login page for another attempt.

この場合、リダイレクトのオプションはデフォルトの動作をオーバーライドします。認証に成功すると、ユーザーはホームページ(/)にリダイレクトされます。 認証に失敗した場合、ユーザーはさらに試みるためにログインページ(/login)へリダイレクトされます。

Flash Messages

Redirects are often combined with flash messages in order to display status information to the user.

リダイレクトは、多くの場合、ユーザにステータス情報を表示するためにフラッシュメッセージと組み合わされます。

app.post('/login',
  passport.authenticate('local', { successRedirect: '/',
                                   failureRedirect: '/login',
                                   failureFlash: true })
);

Setting the failureFlash option to true instructs Passport to flash an error message using the message given by the strategy's verify callback, if any. This is often the best approach, because the verify callback can make the most accurate determination of why authentication failed.

failureFlashオプションをtrueに設定すると、Passportは、strategy の検証によるコールバックによって与えられたメッセージを使用してエラーメッセージをフラッシュするように指示します。

検証によるコールバックは、認証が失敗した理由の最も正確な判定を行うことができるので、これは、多くの場合、最良のアプローチです。

Alternatively, the flash message can be set specifically.

もしくは、フラッシュメッセージを明示的に設定することができます。

passport.authenticate('local', { failureFlash: 'Invalid username or password.' });

A successFlash option is available which flashes a success message when authentication succeeds.

successFlashオプションは、認証が成功したときに成功メッセージをフラッシュすることができます。

passport.authenticate('local', { successFlash: 'Welcome!' });

Note: Using flash messages requires a req.flash() function. Express 2.x provided this functionality, however it was removed from Express 3.x. Use of connect-flash middleware is recommended to provide this functionality when using Express 3.x.

注:フラッシュ·メッセージを使用するには、req.flash()関数が必要です。この機能はExpress2.xで提供されていましたが、Express3.xからは削除されました。 Expressの3.xを使用する場合には、connect-flash middleware を使用することをお勧めします

Disable Sessions

After successful authentication, Passport will establish a persistent login session. This is useful for the common scenario of users accessing a web application via a browser. However, in some cases, session support is not necessary. For example, API servers typically require credentials to be supplied with each request. When this is the case, session support can be safely disabled by setting the session option to false.

認証が成功すると、Passport は、永続的なログインセッションを確立します。これは、ユーザがブラウザを経由してWebアプリケーションにアクセスする一般的なシナリオで有効です。 しかし、場合によっては、セッションのサポートは不要となります。例えば、APIサーバーは通常、それぞれのリクエストで認証を必要とします。この場合には、セッションオプションをfalseに設定することにより、セッションサポートを安全に無効化できます。

app.get('/api/users/me',
  passport.authenticate('basic', { session: false }),
  function(req, res) {
    res.json({ id: req.user.id, username: req.user.username });
  });

Custom Callback

If the built-in options are not sufficient for handling an authentication request, a custom callback can be provided to allow the application to handle success or failure.

ビルトインのオプションが認証要求を処理するのに十分でない場合、アプリケーションが成功または失敗を処理できるように、カスタムのコールバックを提供できます。

app.get('/login', function(req, res, next) {
  passport.authenticate('local', function(err, user, info) {
    if (err) { return next(err); }
    if (!user) { return res.redirect('/login'); }
    req.logIn(user, function(err) {
      if (err) { return next(err); }
      return res.redirect('/users/' + user.username);
    });
  })(req, res, next);
});

In this example, note that authenticate() is called from within the route handler, rather than being used as route middleware. This gives the callback access to the req and res objects through closure.

この例では、authenticate() ルートミドルウェアとして使用されているよりも、むしろルートハンドラ内から認証が呼び出されることに注意してください。これはクロージャを通して req および res オブジェクトへのコールバックのアクセスを提供します。

If authentication failed, user will be set to false. If an exception occurred, err will be set. An optional info argument will be passed, containing additional details provided by the strategy's verify callback.

認証が失敗した場合、user(オブジェクト) はfalseに設定されます。例外が発生した場合は、err が 設定されます。オプションの info 引数が渡されます。それはstrategy の検証するコールバックによって提供される追加の詳細情報を含みます。

The callback can use the arguments supplied to handle the authentication result as desired. Note that when using a custom callback, it becomes the application's responsibility to establish a session (by calling req.login()) and send a response.

コールバックは、必要に応じて認証結果を処理するために指定された引数を使用することができます。カスタムコールバックを使用している場合は、(req.login()メソッドを呼び出して)セッションを確立し、応答を返すのは、アプリケーションの責任範囲になることに注意してください。