Drf-Social-Oauth2 文档翻译(二)

190 阅读1分钟

水平不高,欢迎指正。

集成Google

为了将Google OAuth2设置成您的REST API的授权后端,您的settings.py应该做如下设置:

AUTHENTICATION_BACKENDS = (
    # Others auth providers (e.g. Facebook, OpenId, etc)
    ...
    # Google  OAuth2
    'social_core.backends.google.GoogleOAuth2',
    # drf-social-oauth2
    'drf_social_oauth2.backends.DjangoOAuth2',
    # Django
    'django.contrib.auth.backends.ModelBackend',
)

# Google configuration
SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = <your app id goes here>
SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = <your app secret goes here>

# Define SOCIAL_AUTH_GOOGLE_OAUTH2_SCOPE to get extra permissions from Google.
SOCIAL_AUTH_GOOGLE_OAUTH2_SCOPE = [
    'https://www.googleapis.com/auth/userinfo.email',
    'https://www.googleapis.com/auth/userinfo.profile',
]

为了测试配置好的设置,执行下面的命令:

curl -X POST -d "grant_type=convert_token&client_id=<django-oauth-generated-client_id>&client_secret=<django-oauth-generated-client_secret>&backend=google-oauth2&token=<google_token>" http://localhost:8000/auth/convert-token

成功执行上面的命令后,将返回一个访问令牌(access token)。对您的REST API发出的每一个HTTP请求,都必须使用访问令牌。本质上,您把第三方的访问令牌(user_access_token)转换成可用于您API和客户端的访问令牌(access_token)。对于您的系统/应用程序与API之间的每次后续通信,都有必要使用此令牌对每个请求进行身份验证,从而避免每次都需要向Google进行身份验证。

为了获取您的应用ID(SOCIAL_AUTH_GOOGLE_OAUTH2_KEY)和密码(SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET),访问console.developers.google.com/apis/creden… 。有关创建ID和密码的更多详细信息,请访问developers.google.com/identity/pr…

出于测试目的,你可以从developers.google.com/oauthplaygr… 使用访问令牌(user_access_token)并遵循以下步骤:

关于python-social-auth关于Google配置,请访问python-social-auth.readthedocs.io/en/latest/b…

如果您需要循序渐进的教程,请参阅@djangokatya提供的链接djangokatya.com/2021/04/09/…