全棧身份認證實作:使用 Next.js、NextAuth.js 和 MongoDB-12. 帳號登入
Published in
Dec 13, 2023
使用電子郵件和密碼進行帳號登入的方法。
12–1. 設定登入功能
- 在 nextauth-options.ts 中加入 CredentialsProvider,設定 authorize function 來驗證用戶提供的登入憑證。
- 在 auth.actions.ts 中新增 signInWithCredentials 以處理登入請求,使用 bcrypt 來驗證用戶輸入的密碼,如驗證成功,返回用戶信息;如失敗,返回錯誤信息。
- signin-form.tsx 修改 onSubmit function,使用 credentials signIn 功能並傳遞 email、password 和 callbackUrl 參數進行登入。
程式碼
單元重點
- 於 nextauth-options.ts 添加 CredentialsProvider;新增 server actions:signInWithCredentials。
- 於登入表單使用 credentials signIn 功能。
參考資料
NextAuth.js (Credentials)-https://next-auth.js.org/providers/credentials