跳至主要內容

Max行銷誌

行銷、數據分析、與 Python

  • Python
  • Git
  • Flask
  • Crawler
  • GTM
  • Data Analytics
  • Dashboard
  • About

Max行銷誌

行銷、數據分析、與 Python

  • Python
  • Git
  • Flask
  • Crawler
  • GTM
  • Data Analytics
  • Dashboard
  • About

Max行銷誌

行銷、數據分析、與 Python

[Flask教學] 5分鐘上手 Flask Google login 登入

By MaxAll posts、Python Flask 教學 最後更新時間 17 6 月, 2020
flask_google_login_photo

此篇參考官方文件 Integrating Google Sign-In into your web app這篇文章,部分程式碼有稍微修改,和列出過程中遇到的Bug,希望對有想用Flask架設google login的朋友有幫助。

Table

  • 1. 建立 Google OAuth 2.0 憑證?
  • 2. Flask 建立 login 前端畫面
  • 3. Flask 建立 login 後端設定
  • 發生 Error invalid_request 怎麼辦?

1. 建立 Google OAuth 2.0 憑證?

  1. 在Google Cloud Platform > 點擊APIs & Services >點擊Credentials >建立Create Credentials >選擇Create OAuth client ID 就會到如下圖的畫面
  2. 應用類型選擇Web application
  3. 授權來源和重定向URI填入 http://localhost:5000
  4. 點選建立,就完成囉!

2. Flask 建立 login 前端畫面

  1. 完整html如下,可以看到<div class=”g-signin2″ data-onsuccess=”onSignIn”></div>這段是產生google login的登入按鈕
  2. 點擊按鈕後會呼叫function onSignIn,如果登入成功會console.log出使用者資訊來,並且用$.ajax Post的方始將Token ID傳到Flask後端
  3. 接下來我們看一下Flask後端main.py的檔案內容
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
<html>
  <head>
    <title>Google Sign-In</title>
    <meta name="google-signin-client_id" content="{{ google_oauth2_client_id }}">
    <script src="https://apis.google.com/js/platform.js" async defer></script>
    <script src="https://code.jquery.com/jquery-3.3.1.js" integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60=" crossorigin="anonymous"></script>
  </head>
  <body>
    <script>
      function onSignIn(googleUser) {
        var id_token = googleUser.getAuthResponse().id_token;
        var profile = googleUser.getBasicProfile();
        console.log('ID: ' + profile.getId()); // Do not send to your backend! Use an ID token instead.
        console.log('Name: ' + profile.getName());
        console.log('Image URL: ' + profile.getImageUrl());
        console.log('Email: ' + profile.getEmail()); // This is null if the 'email' scope is not present.
        $.ajax({
          type: "POST",
          url: '/google_sign_in',
          data: JSON.stringify({'id_token': id_token}),
          success: function() {
            console.log('login success')
          },
          dataType: 'json',
          contentType:"application/json",
        });
      }
    </script>
    <div class="g-signin2" data-onsuccess="onSignIn"></div>
  </body>
</html>

3. Flask 建立 login 後端設定

  1. 完整代碼如下,首先要修改GOOGLE_OAUTH2_CLIENT_ID = ‘將自己的Client id輸入’ (可以在我們一開始建立的Google APIs & Services頁面中找到Client ID)
  2. 再來看到 @app.route(‘/google_sign_in’, methods=[‘POST’])這邊是接收剛剛前端所傳來的Cliend ID Token
  3. 最後運行在終端機 env FLASK_APP=app.py flask run
  4. 趕快自己測試看看吧
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# -*- coding: utf-8 -*-
from google.oauth2 import id_token
from google.auth.transport import requests
from flask import Flask
from flask import request
from flask import jsonify
from flask import render_template
 
GOOGLE_OAUTH2_CLIENT_ID = '這部分輸入自己的_oauth2_client_id'
 
def create_app(app_env=None):
    flask_app = Flask(__name__)
    return flask_app
app = create_app()
 
