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
...