转载自:http://www.django-rest-framework.org/tutorial/4-authentication-and-permissions/

Tutorial 4: Authentication & Permissions

Currently our API doesn't have any restrictions on who can edit or delete code snippets. We'd like to have some more advanced behavior in order to make sure that:

  • Code snippets are always associated with a creator.
  • Only authenticated users may create snippets.
  • Only the creator of a snippet may update or delete it.
  • Unauthenticated requests should have full read-only access.

Adding information to our model

We're going to make a couple of changes to our Snippet model class. First, let's add a couple of fields. One of those fields will be used to represent the user who created the code snippet. The other field will be used to store the highlighted HTML representation of the code.

Add the following two fields to the Snippet model in models.py.

  1. owner = models.ForeignKey('auth.User', related_name='snippets', on_delete=models.CASCADE)
  2. highlighted = models.TextField()

We'd also need to make sure that when the model is saved, that we populate the highlighted field, using the pygments code highlighting library.

We'll need some extra imports:

  1. from pygments.lexers import get_lexer_by_name
  2. from pygments.formatters.html import HtmlFormatter
  3. from pygments import highlight

And now we can add a .save() method to our model class:

  1. def save(self, *args, **kwargs):
  2. """
  3. Use the `pygments` library to create a highlighted HTML
  4. representation of the code snippet.
  5. """
  6. lexer = get_lexer_by_name(self.language)
  7. linenos = self.linenos and 'table' or False
  8. options = self.title and {'title': self.title} or {}
  9. formatter = HtmlFormatter(style=self.style, linenos=linenos,
  10. full=True, **options)
  11. self.highlighted = highlight(self.code, lexer, formatter)
  12. super(Snippet, self).save(*args, **kwargs)

When that's all done we'll need to update our database tables. Normally we'd create a database migration in order to do that, but for the purposes of this tutorial, let's just delete the database and start again.

  1. rm -f tmp.db db.sqlite3
  2. rm -r snippets/migrations
  3. python manage.py makemigrations snippets
  4. python manage.py migrate

You might also want to create a few different users, to use for testing the API. The quickest way to do this will be with the createsuperuser command.

  1. python manage.py createsuperuser

Adding endpoints for our User models

Now that we've got some users to work with, we'd better add representations of those users to our API. Creating a new serializer is easy. In serializers.py add:

  1. from django.contrib.auth.models import User
  2. class UserSerializer(serializers.ModelSerializer):
  3. snippets = serializers.PrimaryKeyRelatedField(many=True, queryset=Snippet.objects.all())
  4. class Meta:
  5. model = User
  6. fields = ('id', 'username', 'snippets')

Because 'snippets' is a reverse relationship on the User model, it will not be included by default when using the ModelSerializer class, so we needed to add an explicit field for it.

We'll also add a couple of views to views.py. We'd like to just use read-only views for the user representations, so we'll use the ListAPIView and RetrieveAPIView generic class-based views.

  1. from django.contrib.auth.models import User
  2. class UserList(generics.ListAPIView):
  3. queryset = User.objects.all()
  4. serializer_class = UserSerializer
  5. class UserDetail(generics.RetrieveAPIView):
  6. queryset = User.objects.all()
  7. serializer_class = UserSerializer

Make sure to also import the UserSerializer class

  1. from snippets.serializers import UserSerializer

Finally we need to add those views into the API, by referencing them from the URL conf. Add the following to the patterns in urls.py.

  1. url(r'^users/$', views.UserList.as_view()),
  2. url(r'^users/(?P<pk>[0-9]+)/$', views.UserDetail.as_view()),

Associating Snippets with Users

Right now, if we created a code snippet, there'd be no way of associating the user that created the snippet, with the snippet instance. The user isn't sent as part of the serialized representation, but is instead a property of the incoming request.

The way we deal with that is by overriding a .perform_create() method on our snippet views, that allows us to modify how the instance save is managed, and handle any information that is implicit in the incoming request or requested URL.

On the SnippetList view class, add the following method:

  1. def perform_create(self, serializer):
  2. serializer.save(owner=self.request.user)

The create() method of our serializer will now be passed an additional 'owner' field, along with the validated data from the request.

Updating our serializer

Now that snippets are associated with the user that created them, let's update our SnippetSerializer to reflect that. Add the following field to the serializer definition in serializers.py:

  1. owner = serializers.ReadOnlyField(source='owner.username')

Note: Make sure you also add 'owner', to the list of fields in the inner Meta class.

This field is doing something quite interesting. The source argument controls which attribute is used to populate a field, and can point at any attribute on the serialized instance. It can also take the dotted notation shown above, in which case it will traverse the given attributes, in a similar way as it is used with Django's template language.

