9
11

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[Node.js]Passport.jsを用いたSNS認証(Google編)

9
Last updated at Posted at 2018-02-03

Google認証を利用したので、その時のメモです。
ある程度、Node.jsへの理解がある方向けの記事になります。

必要な前準備

  1. Google Cloud Console でプロジェクトを作成し、client id と client secret を発行する。

  2. https://console.cloud.google.com
    にアクセスして新規プロジェクトを作成し、[API とサービス] > [認証情報]をクリックする。

  3. プロジェクト名を入力後、認証情報を作成をクリックし、OAuthクライアントIDを選択する。

  4. サービス名を入力後、アプリケーションの種類からウェブアプリケーションを選択する。

  5. 承認済みのJavaScript生成元にhttp://localhost:8080
    、承認済みのリダイレクトURLにhttp://localhost:8080/auth/google/callback を入力する。

  6. 必要なモジュールをインストールする。
    npm install --save passport-google-oauth passport

3.Google+ API を有効にする
[API とサービス] > [API ライブラリ]をクリックし、Google+ APIを有効にする。

コードの実装

app.jsに下記のコードを追加してください。

app.js
const passport = require('passport');
const auth = require('./routes/auth');
app.use(passport.initialize());
// Routing
app.use('/auth', auth);
routes/auth.js
const express = require("express");
const passport = require('passport');
const GoogleStrategy = require('passport-google-oauth').OAuth2Strategy;

function extractProfile(profile) {
    let imageUrl = '';
    if (profile.photos && profile.photos.length) {
        imageUrl = profile.photos[0].value;
    }
    return {
        id: profile.id,
        displayName: profile.displayName,
        image: imageUrl,
    };
}

passport.use(new GoogleStrategy({
    clientID: "上記で取得したクライアント ID",
    clientSecret: "上記で取得したクライアントシークレット",
    callbackURL: '上記で設定したロールバック URL',
    accessType: 'offline',
}, function (accessToken, refreshToken, profile, done) {
    if (profile) {
        return done(null, profile);
    }
    else {
        return done(null, false);
    }
}));

const router = express.Router();

router.get('/login',
    passport.authenticate('google', { scope: ['email', 'profile'], session: false, }),
);

router.get('/google/callback', passport.authenticate('google'), (req, res) => {
    res.redirect("/");
});
module.exports = router;

[説明]
・ログイン URL を用意する

routes/auth.js
router.get('/login',
    passport.authenticate('google', { scope: ['email', 'profile'], session: false, }),
);

ここで用意された URL にアクセスすると、Google に認証を委譲します。
・コールバック URL を用意する

routes/auth.js
router.get('/google/callback', passport.authenticate('google'), (req, res) => {
    res.redirect("/");
});

Googleで認証されると、コールバック先として事前に登録しておいたhttp://localhost:8080/auth/google/callback リダイレクトされます。
上記の例だと、リダイレクトされた後に、http://localhost:8080/ にリダイレクトします。

セッションを有効にする場合

1.追加で、express-sessionをインストールする。
npm install --save express-session
2.app.jsに下記のコードを追加。

app.js
var session = require('express-session');

app.use(passport.session());

passport.serializeUser(function(user, done) {
    done(null, user);
});

passport.deserializeUser(function(user, done) {
    done(null, user);
});

動かしてみる

http://localhost:8080/auth/login にアクセスしてみてください。

9
11
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
11

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?