1. 程式人生 > 實用技巧 >Oauth2.0認證 + 微博三方登陸

Oauth2.0認證 + 微博三方登陸

Oauth2.0授權認證

oauth2.0是什麼?

OAuth(開放授權)是一個開放標準,允許使用者讓第三方應用訪問該使用者在某一網站上儲存的私密的資源(如照片,視訊,聯絡人列表),而無需將使用者名稱和密碼提供給第三方應用。

Oauth2.0的四種授權模式?

  • 隱式授權模式(Implicit Grant)
  • 授權碼授權模式(Authorization code Grant)
  • 密碼模式(Resource Owner Password Credentials Grant)
  • 客戶端憑證模式(Client Credentials Grant)

微博三方登陸

微博登陸流程圖

1.建立應用(syl/apps)

pyhton ../manage.py startapp oauth

2.在syl/setting.py裡面配置

INSTALLED_APPS = [
    
    'oauth',

]

WEIBO_APP_KEY = '3909184723'
WEIBO_APP_SECRET = 'd4ca62c699779f0f91bd00c7e7c1197f'
WEIBO_CALL_BACK = 'http://127.0.0.1:8888/oauth/callback/'   # 回撥路由
syl/setting.py

3.apps下oauth/views.py

from urllib.parse import
urlencode import requests from django.contrib.auth.hashers import make_password from rest_framework.response import Response from rest_framework.views import APIView from oauth.models import WbUser from user.models import User from user.views import jwt_response_payload_handler from rest_framework_jwt.serializers import
* class WBUrl(APIView): def post(self, request): url = 'https://api.weibo.com/oauth2/authorize?' # 微博授權的url地址 data = { 'client_id': '3223679452', # WEIBO_APP_KEY, 'response_type': 'code', 'redirect_uri': 'http://127.0.0.1:8888/oauth/callback/', # VUE的回撥, 微博後臺授權的回撥地址 } # 拼接微博授權路由url weibo_url = url + urlencode(data) return Response({'code': '0', 'msg': '成功', 'data': {'url': weibo_url}}) class WBCallBack(APIView): # 自定義許可權類 # permission_classes = (AllowAny,) def post(self, request): # 接收vue端傳過來的code( 微博的使用者code) # 1.使用微博使用者code+微博開發者賬號資訊換取微博的認證access_token code = request.data.get('code') data = { 'client_id': '3223679452', 'client_secret': 'd70a48d3b12e7eb1d6c4b5bf3cecbd58', 'grant_type': 'authorization_code', 'code': code, 'redirect_uri': 'http://127.0.0.1:8888/oauth/callback/' } url = 'https://api.weibo.com/oauth2/access_token' weibo_data = requests.post(url=url, data=data) print(type(weibo_data)) json_weibo_data = weibo_data.json() uid = json_weibo_data.get("uid") if uid: try: uid_user = WbUser.objects.get(uid=uid) user = uid_user.user payload = jwt_payload_handler(user) token = jwt_encode_handler(payload) data = jwt_response_payload_handler(token, user) res_data = { 'code': 0, "msg": "授權成功", "data": { "type": 0, "uid": uid, "username": uid_user.user.username, "token": data['token'] } } return Response(res_data) except Exception as e: res_data = { 'code': 0, "msg": "授權成功", "data": { "type": 1, "uid": uid, } } return Response(res_data) else: return Response({"code": 999, "msg": "獲取微博資訊失敗"}) class BindUser(APIView): def post(self,request): oauth_type=1 username=request.data.get("username") password=request.data.get("password") weibo_uid=request.data.get("weibo_uid") print(username,password,weibo_uid) if not all([username,password,weibo_uid]): return Response({"code":4005,"msg":"引數不全"}) # 存在繫結使用者 try: user=User.objects.filter(username=username).first() payload = jwt_payload_handler(user) token = jwt_encode_handler(payload) data = jwt_response_payload_handler(token, user) oauthinfo=WbUser.objects.create(uid=weibo_uid,oauth_type=oauth_type,user=user) data={ "authenticcated":True, "id":user.id, "role":None, "name":user.nick_name, "username":username, "email":user.email, "token":data['token'], "type":0 } res_data={ "code":0, "msg":"登入成功", "data":data } return Response(res_data) #不存在則create建立 except Exception as e: print(e) password=make_password(password) user=User.objects.create(username=username,password=password) oauthinfo = WbUser.objects.create(uid=weibo_uid, oauth_type=oauth_type, user=user) payload = jwt_payload_handler(user) token = jwt_encode_handler(payload) data_t = jwt_response_payload_handler(token, user) data = { "authenticcated": True, "id": user.id, "role": None, "name": user.nick_name, "username": username, "email": user.email, "token": data_t['token'], "type": 0 } res_data = { "code": 0, "msg": "登入成功", "data": data } return Response(res_data)
oauth/views.py

4.在oauth/urls.py裡配置二級路由

# -*- coding: utf-8 -*-
from django.urls import path
from . import views
urlpatterns = [
    path('weibo/', views.WBUrl.as_view(), ),  # 拼接微博url
    path('weibo/callback/', views.WBCallBack.as_view(), ), # 授權回撥
    path('weibo/binduser/', views.BindUser.as_view(), ),   # 繫結使用者

]
oauth/urls.py