如何通过django-allauth获取Microsoft Graph用户的头像列表?
如何通过django-allauth获取Microsoft Graph用户的头像列表
可以获取用户的头像列表。django-allauth默认仅拉取基础用户信息,要获取头像列表需要扩展其逻辑,调用Microsoft Graph的特定接口。以下是具体实现步骤:
1. 配置应用权限
在Azure Portal的Microsoft应用注册页面,添加User.Read权限(仅获取当前用户头像的话,该权限足够),并完成权限的授予操作。
2. 自定义Microsoft社交账号适配器
创建自定义适配器,继承allauth.socialaccount.adapter.DefaultSocialAccountAdapter,重写populate_user方法,在用户登录或注册时调用Graph API拉取头像列表:
# 在你的应用目录下创建adapter.py文件 from allauth.socialaccount.adapter import DefaultSocialAccountAdapter import requests import json class MicrosoftSocialAccountAdapter(DefaultSocialAccountAdapter): def populate_user(self, request, sociallogin, data): user = super().populate_user(request, sociallogin, data) # 获取当前登录用户的access token social_token = sociallogin.account.socialtoken_set.first() access_token = social_token.token # 调用Microsoft Graph API获取头像列表 headers = {"Authorization": f"Bearer {access_token}"} api_url = "https://graph.microsoft.com/v1.0/me/photos" response = requests.get(api_url, headers=headers) if response.status_code == 200: photos_list = response.json().get("value", []) # 可将头像数据保存到User模型或自定义的Profile模型中 # 示例:假设你有一个关联User的Profile模型,含avatar_list字段 # if hasattr(user, 'profile'): # user.profile.avatar_list = json.dumps(photos_list) # user.profile.save() return user
3. 配置使用自定义适配器
在项目的settings.py中指定自定义适配器:
# settings.py SOCIALACCOUNT_ADAPTER = "你的应用名称.adapter.MicrosoftSocialAccountAdapter"
4. 处理头像资源
/me/photos接口返回的每条头像数据包含id、width、height等信息,可通过https://graph.microsoft.com/v1.0/me/photos/{头像ID}/$value获取对应头像的二进制文件。若需要将头像保存到本地或云存储,可在适配器中进一步发起请求处理。
注意事项
- 确保已安装
requests库(执行pip install requests) - 需处理API调用的异常场景,比如token过期、权限不足等
- 若需在用户登录后随时获取头像,可在视图中通过
SocialAccount关联的token再次调用API
内容的提问来源于stack exchange,提问作者Jayant Jaiswal
相关产品推荐
相关产品推荐

