前端处理
dingtalkLogin() {let url = `https://login.dingtalk.com/oauth2/auth?redirect_uri=${this.dingRedirectUrl}&response_type=code&client_id=${this.appKey}&scope=openid&state=STATE&prompt=consent`window.location.href = url;},
后端处理
def dingtalk_auth(request):try:code = request.GET['code']logger.info('钉钉临时授权码获取 ----{}'.format(code))token = get_user_token(code) # oauth2/userAccessTokenlogger.info('根据钉钉临时授权码获取token ----{}'.format(token))user_resp = get_user_info(token) # /contact/users/{}logger.info('根据获取用户信息 ----{}'.format(user_resp))user = User.objects.filter(username=user_resp['mobile']).first()if user:user.email = user_resp.get('email', '')user.save()else:params = {'username': user_resp.get('mobile'),'first_name': user_resp.get('nick'),'dingtalk_name': user_resp.get('nick'),'dingtalk_avatar': user_resp.get('avatarUrl'),'mobile_phone': user_resp.get('mobile'),'email': user_resp.get('email'),'is_superuser': False}user = User.objects.create(**params)logger.info('根据用户信息 ----{}'.format(user.username))if not user.is_staff:print("----校验用户登录权限{}----".format(user.is_staff))return JsonResponse({'code': 204, "msg": '请确认您是否有此网站的登录权限'})refresh = RefreshToken.for_user(user)# 生成一个Django自己的tokenresult = {'code': 200, "username": user.username, "token": str(refresh.access_token)}print("----校验用户获取返回值为{}----".format(result))return JsonResponse(result)except Exception as e:print(e)print(traceback.format_exc())logger.info('钉钉登录报错 ----{}'.format(traceback.format_exc()))return JsonResponse({'code': 400, 'errmsg': str(e)})
参考
https://developer.aliyun.com/article/1488636
https://open.dingtalk.com/document/orgapp-server/use-dingtalk-account-to-log-on-to-third-party-websites-1?spm=a2c6h.12873639.article-detail.7.5d622205VHxpO0#title-fre-oe4-zqn