原文: https://pythonspot.com/login-to-flask-app-with-google/

在本文中,您将学习如何在 Flask 应用中使用 Google 进行登录身份验证。 您可以使用 Google 来对您的网站进行身份验证,而不是使用自定义用户登录系统。 您的访问者可能已经在 Google 上拥有一个帐户,为什么不使用它登录?

为此,我们使用称为 OAuth 的协议。 从维基百科:

OAuth 是一种使用令牌来代表资源所有者访问资源的协议。 考虑使用户能够对网站的某些部分发出代客密钥。 许多网站,例如 Google,Facebook 和 Twitter,都使用 OAuth 来认证第三方客户端,以便访问某些用户资源。

如果听起来含糊,请放心,我们将逐步指导您。

使用 Google 的登录验证

我们使用名为flask_oauth的模块向 Google 进行身份验证。 它由 Flask 的创建者 Armin Ronacher 维护,因此可以确保该模块不会消失。 该模块使用 OAuth,该协议提供令牌以访问资源。 其他模块可能没有很好的支持。

复制下面的代码,并设置您从上面的 Google 获得的客户端 ID客户端密钥。 只需替换以下行:

  1. GOOGLE_CLIENT_ID = 'PUT CLIENT ID'
  2. GOOGLE_CLIENT_SECRET = 'PUT CLIENT SECRET'

将程序另存为app.py

  1. from flask import Flask, redirect, url_for, session
  2. from flask_oauth import OAuth
  3. # You must configure these 3 values from Google APIs console
  4. # https://code.google.com/apis/console
  5. GOOGLE_CLIENT_ID = 'PUT CLIENT ID'
  6. GOOGLE_CLIENT_SECRET = 'PUT CLIENT SECRET'
  7. REDIRECT_URI = '/oauth2callback' # one of the Redirect URIs from Google APIs console
  8. SECRET_KEY = 'development key'
  9. DEBUG = True
  10. app = Flask(__name__)
  11. app.debug = DEBUG
  12. app.secret_key = SECRET_KEY
  13. oauth = OAuth()
  14. google = oauth.remote_app('google',
  15. base_url='https://www.google.com/accounts/',
  16. authorize_url='https://accounts.google.com/o/oauth2/auth',
  17. request_token_url=None,
  18. request_token_params={'scope': 'https://www.googleapis.com/auth/userinfo.email',
  19. 'response_type': 'code'},
  20. access_token_url='https://accounts.google.com/o/oauth2/token',
  21. access_token_method='POST',
  22. access_token_params={'grant_type': 'authorization_code'},
  23. consumer_key=GOOGLE_CLIENT_ID,
  24. consumer_secret=GOOGLE_CLIENT_SECRET)
  25. @app.route('/')
  26. def index():
  27. access_token = session.get('access_token')
  28. if access_token is None:
  29. return redirect(url_for('login'))
  30. access_token = access_token[0]
  31. from urllib2 import Request, urlopen, URLError
  32. headers = {'Authorization': 'OAuth '+access_token}
  33. req = Request('https://www.googleapis.com/oauth2/v1/userinfo',
  34. None, headers)
  35. try:
  36. res = urlopen(req)
  37. except URLError, e:
  38. if e.code == 401:
  39. # Unauthorized - bad token
  40. session.pop('access_token', None)
  41. return redirect(url_for('login'))
  42. return res.read()
  43. return res.read()
  44. @app.route('/login')
  45. def login():
  46. callback=url_for('authorized', _external=True)
  47. return google.authorize(callback=callback)
  48. @app.route(REDIRECT_URI)
  49. @google.authorized_handler
  50. def authorized(resp):
  51. access_token = resp['access_token']
  52. session['access_token'] = access_token, ''
  53. return redirect(url_for('index'))
  54. @google.tokengetter
  55. def get_access_token():
  56. return session.get('access_token')
  57. def main():
  58. app.run()
  59. if __name__ == '__main__':
  60. main()

使用以下命令执行:

  1. python app.py
  2. * Running on http://127.0.0.1:5000/
  3. * Restarting with reloader

然后,您可以打开链接以查看登录屏幕。 一旦接受,该应用程序将仅返回以 JSON 格式编码的您的帐户信息。

使用 Google 登录到您的 Flask 应用 - 图1

使用 Google 登录到您的 Flask 应用

最后,您可以验证是否在新路由上设置了访问令牌。

下载 Flask 示例