[英]Can I mix sessions auth and token auth in one site?
I have django application using sessions auth. 我有使用会话身份验证的Django应用程序。 I need to add API part.
我需要添加API部分。 This API will be used by my app.users only (web browsers and mobiles devices as well).
该API仅由我的app.users(也包括Web浏览器和移动设备)使用。 I would prefer to use token auth for API as it seems more robust.
我希望对API使用令牌身份验证,因为它似乎更可靠。 I found rest_framework_jwt that can handle it.
我发现rest_framework_jwt可以处理它。 My question: Can I mix sessions auth for web and token auth for API in one site without problems?
我的问题:我可以在一个站点中混合使用针对Web的会话身份验证和针对API的令牌身份验证吗? I think about the web app and the API app as two different applications.
我认为Web应用程序和API应用程序是两个不同的应用程序。 So I want to separate them in my project, use different subdomain and use different kind of auth for each.
所以我想在我的项目中将它们分开,使用不同的子域,并为每个使用不同的身份验证。 Is it possible to separate auth by subdomain?
是否可以按子域分隔身份验证? I would like to send token when user log in to web app.
我想在用户登录Web应用程序时发送令牌。 Is it good idea?
好主意吗?
As you see in the documentation , you can configure multiple authentication backends without any problems. 如您在文档中所见,您可以配置多个身份验证后端,而不会出现任何问题。 DRF will just try each one of the backends until one says "ok".
DRF只会尝试每个后端,直到有人说“确定”为止。
One thing to keep in mind: If you (for example) provide an invalid JSON-Web-Token then the authentication will immediately fail and other backends will not be tried. 要记住的一件事:如果(例如)提供无效的JSON-Web-Token,则认证将立即失败,并且将不尝试其他后端。 Good to see in the source of rest_framework_jwt .
很高兴在rest_framework_jwt的源代码中看到 。
def authenticate(self, request):
"""
Returns a two-tuple of `User` and token if a valid signature has been
supplied using JWT-based authentication. Otherwise returns `None`.
"""
auth = get_authorization_header(request).split()
if not auth or auth[0].lower() != b'jwt':
return None
if len(auth) == 1:
msg = 'Invalid JWT header. No credentials provided.'
raise exceptions.AuthenticationFailed(msg)
elif len(auth) > 2:
msg = ('Invalid JWT header. Credentials string '
'should not contain spaces.')
raise exceptions.AuthenticationFailed(msg)
try:
payload = jwt_decode_handler(auth[1])
except jwt.ExpiredSignature:
msg = 'Signature has expired.'
raise exceptions.AuthenticationFailed(msg)
except jwt.DecodeError:
msg = 'Error decoding signature.'
raise exceptions.AuthenticationFailed(msg)
user = self.authenticate_credentials(payload)
return (user, auth[1])
return None
means the backend saying: "this is not JWT, let the others try return None
表示后端说:“这不是JWT,让其他人尝试 raise exceptions.AuthenticationFailed(msg)
means: "the user tried JWT, but the he failed it." raise exceptions.AuthenticationFailed(msg)
意思是:“用户尝试了JWT,但他失败了。” To answer the further questions: 要回答其他问题:
View
or ViewSet
. View
或ViewSet
覆盖它们。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.