WebLog

NestJSでgoogle oauth認証を実装する

2022/12/10 21:39

準備

新しい nest プロジェクトを nest コマンドで作ってそこで作業します

1nest new nest-oauth

できたら、そこに移動して起動するかどうか試してみましょう

1cd nest-oauth
2npm run start:dev

http://localhost:3000 にアクセスして「Hello World!」と出れば準備 OK です

oauth2.0 クライアント ID を取得する

GCP のプロジェクトを作り、「認証情報」→「認証情報を作成」→「oauth クライアント ID」を選択し、以下の内容で作成します

:::message 承認済みの Javascript 生成元とは、oauth 認証フローを開始する(呼び出す)ところの URI です。 一方、承認済みのリダイレクト URI とは、oauth 認証が行われた後にリダイレクトされる URI です。これは、ここで設定するだけで、自動でリダイレクトされるわけではなく、アプリケーション側でここにリダイレクトするように設定します。その際、ここで指定した URI 以外にリダイレクトしようとするとエラーになります。 :::

必要なパッケージのインストール

passportという express で有名な認証ライブラリを使います。passport は色々な認証方式(strategy)に対応しています。実装したい認証方式に対応したライブラリをインストールすることで、その認証方式を簡単に実装することができます。今回は google oauth に対応したいので、それ用のライブラリをインストールします。

1npm i --save @nestjs/passport passport passport-google-oauth20 @nestjs/config dotenv
2npm i -D @types/passport-google-oauth20

nest cli コマンドで必要なファイルを生成

今回は google フォルダを作ってその中に google   oauth 関連のファイルを詰め込みたいと思います

1nest g res google # controllerとserviceとmoduleを作成

passport を使って認証部分を実装する

今回は passport を用いた google oauth に関する設定ファイルとしてgoogle.strategy.tsを以下のような内容で作成します。

google/google.strategy.ts
1import { Injectable } from '@nestjs/common';
2import { PassportStrategy } from '@nestjs/passport';
3import { config } from 'dotenv';
4import { Strategy, VerifyCallback } from 'passport-google-oauth20';
5
6config(); // .envファイルを使えるようにする
7
8@Injectable()
9export class GoogleStrategy extends PassportStrategy(Strategy, 'google') {
10 constructor() {
11 // Passportのstrategyに関する設定
12 super({
13 clientID: process.env.GOOGLE_CLIENT_ID,
14 clientSecret: process.env.GOOGLE_CLIENT_SECRET,
15 callbackURL: process.env.CALLBACK_URL,
16 scope: ['email', 'profile'],
17 });
18 }
19
20 async validate(
21 accessToken: string,
22 refreshToken: string,
23 profile: any,
24 done: VerifyCallback,
25 ): Promise<any> {
26 const { name, emails, photos } = profile;
27
28 const user = {
29 email: emails[0].value,
30 firstName: name.givenName,
31 lastName: name.familyName,
32 picture: photos[0].value,
33 accessToken,
34 };
35
36 done(null, user);
37 }
38}

.envファイルを作ります

1GOOGLE_CLIENT_ID= <your-client-id>
2GOOGLE_CLIENT_SECRET= <your-client-secret>
3CALLBACK_URL=http://localhost:3000/google/redirect

google.controller.tsで必要なルートを設定します。 AuthGuardを import して、ハンドラーを guard し、そこにリクエストが行くことで、google oatuh 認証フローが開始します。

google/google.controller.ts
1import { AuthGuard } from '@nestjs/passport';
2import { Controller, Get, Request, UseGuards } from '@nestjs/common';
3import { GoogleService } from './google.service';
4
5@Controller('google')
6export class GoogleController {
7 constructor(private readonly googleService: GoogleService) {}
8
9 // ここにリクエストがいくことでoauth認証フローのスタート
10 @Get()
11 @UseGuards(AuthGuard('google'))
12 async googleAuth(@Request() req) {}
13
14 // 認証フローが終了し、アクセストークンを取得したら、ここにリダイレクトされる
15 @Get('redirect')
16 @UseGuards(AuthGuard('google'))
17 googleAuthRedirect(@Request() req) {
18 // この時点でreq.userに上のほうで定義したvalidateで抜き出した認証情報が入っている(名前、メールアドレス、画像など)
19 // 具体的な処理はserviceにやらせる
20 return this.googleService.googleLogin(req);
21 }
22}

google.service.tsの中を書いていきます。

