简体   繁体   English

Python Social Auth、Google 和刷新令牌

[英]Python Social Auth, Google, and refresh token

In a personal project, I am trying to use Django as my front end and then allow data entered by users in a particular form to be copied to google sheets.在个人项目中,我尝试使用 Django 作为我的前端,然后允许将用户以特定形式输入的数据复制到 Google 表格中。

Google's own docs recommend using https://github.com/google/oauth2client which is now deprecated, and the docs have not been updated.谷歌自己的文档推荐使用https://github.com/google/oauth2client现在已弃用,并且文档尚未更新。 With this, I have started attempting to use Python Social Auth and Gspread .有了这个,我开始尝试使用Python Social AuthGspread For Gspread to be able to function correctly, I need to be able to pass it not only an access token but also a refresh token.为了让 Gspread 能够正常运行,我不仅需要向它传递访问令牌,还需要传递刷新令牌。 Python Social Auth however is not persisting the refresh token along with the rest of the "extra data".然而,Python Social Auth 不会将刷新令牌与“额外数据”的其余部分一起保存。 Looking at the data preserved and the URLs routed to, it seems to me more like somewhere it is routing through Google+.查看保留的数据和路由到的 URL,在我看来更像是通过 Google+ 路由的某个地方。

I have the following configurations in my Django settings files:我的 Django 设置文件中有以下配置:

AUTHENTICATION_BACKENDS = (
    'social_core.backends.google.GoogleOAuth2',
    'django.contrib.auth.backends.ModelBackend',
)

SOCIAL_AUTH_PIPELINE = (
    'social_core.pipeline.social_auth.social_details',
    'social_core.pipeline.social_auth.social_uid',
    'social_core.pipeline.social_auth.social_user',
    'social_core.pipeline.user.get_username',
    'social_core.pipeline.user.create_user',
    'social_core.pipeline.social_auth.associate_user',
    'social_core.pipeline.social_auth.load_extra_data',
    'social_core.pipeline.user.user_details',
    'social_core.pipeline.social_auth.associate_by_email',
)    

SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = '...'
SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = '...'
SOCIAL_AUTH_GOOGLE_OAUTH2_SCOPE = ['https://www.googleapis.com/auth/spreadsheets']
  • Is there a better way to access a google sheet?有没有更好的方法来访问谷歌表?
  • Am I correct that PSA or google is redirecting me into a Google+ auth flow instead of the Google Oauth2? PSA 或 google 将我重定向到 Google+ 身份验证流程而不是 Google Oauth2 是否正确?
  • If not, what must change so that Python Social Auth keeps the refresh token?如果不是,那么必须更改什么才能使 Python Social Auth 保留刷新令牌?

Just provide this in your settings.py :只需在您的settings.py提供:

SOCIAL_AUTH_GOOGLE_OAUTH2_AUTH_EXTRA_ARGUMENTS = { 'access_type': 'offline', 'hd': 'xyzabc.com', 'approval_prompt':'force' } remeber there is {'approval_prompt' : 'force'} which will force the user to select the gmail account, this way you will get refresh token. SOCIAL_AUTH_GOOGLE_OAUTH2_AUTH_EXTRA_ARGUMENTS = { 'access_type': 'offline', 'hd': 'xyzabc.com', 'approval_prompt':'force' }记住有{'approval_prompt' : 'force'}帐户,这样您将获得刷新令牌。

It's true that python-social-auth will use some bits of the Google+ platform, at least the API to retrieve details about the user to fill in the account.确实, python-social-auth将使用 Google+ 平台的一些部分,至少是 API 来检索有关用户的详细信息以填写帐户。

From your settings, I see you have associate_by_email at the bottom, at that point, at that point it has no use since the user is already be created, if you really plan to use it, it must be before the create_user one, you can check the DEFAULT_PIPELINE as a reference.从你的设置看,你在底部有associate_by_email ,那个时候,那个时候没有用,因为已经创建了用户,如果你真的打算使用它,它必须在create_user之前,你可以检查DEFAULT_PIPELINE作为参考。

In order to get a refresh_token from google, you need to tell it that you want one, to do that you need to set the offline access type:为了从 google 获取refresh_token ,您需要告诉它您想要一个,为此您需要设置offline访问类型:

SOCIAL_AUTH_GOOGLE_OAUTH2_AUTH_EXTRA_ARGUMENTS = {
  'access_type': 'offline'
}

With that setting Google will give you a refresh_token and it will automatically stored in extra_data .有了这个设置,谷歌会给你一个refresh_token ,它会自动存储在extra_data

You can send extra parameters to the OAuth2 provider using the variable您可以使用变量向 OAuth2 提供程序发送额外的参数

SOCIAL_AUTH_<PROVIDER>_AUTH_EXTRA_ARGUMENTS

For Google, you can see the extra parameters they accept in their documentation (scroll down to "parameters") .对于 Google,您可以在他们的文档中看到他们接受的额外参数(向下滚动到“参数”) The one we are looking for is access_type :我们正在寻找的是access_type

access_type : Indicates whether your application can refresh access tokens when the user is not present at the browser. access_type :指示当用户不在浏览器时您的应用程序是否可以刷新访问令牌。 Valid parameter values are online, which is the default value, and offline.有效参数值为 online(默认值)和 offline。

So we can add the following to settings.py , to indicate that we want to receive a refresh token:因此,我们可以将以下内容添加到settings.py ,以表明我们想要接收刷新令牌:

SOCIAL_AUTH_GOOGLE_OAUTH2_EXTRA_ARGUMENTS = {"access_type: offline"}

The results from EXTRA_ARGUMENTS will be stored in extra_data , so the refresh token can be accessed like this: EXTRA_ARGUMENTS的结果将存储在extra_data ,因此可以像这样访问刷新令牌:

refresh_token = user.social_auth.get(provider="google-oauth2").extra_data["refresh_token"]

One possible solution is to store the refresh token alongside the user in a UserProfile model, by adding a custom function to the social-auth pipeline:一种可能的解决方案是通过向社交身份验证管道添加自定义函数,将刷新令牌与用户一起存储在UserProfile模型中:

  1. Create the model创建模型
# models.py

class UserProfile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="profile")
    refresh_token = models.CharField(max_length=255, default="")
  1. Add a function to access store the refresh token添加一个函数来访问存储刷新令牌
# pipeline.py

from .models import UserProfile

def store_refresh_token(user=none, *args, **kwargs):
    extra_data = user.social_auth.get(provider="google-oauth2").extra_data
    UserProfile.objects.get_or_create(
        user=user, defaults={"refresh_token": extra_data["refresh_token"]}
    )
  1. Add our new function to the social-auth pipeline.将我们的新功能添加到社交身份验证管道中。
# settings.py

...

SOCIAL_AUTH_PIPELINE = (
    ...
    "my-app.pipeline.store_refresh_token"
)  

SOCIAL_AUTH_GOOGLE_OAUTH2_SCOPE = [
    'https://www.googleapis.com/auth/spreadsheets'
    # any other scopes you need
]

...

The token is now stored alongside the user and can be used to initialise the sheets client or whatever else you need.令牌现在与用户一起存储,可用于初始化工作表客户端或您需要的任何其他内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM