--- tags: Node.js 直播班 - 2023 春季班 --- # Google 第三方登入 * [線上範例程式碼 week8 branch](https://github.com/gonsakon/express-week4-sample/tree/feature/googleAuth) * [Google 第三方圖示](https://whimsical.com/google-passport-6kuRrQ3ioC5mVwhaM5kngy) * [Google 服務設計](https://console.cloud.google.com/welcome) ## NPM * [passport](https://www.npmjs.com/package/passport) ## 圖示  ## OAuth 2.0 的授權 簡單來說其實就是獲取令牌(token)的過程。OAuth 協定定義了四種獲取令牌的授權方式(authorization grant)如下: * 授權碼模式(authorization-code) * 隱藏模式(implicit) * 密碼模式(password) * 客戶端憑證模式(client credentials) ## 延伸資訊 * [使用 Express + Passport 實作一個 Google OAuth 2.0 登入](https://israynotarray.com/nodejs/20220525/790433249/) * [前後端分離範例](https://blog.hanklu.tw/spa-api-social-loign/) * [[筆記] 認識 OAuth 2.0:一次了解各角色、各類型流程的差異](https://medium.com/%E9%BA%A5%E5%85%8B%E7%9A%84%E5%8D%8A%E8%B7%AF%E5%87%BA%E5%AE%B6%E7%AD%86%E8%A8%98/%E7%AD%86%E8%A8%98-%E8%AA%8D%E8%AD%98-oauth-2-0-%E4%B8%80%E6%AC%A1%E4%BA%86%E8%A7%A3%E5%90%84%E8%A7%92%E8%89%B2-%E5%90%84%E9%A1%9E%E5%9E%8B%E6%B5%81%E7%A8%8B%E7%9A%84%E5%B7%AE%E7%95%B0-c42da83a6015) * [Google 的第三方登入 (web 前端實作)](https://dwatow.github.io/2021/06-15-google-sign-in-oauth/) ## 前後端分離後端寫法 ### 前端 ``` <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <a href="https://accounts.google.com/o/oauth2/v2/auth?client_id=771760535711-6it451lk1m6ah82gk5rps86p7qsopkt6.apps.googleusercontent.com&redirect_uri=http://localhost:5500/googlecallback.html&response_type=code&scope=email%20profile&access_type=offline">Google 登入</a> </body> </html> ``` ### 後端 ``` router.post('/googleClient/callback', passport.authenticate('google', { session: false }), handleErrorAsync(async(req,res,next)=> { const user = await User.findById(req.user.id); generateSendJWT(user,200,res) })) ```
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up