google/google.service.ts
1import { Injectable } from '@nestjs/common';
2
3@Injectable()
4export class GoogleService {
5 googleLogin(req) {
6 if (!req.user) {
7 return 'No user from google';
8 }
9
10 return {
11 message: 'User information from google',
12 user: req.user,
13 };
14 }
15}

最後に、DI のためにgoogle.module.tsをごにょごにょして、それをapp.module.tsで import すれば OK です。

google/google.module.ts
1import { Module } from '@nestjs/common';
2import { GoogleService } from './google.service';
3import { GoogleController } from './google.controller';
4import { GoogleStrategy } from './google.strategy';
5
6@Module({
7 controllers: [GoogleController],
8 providers: [GoogleService, GoogleStrategy],
9})
10export class GoogleModule {}
app.module.ts
1import { Module } from '@nestjs/common';
2import { AppController } from './app.controller';
3import { AppService } from './app.service';
4import { GoogleModule } from './google/google.module';
5
6@Module({
7 imports: [GoogleModule],
8 controllers: [AppController],
9 providers: [AppService],
10})
11export class AppModule {}

テスト

1npm run start:dev

この状態で、http://localhost:3000/google にアクセスして、google アカウントでログイン後、http://localhost:3000/google/redirect にリダイレクトされ、ユーザー情報が見れれば OK です。

参考

Implement Google OAuth in NestJS using Passport - DEV CommunityNavigation menuSearchSearchCloseMore...Copy linkEnter fullscreen modeExit fullscreen modeEnter fullscreen modeExit fullscreen modeEnter fullscreen modeExit fullscreen modeEnter fullscreen modeExit fullscreen modeEnter fullscreen modeExit fullscreen modeEnter fullscreen modeExit fullscreen modeEnter fullscreen modeExit fullscreen modeEnter fullscreen modeExit fullscreen modeEnter fullscreen modeExit fullscreen modeEnter fullscreen modeExit fullscreen modeEnter fullscreen modeExit fullscreen modeCollapseExpandDropdown menuLike comment: Like comment: Comment buttonCollapseExpandDropdown menuLike comment: Like comment: Comment buttonCollapseExpandDropdown menuLike comment: Like comment: Comment buttonCollapseExpandDropdown menuLike comment: Like comment: Comment buttonCollapseExpandDropdown menuLike comment: Like comment: Comment buttonCollapseExpandDropdown menuLike comment: Like comment: Comment buttonCollapseExpandDropdown menuLike comment: Like comment: Comment buttonCollapseExpandDropdown menuLike comment: Like comment: Comment buttonCollapseExpandDropdown menuLike comment: Like comment: ThreadDropdown menuLike comment: Like comment: ThreadDropdown menuLike comment: Like comment: ThreadDropdown menuLike comment: Like comment: ThreadDropdown menuLike comment: Like comment: ThreadDropdown menuLike comment: Like comment: Comment buttonCollapseExpandDropdown menuLike comment: Like comment: Comment buttonCollapseExpandDropdown menuLike comment: Like comment: Comment buttonCollapseExpandDropdown menuLike comment: Like comment: Comment buttonCollapseExpandDropdown menuLike comment: Like comment: Comment buttonCollapseExpandDropdown menuLike comment: Like comment: Comment buttonCollapseExpandDropdown menuLike comment: Like comment: Comment buttonCollapseExpandDropdown menuLike comment: Like comment: Comment buttonCollapseExpandDropdown menuLike comment: Like comment: Comment buttonCollapseExpandDropdown menuLike comment: Like comment: Comment buttonCollapseExpandDropdown menuLike comment: Like comment: Comment button
Implement Google OAuth in NestJS using Passport - DEV CommunityNavigation menuSearchSearchCloseMore...Copy linkEnter fullscreen modeExit fullscreen modeEnter fullscreen modeExit fullscreen modeEnter fullscreen modeExit fullscreen modeEnter fullscreen modeExit fullscreen modeEnter fullscreen modeExit fullscreen modeEnter fullscreen modeExit fullscreen modeEnter fullscreen modeExit fullscreen modeEnter fullscreen modeExit fullscreen modeEnter fullscreen modeExit fullscreen modeEnter fullscreen modeExit fullscreen modeEnter fullscreen modeExit fullscreen modeCollapseExpandDropdown menuLike comment: Like comment: Comment buttonCollapseExpandDropdown menuLike comment: Like comment: Comment buttonCollapseExpandDropdown menuLike comment: Like comment: Comment buttonCollapseExpandDropdown menuLike comment: Like comment: Comment buttonCollapseExpandDropdown menuLike comment: Like comment: Comment buttonCollapseExpandDropdown menuLike comment: Like comment: Comment buttonCollapseExpandDropdown menuLike comment: Like comment: Comment buttonCollapseExpandDropdown menuLike comment: Like comment: Comment buttonCollapseExpandDropdown menuLike comment: Like comment: ThreadDropdown menuLike comment: Like comment: ThreadDropdown menuLike comment: Like comment: ThreadDropdown menuLike comment: Like comment: ThreadDropdown menuLike comment: Like comment: ThreadDropdown menuLike comment: Like comment: Comment buttonCollapseExpandDropdown menuLike comment: Like comment: Comment buttonCollapseExpandDropdown menuLike comment: Like comment: Comment buttonCollapseExpandDropdown menuLike comment: Like comment: Comment buttonCollapseExpandDropdown menuLike comment: Like comment: Comment buttonCollapseExpandDropdown menuLike comment: Like comment: Comment buttonCollapseExpandDropdown menuLike comment: Like comment: Comment buttonCollapseExpandDropdown menuLike comment: Like comment: Comment buttonCollapseExpandDropdown menuLike comment: Like comment: Comment buttonCollapseExpandDropdown menuLike comment: Like comment: Comment buttonCollapseExpandDropdown menuLike comment: Like comment: Comment button

