How can I add IsAdminUser permissions to /o/applications/* views in Django OAuth Toolkit?
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAdminUser',
)
}
in my settings.py doesn't work with Django OAuth Toolkit views, also I modify ApplicationList in my view.py doesn't work:
class ApplicationList:
permission_classes = (permissions.IsAdminUser,)
I'm kind of newby to Django and Python so I will be glad for your help
Related
I want to create global authentication with middleware django restframework which check every request user authenticate or not.
I don't want to add code on every view class like this
#permission_classes([IsAuthenticated])
class UserProfile(APIView):
You just need to set the permissions policy for DRF in your settings.py file. Here the Docs
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.IsAuthenticated',
]
}
I'm having problem with Django REST Swagger. I've created a simple viewset for users using DRF (just for showing my problem), where AppUser is my custom user model and it is not showing the POST method in my documentation, but I can call it with Postman and create a new resource.
I'm using:
Django 2.1
Django-rest-swagger 2.2.0
Djangorestframework 3.9.1
Here is my code:
views.py
class UserViewSet(viewsets.ModelViewSet):
queryset = AppUser.objects.all()
serializer_class = UserSerializer
serializers.py
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = AppUser
fields = '__all__'
urls.py
from django.conf.urls import url, include
from rest_framework.routers import SimpleRouter
from rest_framework_swagger.views import get_swagger_view
import app.views as app
# creating router
router = SimpleRouter()
router.register(r'users', app.UserViewSet)
schema_view = get_swagger_view(title='My app API')
# register urls
urlpatterns = [
url(r'^', include(router.urls)),
url(r'^docs', schema_view)
]
Here you can see what my app documentation looks like:
I would like to get something like this:
I've tried multiple tutorials on creating Swagger documentation and I was trying it on User model, but I still get only the GET request. What am I doing wrong?
Thank you for your help.
I've figured it out. I haven't been logged in properly so I haven't been authenticated against permissions listed in DEFAULT_PERMISSION_CLASSES setting for DRF in settings.py.
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES':
('rest_framework.permissions.IsAuthenticatedOrReadOnly',),
}
HTTP methods POST, PUT, PATCH, etc. are checked using has_permission() against list of permissions defined there.
After logging in it works well.
EDIT: Problem with login was, that Django-rest-swagger 2.2.0 is not working correctly with JWT authentication, so I downgraded to 2.1.2.
I am currently documenting the API I have created for an app.
I'm using the built in documentation system that comes with Django Rest Framework and coreapi (as described here).
class MyAPI(APIView):
schema = ManualSchema(fields=[coreapi.Field(...), ...],
description='Describe this view')
I set up the url for the docs in the urls.py for the API app:
url_patterns = [
url(r'^docs/', include_docs_urls('My API Title')),
...
]
The problem I have is that when I visit the docs I see the admin API docs alongside my API docs.
I've tried using the answer to this question:
REST_FRAMEWORK = {
'DEFAULT_RENDERER_CLASSES': (
'rest_framework.renderers.JSONRenderer',
)
}
But the admin docs still show up.
Is there a way to hide the admin docs?
I have a custom user model as follows in account/models.py
from django.contrib.auth.modles import AbstractUser
from django.db.models.signals import post_save
from rest_framework.authtoken.models import Token
from django.db import models
from django.dispatch import receiver
from django.conf import settings
#receiver(post_save, sender=settings.AUTH_USER_MODEL)
def create_auth_token(sender, instance=None, created=False, **kwargs):
if created:
Token.objects.create(user=instance)
class UserProfile(AbstractUser):
gender = models.CharField(max_length=1,default='')
and in settings.py
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.TokenAuthentication',
)
}
...
AUTH_USER_MODEL = "account.UserProfile"
However, whenever I try to log into the browsable API, it asks me to use a correct username and password, and I am using credentials of users who are both marked as superusers and staff.
The manage.py runserver console shows this status message:
[27/Jul/2016 20:41:39] "POST /api-auth/login/ HTTP/1.1" 200 2897
I've ran into this before too and from what I remember it's because the built-in DRF auth form is not using TokenAuthentication, but rather SessionAuthentication. Try adding rest_framework.authentication.SessionAuthentication to your DEFAULT_AUTHENTICATION_CLASSES tuple
Django Rest Framework "Login to browsable API" uses session authentication rather than token authentication. To add login to the browsable API follow the steps below:
Step 1 : Add the following in the 'urls.py' file in your project.
from django.urls import path, include
urlpatterns += [path('api-auth/', include('rest_framework.urls')),]
Step 2 : You have added only TokenAuthentication in 'DEFAULT_AUTHENTICATION_CLASSES', you need to add sessionAuthentication as well. Change your code as below:
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.TokenAuthentication',
'rest_framework.authentication.SessionAuthentication'
),
Now both your Token authentication for your custom authentication, and Session Authentication for Browsable API will work.
I have this custom user model:
class CustomUser(AbstractBaseUser,PermissionsMixin):
email = models.CharField(max_length=255, unique=True)
....
And this view that is supossed to require authentication in order to run:
#authentication_classes((TokenAuthentication,))
#permission_classes((IsAuthenticated,))
def test_view(request):
return HttpResponse("Allowed")
When i launch the url for this, it will always run no matter if i provide credentials or not in my authorization header. My guess is that rest framework is using django's default user model, since the request.user object contains an AnonymousUser instance. But i have checked the database, and the authtoken table is referencing my custom user table.
I thoguht that this should be as simple as my code is, but i guess im missing something. Any ideas?
Edit: here are more details:
settings.py:
INSTALLED_APPS = (
'myapps',
...
'django.contrib.auth', #should this be enabled?
...
'rest_framework.authtoken'
)
...
#I think this is unnecesary since i use per-view decorators, but...
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.TokenAuthentication',
)
}
AUTH_USER_MODEL = 'users.CustomUser'
urls.py:
urlpatterns = patterns('',
...
url(r'^test', test_view, name='test'),
...
)
just add #api_view(['GET']) decorator to your view like
from rest_framework.decorators import api_view
#api_view(['GET'])
#authentication_classes((TokenAuthentication,))
#permission_classes((IsAuthenticated,))
def test_view(request):
return HttpResponse("Allowed")
Add the following to settings.py
If you're using DRF token Auth:
INSTALLED_APPS = (
...
'rest_framework.authtoken'
)
If you're using JWT Auth:
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
),
...
}