老师您这里讲到AuthmiddlewareStack能够识别session,cookies,那像前后端分离中的jwttoken应该如何兼容呢
来源:9-12 Channels的路由Routing开发
李嘉图principal
2019-08-26
老师您这里讲到AuthmiddlewareStack能够识别session,cookies,那像前后端分离中的jwttoken应该如何兼容呢
2回答
-
channels 2中的AuthMiddleware仅支持标准的Django认证,要兼容其它的认证方式(比如JWT)可以自定义中间件实现。
后端定义TokenAuthMiddlewareStack
class TokenAuthMiddleware(object):
""" Token authorization middleware for Django Channels 2"""
def __init__(self, inner):
self.inner = inner
def __call__(self, scope):
headers = dict(scope['headers'])
if 'authorization' in headers:
try:
token_name, token_key = headers['authorization'].decode().split()
if token_name == 'Token':
token = Token.objects.get(key=token_key)
scope['user'] = token.user
except Token.DoesNotExist:
scope['user'] = AnonymousUser()
return self.inner(scope)
TokenAuthMiddlewareStack = lambda inner: TokenAuthMiddleware(AuthMiddlewareStack(inner))然后替换routings.py中的AuthMiddlewareStack
客户端POST示例URL:
https://api2.scaledrone.com/[channel_id]/[room_name]/publish
Data:
{"hello": "from REST, now with Auth!"}Headers:
Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1xxxb0Vo042019-08-30 -
慕粉0036235932
2019-08-26
同问,在网上找了几个,感觉都用不起来,有些问题,求前后分离的jwttoken装饰器的demo
012019-08-27
相似问题