5
4

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.

NodeJSバックエンドでユーザー認証を扱う

Last updated at Posted at 2019-06-27

NodeJSバックエンドでユーザー認証を扱うのに使いそうなモジュール。

パスワードをハッシュ化する

パッケージ:

yarn add bcrypt
yarn add --dev @types/bcrypt

想定される状況

  • クライアント側から送られてきたパスワードをハッシュ化してデータベースに格納する。
  • データベースに格納されたハッシュ化したパスワードと認証のために送られてきたパスワードを比較する。
...
import bcrypt from 'bcrypt';
...
action: async (request: Request, response: Response) => {
    const saltRounds: number = 10;

    const hashedPassword: string = await bcrypt.hash(request.body.password, saltRounds);
    const result: boolean = await bcrypt.compare(request.body.password, hashedPassword);
    const result2: boolean = await bcrypt.compare('wrong_password', hashedPassword);

    console.log(hashedPassword); // --> ハッシュ化されたパスワード
    console.log(result); // --> TRUE 
    console.log(result2); // --> FALSE
...
5
4
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
5
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?