django 微信網(wǎng)頁(yè)授權(quán)登陸的實(shí)現(xiàn)
一、準(zhǔn)備工作
0x00 開(kāi)發(fā)前準(zhǔn)備
- 服務(wù)號(hào)!?。?/strong>
- 微信認(rèn)證。
- 備案過(guò)的域名。
- 服務(wù)器。
0x01 手動(dòng)觸發(fā)dns更新

0x02 配置業(yè)務(wù)域名
0x03 將服務(wù)器請(qǐng)求轉(zhuǎn)發(fā)到本地
修改服務(wù)器的 /etc/ssh/sshd_config 加入 GatewayPorts yes
ssh -R 0.0.0.0:80:localhost:8080 user@server_host
二、微信網(wǎng)頁(yè)授權(quán)
0x01 授權(quán)流程
用戶(hù)同意授權(quán),獲取 code
想辦法讓用戶(hù)頁(yè)面跳轉(zhuǎn)到微信的授權(quán)鏈接(比如在修飾器中進(jìn)行跳轉(zhuǎn)):
def get_wx_authorize_url(appid : str, state: str = None):
if state is None:
state = "".join([random.choice(string.ascii_letters + string.digits) for _ in range(20)])
redirect_url = 'your callback url' # 回調(diào)鏈接,在這里面進(jìn)行用戶(hù)信息入庫(kù)的操作
response_type = 'code'
scope = 'snsapi_userinfo'
wx_url = f"https://open.weixin.qq.com/connect/oauth2/authorize?appid={appid}&redirect_uri={redirect_url}&response_type={response_type}&scope={scope}&state={state}#wechat_redirect"
return wx_url
通過(guò) code 換取 access_token 和 openid
def request_access_token(appid : str, secret : str, code: str):
secret = settings.WX_SECRET
api = f"https://api.weixin.qq.com/sns/oauth2/access_token?appid={appid}&secret={secret}&code=[code]&grant_type=authorization_code"
r = requests.get(api)
return r.json()
通過(guò) access_token 換取 用戶(hù)信息
def request_userinfo(access_token: str, openid: str):
api = f"https://api.weixin.qq.com/sns/userinfo?access_token={access_token}&openid={openid}&lang=zh_CN"
r = requests.get(api)
return r.json()
用戶(hù)信息入庫(kù)
需要注意的是:微信返回的數(shù)據(jù)編碼格式為 ISO-8859-1 ,需要轉(zhuǎn)換成 utf-8 。
def convert_string_encoding(s: str, from_encoding: str, to_encoding: str) -> str: """先根據(jù) from_encoding 轉(zhuǎn)換成bytes,然后在 decode 為 to_encoding 的字符串 """ return bytes(s, encoding=from_encoding).decode(to_encoding)
nickname = convert_string_encoding(resp['nickname'], 'ISO-8859-1', 'utf-8')
跳轉(zhuǎn)回原來(lái)訪(fǎng)問(wèn)的鏈接
我的實(shí)現(xiàn)方式是在數(shù)據(jù)庫(kù)保存一條記錄,以 state 為 key 。
from app.models import WXUser, RedirectUrl
from utils import get_wx_authorize_url, get_random_string
from django.shortcuts import redirect
def login_required(func):
def wrapper(request, *args, **kwargs):
openid = request.openid
try:
user = WXUser.objects.get(openid=openid)
request.wxuser = user
except WXUser.DoesNotExist:
state = get_random_string()
redirect_url = get_wx_authorize_url(state=state)
# 存儲(chǔ)跳轉(zhuǎn)鏈接
try:
r = RedirectUrl.objects.get(state=state)
except RedirectUrl.DoesNotExist:
r = RedirectUrl()
r.state = state
origin_url = request.get_raw_uri()
r.url = origin_url
r.save()
return redirect(redirect_url)
return func(request, *args, **kwargs)
return wrapper
然后在我們?cè)O(shè)置的回調(diào)接口(會(huì)帶上 code 和 state )里面,就可以通過(guò) state 從數(shù)據(jù)庫(kù)里獲取原鏈接。
class RedirectUrl(BaseModel): state = models.TextField(unique=True) url = models.TextField()
0x02 中間件
這個(gè)中間件使用 jwt 作為認(rèn)證手段,為什么不使用 session ,那可以講另一個(gè)故事了,這里不贅述了。
從 HTTP_AUTHORIZATION (請(qǐng)求頭中的 Authorization 字段)或者 key 為 jwttoken 的 cookie 中抽取出 jwt token ,從中解析出 openid ,添加到 request 變量中,之后就可以在后續(xù)的 views里面通過(guò) request.openid 直接獲取 openid 了。
def jwt_decode(token: Union[str, bytes]) -> tuple:
"""
:param token : 可以是 bytes 也可以是 str,如果是 str,會(huì)先 encode 轉(zhuǎn)成 bytes
:return: 第一個(gè)參數(shù)為 payload,第二個(gè)參數(shù)為異常類(lèi)型
"""
if isinstance(token, str):
token = token.encode()
secret = settings.JWT_SECRET
try:
return jwt.decode(token, secret, algorithms=["HS256"]), None
except Exception as e:
# 統(tǒng)一捕捉異常:
# jwt.exceptions.DecodeError
# jwt.exceptions.InvalidSignatureError
# jwt.exceptions.ExpiredSignatureError
return None, e
class JWTAuthMiddleware(object):
"""
小程序認(rèn)證中間件
"""
def __init__(self, get_response=None):
self.get_response = get_response
def __call__(self, request, *args, **kws):
token = self.get_authorization_header(request)
payload, error = jwt_decode(token)
if not error:
openid = payload['openid']
request.openid = openid
else:
request.openid = None
response = self.get_response(request, *args, **kws)
return response
def get_authorization_header(self, request):
"""
從 AUTHORIZATION 請(qǐng)求頭或者cookie 中獲取 jwt code
cookie 的 jwt code 的 key 為 jwtcode
:param request:
:return: rawtoken
"""
auth_header = request.META.get('HTTP_AUTHORIZATION', '')
cookie = request.COOKIES
rawtoken = None
if auth_header != "":
try:
rawtoken = auth_header.split(" ")[1]
except IndexError as e:
pass
if 'jwttoken' in cookie:
rawtoken = cookie['jwttoken']
return rawtoken
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Python?VisPy庫(kù)高性能科學(xué)可視化圖形處理用法實(shí)例探究
VisPy是一個(gè)用于高性能科學(xué)可視化的Python庫(kù),它建立在現(xiàn)代圖形處理單元(GPU)上,旨在提供流暢、交互式的數(shù)據(jù)可視化體驗(yàn),本文將深入探討VisPy的基本概念、核心特性以及實(shí)際應(yīng)用場(chǎng)景,并通過(guò)豐富的示例代碼演示其強(qiáng)大的可視化能力2023-12-12
Python爬取三國(guó)演義的實(shí)現(xiàn)方法
這篇文章通過(guò)實(shí)例給大家演示了利用python如何爬取三國(guó)演義,對(duì)于學(xué)習(xí)python的朋友們來(lái)說(shuō)是個(gè)不錯(cuò)的實(shí)例,有需要的朋友可以參考借鑒,下面來(lái)一起看看吧。2016-09-09
python如何解析配置文件并應(yīng)用到項(xiàng)目中
這篇文章主要介紹了python如何解析配置文件并應(yīng)用到項(xiàng)目中,如果我們更換了電腦也可以繼續(xù)使用原來(lái)的文件,只要把里面的數(shù)據(jù)拷貝到游戲執(zhí)行的配置文件里面就可以了,我們重新再進(jìn)入就不用重新設(shè)置內(nèi)掛的配置了,需要的朋友可以參考下2019-06-06
Python range與enumerate函數(shù)區(qū)別解析
這篇文章主要介紹了Python range與enumerate函數(shù)區(qū)別解析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-02-02
基于Python實(shí)現(xiàn)自動(dòng)化文檔整理工具
一個(gè)人可能會(huì)在計(jì)算機(jī)上存儲(chǔ)大量的照片、視頻和文檔文件,這些文件可能散落在不同的文件夾中,難以管理和查找。所以本文就來(lái)用Python制作一個(gè)自動(dòng)化文檔整理工具吧2023-04-04
keras打印loss對(duì)權(quán)重的導(dǎo)數(shù)方式
這篇文章主要介紹了keras打印loss對(duì)權(quán)重的導(dǎo)數(shù)方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-06-06