Implement Google OAuth in NestJS using Passport - DEV CommunityNavigation menuSearchSearchCloseMore...Copy linkEnter fullscreen modeExit fullscreen modeEnter fullscreen modeExit fullscreen modeEnter fullscreen modeExit fullscreen modeEnter fullscreen modeExit fullscreen modeEnter fullscreen modeExit fullscreen modeEnter fullscreen modeExit fullscreen modeEnter fullscreen modeExit fullscreen modeEnter fullscreen modeExit fullscreen modeEnter fullscreen modeExit fullscreen modeEnter fullscreen modeExit fullscreen modeEnter fullscreen modeExit fullscreen modeCollapseExpandDropdown menuLike comment: Like comment: Comment buttonCollapseExpandDropdown menuLike comment: Like comment: Comment buttonCollapseExpandDropdown menuLike comment: Like comment: Comment buttonCollapseExpandDropdown menuLike comment: Like comment: Comment buttonCollapseExpandDropdown menuLike comment: Like comment: Comment buttonCollapseExpandDropdown menuLike comment: Like comment: Comment buttonCollapseExpandDropdown menuLike comment: Like comment: Comment buttonCollapseExpandDropdown menuLike comment: Like comment: Comment buttonCollapseExpandDropdown menuLike comment: Like comment: ThreadDropdown menuLike comment: Like comment: ThreadDropdown menuLike comment: Like comment: ThreadDropdown menuLike comment: Like comment: ThreadDropdown menuLike comment: Like comment: ThreadDropdown menuLike comment: Like comment: Comment buttonCollapseExpandDropdown menuLike comment: Like comment: Comment buttonCollapseExpandDropdown menuLike comment: Like comment: Comment buttonCollapseExpandDropdown menuLike comment: Like comment: Comment buttonCollapseExpandDropdown menuLike comment: Like comment: Comment buttonCollapseExpandDropdown menuLike comment: Like comment: Comment buttonCollapseExpandDropdown menuLike comment: Like comment: Comment buttonCollapseExpandDropdown menuLike comment: Like comment: Comment buttonCollapseExpandDropdown menuLike comment: Like comment: Comment buttonCollapseExpandDropdown menuLike comment: Like comment: Comment buttonCollapseExpandDropdown menuLike comment: Like comment: Comment button

This article teaches you how to use Passport to implement Google OAuth in a [NestJS](https://docs.nestjs.com/) application. Tagged with webdev, javascript, node, nestjs.

Passport   - Node.jsのための、シンプルで使いどころを選ばない認証モジュール

Passport - Node.jsのための、シンプルで使いどころを選ばない認証モジュール

security-authentication|NestJS 公式ドキュメントver7日本語訳Zenn

security-authentication|NestJS 公式ドキュメントver7日本語訳Zenn

Documentation | NestJS - A progressive Node.js framework
Documentation | NestJS - A progressive Node.js framework

Documentation | NestJS - A progressive Node.js framework

Nest is a framework for building efficient, scalable Node.js server-side applications. It uses progressive JavaScript, is built with TypeScript and combines elements of OOP (Object Oriented Programming), FP (Functional Programming), and FRP (Functional Reactive Programming).

最新の投稿