我在Django应用中使用OAuth2身份验证,授权后,我想将凭据保存在某处。我试图将它们保存在我的Django模型中。 到目前为止的代码如下:
models.py:
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
country = models.CharField(max_length=30, blank=True)
credentials = CustomCredential(
client_id='',
access_token='',
expires_in_seconds=0,
scopes='',
grant_type=''
)
def __str__(self):
return self.user.username
tasks.py:
def authorise(user, auth, redirect_url):
if auth:
session = auth_flow.get_session(redirect_url)
credentials = session.oauth2credential
print("Before:", user.profile.credentials.client_id) # blank value here
user.profile.country = country # some variable
user.profile.credentials = credentials
print("After:", user.profile.credentials.client_id) # client_id is printed
user.save()
return "/"
else:
auth_flow = AuthorizationCodeGrant(
CLIENT_ID,
SCOPE,
CLIENT_SECRET,
'http://localhost:8000/auth'
)
return auth_flow.get_authorization_url()
使用此代码,我可以更改字段值country
,credentials
,但是所做的更改仅保存到国家/地区,而不保存到凭据字段(client_id为空)
有人可以帮助我解决这个问题吗?或者,请提出是否有更好的方法在Django中存储授权凭证。