跳转到主要内容

为Tastypie API提供OAuth服务

项目描述

django-tastypie-oauth
=====================

[![构建状态](https://travis-ci.org/orcasgit/django-tastypie-oauth.svg?branch=master)](https://travis-ci.org/orcasgit/django-tastypie-oauth) [![覆盖率状态](https://coveralls.io/repos/orcasgit/django-tastypie-oauth/badge.png?branch=master)](https://coveralls.io/r/orcasgit/django-tastypie-oauth?branch=master) [![需求状态](https://requires.io/github/orcasgit/django-tastypie-oauth/requirements.png?branch=master)](https://requires.io/github/orcasgit/django-tastypie-oauth/requirements/?branch=master)

为Tastypie API提供OAuth服务

依赖项
============
此库与两个不同的OAuth提供商一起工作,您必须安装其中之一
- django-oauth-toolkit: https://github.com/evonove/django-oauth-toolkit
- django-oauth2-provider: https://github.com/caffeinehit/django-oauth2-provider

在继续之前,设置这些库之一

用法
=====

1. 将`tastypie_oauth`添加到Django中的`INSTALLED_APPS`。
2. 在Django设置中指定`OAUTH_ACCESS_TOKEN_MODEL`。此时,对于django-oauth-toolkit可以是`'oauth2_provider.models.AccessToken'`,对于django-oauth2-provider可以是`'provider.oauth2.models.AccessToken'`。
3. 在创建Tastypie资源时,使用`OAuth20Authentication`如下所示

```python
# mysite/polls/api.py
from tastypie.resources import ModelResource
from tastypie.authorization import DjangoAuthorization
from polls.models import Poll, Choice
from tastypie import fields
from tastypie_oauth.authentication import OAuth20Authentication

class ChoiceResource(ModelResource)
class Meta
queryset = Choice.objects.all()
resource_name = 'choice'
authorization = DjangoAuthorization()
authentication = OAuth20Authentication()

class PollResource(ModelResource)
choices = fields.ToManyField(ChoiceResource, 'choice_set', full=True)
class Meta
queryset = Poll.objects.all()
resource_name = 'poll'
authorization = DjangoAuthorization()
authentication = OAuth20Authentication()
```
或者,如果您想使用范围认证,请使用`OAuth2ScopedAuthentication`类
```python
from tastypie_oauth.authentication import OAuth20ScopedAuthentication

# 使用 Django-oauth-toolkit
class ChoiceResource(ModelResource)
poll = fields.ToOneField("polls.api.PollResource", "poll", full=False)
class Meta
resource_name = 'choice'
queryset = Choice.objects.all()
authorization = DjangoAuthorization()
authentication = OAuth2ScopedAuthentication(
post=("read write",),
get=("read",),
put=("read","write")
)
```
```python
from provider.constants import READ, WRITE, READ_WRITE
from tastypie_oauth.authentication import OAuth20ScopedAuthentication

# 使用 Django-oauth2-provider
class ChoiceResource(ModelResource)
poll = fields.ToOneField("polls.api.PollResource", "poll", full=False)
class Meta
resource_name = 'choice'
queryset = Choice.objects.all()
authorization = DjangoAuthorization()
authentication = OAuth2ScopedAuthentication(
post=(READ_WRITE,),
get=(READ,),
put=(READ,WRITE)
)
```
4. 在用户授权并获得访问令牌后,您可以几乎像以前一样使用API,只需进行一个小的更改。您必须添加一个`oauth_consumer_key` GET或POST参数,其值为访问令牌,或者将访问令牌放入“Authorization”头中。

支持者