nodejs mysql ER_NOT_SUPPORTED_AUTH_MODE

1. 問題描述

本地使用docker-compose啓動了一個mysql服務, 默認使用image tag 是latest, yaml文件以下:html

## 本地開發所需資源文件
version: '3'
services:
  ### mysql (https://hub.docker.com/_/mysql/)
  db_mysql:
    container_name: mysql
    environment:
      MYSQL_ROOT_PASSWORD: 1qaz
      TZ: Asia/Shanghai
    image: mysql
    ports:
      - 3306:3306
    restart: always

nodejs 程序使用typeorm和以下配置連接本地mysql:node

DB_TYPE=mysql
DB_HOST=localhost
DB_PORT=3306
DB_USERNAME=root
DB_PASSWORD=1qaz
DB_DATABASE=test
DB_SYNC=true

啓動程序報告錯誤:mysql

{ Error: ER_NOT_SUPPORTED_AUTH_MODE: Client does not support authentication protocol requested by server; consider upgrading MySQL client
    at Handshake.Sequence._packetToError (/usr/src/app/node_modules/mysql/lib/protocol/sequences/Sequence.js:52:14)
... ...

問題定義: mysql client 連接 mysql server 出現權限驗證方面錯誤git

2. 問題調查

根本緣由: mysql的client驅動當前僅支持 mysql_native_password/mysql_old_password 鑑權模式, 而5.7後默認的鑑權模式是: plugin, mysql提供兩個插件:安全

  • sha256_password: Implements basic SHA-256 authentication
  • caching_sha2_password: Implements SHA-256 authentication (like sha256_password), but uses caching on the server side for better performance and has additional features for wider applicability

mysql8.0默認用的是: caching_sha2_password而不是mysql_native_password, 咱們的解決方案則是修改root用戶鑑權模式從caching_sha2_password爲傳統的mysql_native_password.app

經過查詢用戶信息:socket

mysql> select Host,User,plugin,authentication_string from user where User='root'\G
*************************** 1. row ***************************
                 Host: localhost
                 User: root
               plugin: auth_socket
authentication_string: 
1 row in set (0.00 sec)

本質上應該使得client driver支持auth_socket.

3. 解決方案

方案一: 連接到mysql server, 執行以下命令:

ALTER USER 'root'@'%' IDENTIFIED WITH mysql_native_password BY 'password'; 
ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'password';

方案二: 設置docker啓動命令, 採用native password

db_mysql:
    container_name: mysql
    environment:
      MYSQL_ROOT_PASSWORD: 1qaz
      TZ: Asia/Shanghai
    image: mysql
    command: --default-authentication-plugin=mysql_native_password
    ports:
      - 3306:3306
    restart: always

重啓nodejs服務沒有錯誤了, 問題解決!

4 .參考資料

相關文章
相關標籤/搜索