The field we've added is the untyped ReadOnlyField class, in contrast to the other typed fields, such as CharFieldBooleanField etc... The untyped ReadOnlyField is always read-only, and will be used for serialized representations, but will not be used for updating model instances when they are deserialized. We could have also used CharField(read_only=True)here.

Adding required permissions to views

Now that code snippets are associated with users, we want to make sure that only authenticated users are able to create, update and delete code snippets.

REST framework includes a number of permission classes that we can use to restrict who can access a given view. In this case the one we're looking for is IsAuthenticatedOrReadOnly, which will ensure that authenticated requests get read-write access, and unauthenticated requests get read-only access.

First add the following import in the views module

  1. from rest_framework import permissions

Then, add the following property to both the SnippetList and SnippetDetail view classes.

  1. permission_classes = (permissions.IsAuthenticatedOrReadOnly,)

Adding login to the Browsable API

If you open a browser and navigate to the browsable API at the moment, you'll find that you're no longer able to create new code snippets. In order to do so we'd need to be able to login as a user.

We can add a login view for use with the browsable API, by editing the URLconf in our project-level urls.py file.

Add the following import at the top of the file:

  1. from django.conf.urls import include

And, at the end of the file, add a pattern to include the login and logout views for the browsable API.

  1. urlpatterns += [
  2. url(r'^api-auth/', include('rest_framework.urls',
  3. namespace='rest_framework')),
  4. ]

The r'^api-auth/' part of pattern can actually be whatever URL you want to use. The only restriction is that the included urls must use the 'rest_framework' namespace. In Django 1.9+, REST framework will set the namespace, so you may leave it out.

Now if you open up the browser again and refresh the page you'll see a 'Login' link in the top right of the page. If you log in as one of the users you created earlier, you'll be able to create code snippets again.

Once you've created a few code snippets, navigate to the '/users/' endpoint, and notice that the representation includes a list of the snippet ids that are associated with each user, in each user's 'snippets' field.

Object level permissions

Really we'd like all code snippets to be visible to anyone, but also make sure that only the user that created a code snippet is able to update or delete it.

To do that we're going to need to create a custom permission.

In the snippets app, create a new file, permissions.py

  1. from rest_framework import permissions
  2. class IsOwnerOrReadOnly(permissions.BasePermission):
  3. """
  4. Custom permission to only allow owners of an object to edit it.
  5. """
  6. def has_object_permission(self, request, view, obj):
  7. # Read permissions are allowed to any request,
  8. # so we'll always allow GET, HEAD or OPTIONS requests.
  9. if request.method in permissions.SAFE_METHODS:
  10. return True
  11. # Write permissions are only allowed to the owner of the snippet.
  12. return obj.owner == request.user

Now we can add that custom permission to our snippet instance endpoint, by editing the permission_classes property on the SnippetDetail view class:

  1. permission_classes = (permissions.IsAuthenticatedOrReadOnly,
  2. IsOwnerOrReadOnly,)

Make sure to also import the IsOwnerOrReadOnly class.

  1. from snippets.permissions import IsOwnerOrReadOnly

Now, if you open a browser again, you find that the 'DELETE' and 'PUT' actions only appear on a snippet instance endpoint if you're logged in as the same user that created the code snippet.

Authenticating with the API

Because we now have a set of permissions on the API, we need to authenticate our requests to it if we want to edit any snippets. We haven't set up any authentication classes, so the defaults are currently applied, which are SessionAuthentication and BasicAuthentication.

When we interact with the API through the web browser, we can login, and the browser session will then provide the required authentication for the requests.

If we're interacting with the API programmatically we need to explicitly provide the authentication credentials on each request.

If we try to create a snippet without authenticating, we'll get an error:

  1. http POST http://127.0.0.1:8000/snippets/ code="print 123"
  2. {
  3. "detail": "Authentication credentials were not provided."
  4. }

We can make a successful request by including the username and password of one of the users we created earlier.

  1. http -a tom:password123 POST http://127.0.0.1:8000/snippets/ code="print 789"
  2. {
  3. "id": 1,
  4. "owner": "tom",
  5. "title": "foo",
  6. "code": "print 789",
  7. "linenos": false,
  8. "language": "python",
  9. "style": "friendly"
  10. }

Summary

We've now got a fairly fine-grained set of permissions on our Web API, and end points for users of the system and for the code snippets that they have created.

In part 5 of the tutorial we'll look at how we can tie everything together by creating an HTML endpoint for our highlighted snippets, and improve the cohesion of our API by using hyperlinking for the relationships within the system.

