我用 django + sweetpie 和 iOS 的 Facebook 登录做了类似的事情。
验证
使用您将使用的任何方式登录用户,获取access_token。
创建一个 GET 请求 sweetpie 端点,您将把 accesstoken 作为查询字符串传递给该端点。
- 在服务器端验证等...然后创建您自己的内部“tastypie”令牌并在对 get 请求的响应中返回它,例如:
class GetToken(ModelResource):
"""
Authenticates the user via facebook and returns an APIToken for them.
"""
class Meta(object):
queryset = ApiKey.objects.all()
resource_name = 'authenticate'
fields = ['user', 'key']
allowed_methods = ['get']
authorization = Authorization()
authentication = FacebookAuthentication()
def prepend_urls(self):
"""We override this to change default behavior
for the API when using GET to actually "create" a resource,
in this case a new session/token."""
return [
url(r"^(?P<resource_name>%s)%s$" % (self._meta.resource_name, trailing_slash()),
self.wrap_view('_create_token'), name="api_get_token"),
]
def _create_token(self, request, **kwargs):
"""Validate using FacebookAuthentication, and create Api Token if authenticated"""
self.method_check(request, allowed=['get'])
# This checks that the user is authenticated on facebook and also creates the user
# if they have not been created.
self.is_authenticated(request)
self.throttle_check(request)
bundle = self.build_bundle(obj=None, request=request)
bundle = self.obj_create(bundle, request, **kwargs)
bundle = self.full_dehydrate(bundle)
self.log_throttled_access(request)
return self.create_response(request, bundle.data)
def obj_create(self, bundle, request=None, **kwargs):
"""Create a new token for the session"""
bundle.obj, created = ApiKey.objects.get_or_create(user=request.user)
return bundle
在所有后续调用中传递返回的 API 密钥,可以再次作为查询字符串参数,也可以在每次调用的 Authorization 标头上设置它。
确保您想要对其进行身份验证的所有ApiKeyAuthentication()
其他资源都已在 Meta.xml 中设置。
class ThingResource(ModelResource):
class Meta:
queryset = Thing.objects.all()
resource_name = 'thing'
authentication = ApiKeyAuthentication()
授权
所以现在你在服务器端知道用户就是他们所说的那个用户,这个用户可以做什么?这就是授权元的全部内容。
您可能需要Django 授权,在这种情况下,您可以只为用户使用正常的权限方案,或者您可以自己滚动。这很简单。