@app.route('/')
def index():
    return render_template('index.html', google_oauth2_client_id=GOOGLE_OAUTH2_CLIENT_ID)
    
    
@app.route('/google_sign_in', methods=['POST'])
def google_sign_in():
    token = request.json['id_token']
    
    try:
        id_info = id_token.verify_oauth2_token(
            token,
            requests.Request(),
            GOOGLE_OAUTH2_CLIENT_ID
        )
        if id_info['iss'] not in ['accounts.google.com', 'https://accounts.google.com']:
            raise ValueError('Wrong issuer.')
    except ValueError:
        # Invalid token
        raise ValueError('Invalid token')
    print('登入成功')
    return jsonify({}), 200

發生 Error: invalid_request 怎麼辦?

  1. 詳細錯誤訊息如下:Permission denied to generate login hint for target domain.
  2. 原因是Google OAuth的登入他不吃IP
  3. 所以只需要將http://127.0.0.1:5000/改成http://localhost:5000就可以成功登入囉!

關於 Flask 教學的延伸閱讀:

▍關於 Flask 教學系列目錄:

  • 【Flask教學系列】實作 Flask 教學目錄

▍其他 Flask 相關教學:

  • 【Flask教學系列】Flask 為甚麼需要 WSGI 與 Nginx
  • 【Flask教學系列】Flask-SQLAlchemy 資料庫連線&設定入門 (一)
  • 【Flask教學系列】Flask-JWT-Extended 實作
  • 【Flask教學系列】實作 Flask CORS
  • 【Flask教學系列】實作 Flask CSRF Protection
  • 【Flask教學系列】實作 Dockerfile + nginx + ssl + Flask 教學 (附GitHub完整程式)

[Flask教學] 5分鐘上手Flask Google login登入教學結束囉,感謝收看,有關Max行銷誌的最新文章,都會發佈在Max的Facebook粉絲專頁,如果想看最新更新,還請您按讚或是追蹤唷!

flaskflask google loginflask google登入flask教學flask登入介面

文章導覽

[Flask教學] 5分鐘快速設定 Flask 取得 Cookie
[Flask教學] Flask Session 使用方法和介紹

Archives

  • All posts
  • 2025
  • 2024 (4 pages)
  • 2023 (22 pages)
  • 2022 (20 pages)
  • 2021 (17 pages)
  • 2020 (48 pages)
  • 2019 (35 pages)
  • 2018 (31 pages)

Category

  • Python 從 0 開始教學手冊
  • Git 學習路線指南
  • Flask 入門指南
  • 進階爬蟲
  • 走在數據工程師的路上
  • 數據視覺化 Looker Studio
  • 數據追蹤學 GTM

Hot Topic

  • 蝦皮賣家競品分析
  • 電商小細節:頁面優化經驗談
  • 電商數據儀表板
  • 從部落格學數據分析
  • Python 一切皆為物件,到底什麼是物件 Object ?
  • Git 時光機 – 回復版本的 2 種方法
  • 過去一年,下班後的學習

Tags

  • All posts (171)
  • Crypto (6)
  • Git 教學 (10)
  • Google Tag Manager 教學 (19)
  • Looker Studio 教學 (10)
  • n8n (2)
  • Python Django 教學 (3)
  • Python Flask 教學 (36)
  • Python 基礎教學 (29)
  • Python 數據分析 (25)
  • Python 機器學習 (6)
  • Python 爬蟲教學 (15)
  • Python 資料庫教學 (12)
  • Swift 教學 (5)

About

  • Made with ☕ by Max

About

  • Made with ☕ by Max

Archives

  • All posts
  • 2025
  • 2024 (4 pages)
  • 2023 (22 pages)
  • 2022 (20 pages)
  • 2021 (17 pages)
  • 2020 (48 pages)
  • 2019 (35 pages)
  • 2018 (31 pages)

Explore

  • Python
  • Git
  • Flask
  • Crawler
  • Data Analytics
  • Dashboard
  • GTM
  • Max Newsletter
© 2025 Max行銷誌.