Tutorial 4: Authentication & Permissions的更多相关文章

  1. 04_Tutorial 4: Authentication & Permissions 认证和权限

    1.认证和权限 0.文档 https://www.django-rest-framework.org/tutorial/4-authentication-and-permissions/ https: ...

  2. django Rest Framework----认证/访问权限控制/访问频率限制 执行流程 Authentication/Permissions/Throttling 源码分析

    url: url(r'books/$',views.BookView.as_view({'get':'list','post':'create'})) 为例 当django启动的时候,会调用执行vie ...

  3. 06_Tutorial 6: ViewSets & Routers 视图集与路由器

    1.Tutorial 6: ViewSets & Routers 视图集与路由器 0.文档 https://q1mi.github.io/Django-REST-framework-docum ...

  4. 05_Tutorial 5: Relationships & Hyperlinked APIs 关系和超链接

    1.关系和超链接 0.文档 https://www.django-rest-framework.org/tutorial/5-relationships-and-hyperlinked-apis/ h ...

  5. JWT Authentication Tutorial: An example using Spring Boot--转

    原文地址:http://www.svlada.com/jwt-token-authentication-with-spring-boot/ Table of contents: Introductio ...

  6. java Permissions and Security Policy--官方文档

    3 Permissions and Security Policy 3.1 The Permission Classes The permission classes represent access ...

  7. django-rest-framework快速入门

    前言:第一次接触django-rest-framework是在实习的时候.当时也不懂,看到视图用类方法写的感觉很牛逼的样子.因为官网是英文的,这对我的学习还是有一点的阻力的,所以当时也没怎么学.真是太 ...

  8. django rest framework 详解

    Django REST framework 是用于构建Web API 的强大而灵活的工具包. 我们可能想使用REST框架的一些原因: Web浏览API对于开发人员来说是一个巨大的可用性. 认证策略包括 ...

  9. Bluetooth ATT介绍

    目录 1 介绍 2 详细内容 2.1 Attribute Type 2.2 Attribute Handle 2.3 Attribute Handle Grouping 2.4 Attribute V ...

随机推荐

  1. Probability|Given UVA - 11181(条件概率)

    题目大意:n个人去购物,要求只有r个人买东西.给你n个人每个人买东西的概率,然后要你求出这n个人中有r个人购物并且其中一个人是ni的概率pi. 类似于5个人中 抽出三个人  其中甲是这三个人中的一个的 ...

  2. 飞舞的蝴蝶(GraphicsView框架)

    飞舞的蝴蝶(GraphicsView框架) 一.简介 GraphicsView框架结构主要包含三个主要的类QGraphicsScene(容器).QGraphicsView(视图).QGraphicsI ...

  3. IOS中手势UIGestureRecognizer

    通常在对视图进行缩放移动等操作的时候我们可以用UIScrollView,因为它里边自带了这些功能,我们要做的就是告诉UIScrollView的几个相关参数就可以了 但是没有实现旋转的手势即UIRota ...

  4. linux内核分析 第二周 操作系统是如何工作的

    银雪纯 原创作品转载请注明出处 <Linux内核分析>MOOC课程http://mooc.study.163.com/course/USTC-1000029000 一.计算机是如何工作的 ...

  5. AtCoder Regular Contest 086 E - Smuggling Marbles(树形迭屁)

    好强的题. 方案不好算,改成算概率,注意因为是模意义下的概率所以直接乘法逆元就好不要傻傻地开double. 设$f[i][d][0]$为第i个节点离d层的球球走到第i个点时第i个点没有球的概率, $f ...

  6. 图像处理之Canny边缘检测

    http://blog.csdn.net/jia20003/article/details/41173767 图像处理之Canny 边缘检测 一:历史 Canny边缘检测算法是1986年有John F ...

  7. Codeforces 449.C Jzzhu and Apples

    C. Jzzhu and Apples time limit per test 1 second memory limit per test 256 megabytes input standard ...

  8. CSUST 四月选拔赛个人题解

    这场比赛演的逼真,感谢队友不杀之恩 总结:卡题了赶紧换,手上捏着的题尽快上机解决 http://csustacm.com:4803/ 1113~1122 1113:六学家 题意:找出满足ai+aj=a ...

  9. 正则(?is)

    Q:经常看见的正则前面的 (?i) (?s) (?m) (?is) (?im) 是什么意思?A: 称为内联匹配模式,通常用内联匹配模式代替使用枚举值RegexOptions指定的全局匹配模式,写起来更 ...

  10. 驱动学习5: zynq实现点亮led

    驱动代码: #include <linux/module.h> #include <linux/kernel.h> #include <linux/fs.h> #i ...