vue+Django接入钉钉登录

前端处理

复制代码
 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/userAccessToken
        
        logger.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自己的token
        result = {'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

相关推荐
FRing0318 小时前
vue2干货总结3(computed计算属性、watch监听器)
开发语言·前端·vue.js·vue2
Java小卷19 小时前
JuanForm vs FormCreate!Vue3 表单引擎联动配置 PK!
vue.js·低代码
小郎君6581 天前
Vue 多标签页的加载态设计:为什么我没有用 Suspense 实现 PageLoading
vue.js·算法
yilaisai1 天前
前端开发遇到的一些细节问题整理
vue.js
华玥作者1 天前
Vue 3 + TypeScript + uni-app 组件库推荐:hy-app(华玥组件库)
vue.js·typescript·uni-app
阿琳a_1 天前
b-map-viewer:面向 Vue 3 的地图可视化 SDK,从接入到展示再到交互分析
前端·javascript·vue.js·gis·数据可视化·地图
齐 飞1 天前
VUE2常用语法总结
javascript·vue.js
北城笑笑1 天前
Vue 106 ,上篇:前端桌面端应用实现方案( Electron 框架详细介绍,Vue + Electron )
前端·javascript·vue.js·python·electron
不磕了还不行1 天前
用 Vue + Element UI 把元宝搜索的返回值做成“能点开检查的证据卡片”
前端·vue.js·ui
实名上网宋凯宣2 天前
Django
后端·python·django