首頁 >web前端 >js教程 >使用JavaScript和BUN的Google Oauthententication的分步指南

使用JavaScript和BUN的Google Oauthententication的分步指南

Susan Sarandon
Susan Sarandon原創
2025-01-29 08:35:08841瀏覽

本指南展示了Google OAuth2用戶身份驗證的基本JavaScript和Express Server實現。 儘管庫簡化了過程,但這種動手方法闡明了核心概念。我們將使用bun,快速的JavaScript運行時。


Google OAuth2設置

在編碼之前,配置您的Google Cloud項目:

步驟1:創建一個Google Cloud Project

  1. 訪問Google Cloud Console。
  2. 創建一個新項目(或使用現有項目)。 A Step-by-Step Guide to Google OAuthuthentication with JavaScript and Bun

>步驟2:配置OAuth同意屏幕

  1. >導航到> api&services> oauth同意屏幕
  2. 提供應用程序名稱,支持電子郵件和其他必需的詳細信息。 A Step-by-Step Guide to Google OAuthuthentication with JavaScript and Bun
  3. (可選)自定義品牌,以提供更有信息的同意屏幕。 A Step-by-Step Guide to Google OAuthuthentication with JavaScript and Bun

步驟3:定義範圍

  1. > scopes 下,添加:
    • :訪問用戶的電子郵件。 email
    • :openID Connect用於身份驗證。 openid>
    • :訪問基本配置文件數據(名稱,圖片)。 profileA Step-by-Step Guide to Google OAuthuthentication with JavaScript and Bun
步驟4:生成OAuth客戶端ID

(允許幾分鐘進行處理。)

>

  1. 轉到憑據>創建證書> OAuth客戶端ID
  2. 選擇> Web應用程序作為應用程序類型。
  3. >
  4. set 指定ahttp://localhost:3000>重定向uri
  5. 。 請記住要更新這些URI進行生產部署。 Google在身份驗證後將用戶重定向到重定向URI,包括授權代碼和狀態。為簡單起見,我們使用同一頁面。 http://localhost:3000 A Step-by-Step Guide to Google OAuthuthentication with JavaScript and Bun A Step-by-Step Guide to Google OAuthuthentication with JavaScript and Bun>步驟5:添加測試用戶
>用於測試,添加測試用戶的電子郵件地址。徹底測試後發布您的應用程序。

A Step-by-Step Guide to Google OAuthuthentication with JavaScript and Bun

google oauth2代碼實現

> 項目結構

我們使用BUN版本1.2。

<code>project/
├── public/
│   └── index.html
├── src/
│   └── index.js
├── .env
└── bun.lock</code>

>此HTML為Google登錄和OAuth回調處理提供了一個簡單的接口。 (簡潔而省略了代碼,但包含在原始提示中)index.html

(服務器端邏輯)

(省略了簡潔的代碼,但包含在原始提示中)index.js>

>運行項目

>安裝bun(BUN網站上可用的說明)。

    >用您的
  1. .env運行服務器:GOOGLE_CLIENT_IDGOOGLE_CLIENT_SECRET> GOOGLE_REDIRECT_URI測試流量:訪問
  2. ,與Google登錄,然後檢查令牌的控制台。
  3. bun run index.js
  4. http://localhost:3000結論

此手冊實現提供了對Google OAuth2的深刻了解。儘管護照或NextAuth等圖書館提供了便利,但這種方法闡明了基本的身份驗證機制。

以上是使用JavaScript和BUN的Google Oauthententication的分步指南的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn