我想开发一个基于Django的Web服务,我的Web应用程序(Platform:Angular JS)和移动应用程序(Platform:iOS,android,Windows Phone)将与之通信。 我的django Web服务应用程序仅用于处理API调用。出于安全原因,我为移动应用程序选择了Oauth工具包,用于Web会话身份验证吗?
身份验证的Settings.py,
hreflang
需要你的帮助!!
答案 0 :(得分:0)
您可以使用django-mobile
库来检测来自移动浏览器的请求,然后调用不同的身份验证类。
django-mobile
库定义了MobileDetectionMiddleware
和SetFlavourMiddleware
个中间件类。
MobileDetectionMiddleware
检测请求是来自移动设备还是网络浏览器。
SetFlavourMiddleware
类在请求中设置flavour
属性。 flavour
有两个可能的值:
'mobile' # Mobile requests
'full' # Web requests
在中间件以某种方式选择了正确的风格后,它被分配到request.flavour
属性。
步骤1:在您的应用中配置django-mobile
按照https://github.com/gregmuellegger/django-mobile#installation中的步骤在您的应用中安装和配置django-mobile
。
配置完成后,您只需使用request.flavour
检查请求是来自移动浏览器还是网络浏览器。
第2步:创建自定义WebSessionAuthentication
类
由于您希望将OAuth的OAuth2Authentication
用于移动应用,DRF的SessionAuthentication
用于网络,因此我们可以创建一个自定义WebSessionAuthentication
类,该类将继承自DRF' SessionAuthentication
。
此WebSessionAuthentication
类不会对移动请求执行任何身份验证。如果是Web请求,它将使用CSRF检查执行正确的会话身份验证。
from rest_framework.authentication import SessionAuthentication
class WebSessionAuthentication(SessionAuthentication):
"""
Performs session authentication for web requests
"""
def authenticate(self, request):
"""
Returns a `User` if the request session currently has a logged in user
and request is a web request
Otherwise returns `None`.
"""
underlying_request = request._request # get the underlying HttpRequest object
if underlying_request.flavour == 'mobile': # check if mobile request
return None # No authentication performed for mobile requests
# For web requests perform DRF's original session authentication
return super(WebSessionAuthentication, self).authenticate(request)
第3步:创建自定义MobileOAuth2Authentication
类
MobileOAuth2Authentication
类仅对mobile
个请求执行身份验证,即.flavour
为mobile
。不对web
请求执行身份验证。
from oauth2_provider.ext.rest_framework import OAuth2Authentication
class MobileOAuth2Authentication(OAuth2Authentication):
"""
Performs outh2 authentication for mobile requests
"""
def authenticate(self, request):
"""
Returns two-tuple of (user, token) if mobile authentication succeeds,
or None otherwise.
"""
underlying_request = request._request # get the underlying HttpRequest object
if underlying_request.flavour == 'full': # check if web request
return None # No authentication performed for web requests
# For mobile requests perform OAuth2's original authentication
return super(MobileOAuth2Authentication, self).authenticate(request)
步骤4:在设置中定义您的身份验证类
创建自定义WebSessionAuthentication
和MobileOuth2Authentication
身份验证类后,请在项目设置中定义这些身份验证类。
'DEFAULT_AUTHENTICATION_CLASSES': (
'my_app.authentication.WebSessionAuthentication', # custom session authentication class for web requests
'my_app.authentication.MobileOAuth2Authentication', # custom oauth2 authentication class for mobile requests
),