Django permissions.IsAuthenticated can check on middleware - python

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',
]
}

Related

Is there a way to login in django rest api in browser without UI?

I'm doing backend project in which I need to do an API without any UI. In this API there's no registration (only by admin UI), but I need a way to log in, because I need some "pages" to be only for logged in users.
I set up token authentication, each user has their token created.
Is there a simple way to make some login "form" with serializer? I mean "page" in which there is only two fields (for username and password) and ability to POST this to get authenticated and then go back to "login only pages"?
I recommend to try DjangoREST browsable API: https://www.django-rest-framework.org/topics/browsable-api/. It is included into DRF, so you do not need to install any extras. In order to use the browsable API, just type the endpoint url into your browser. If you are using ModelSerializers, then forms for data input will be generated automatically, otherwise you will have to enter data as a JSON.
add to settings.py
REST_FRAMEWORK = {
'DEFAULT_PARSER_CLASSES': (
'rest_framework.parsers.JSONParser',
'rest_framework.parsers.FormParser',
'rest_framework.parsers.MultiPartParser'
),
'DEFAULT_RENDERER_CLASSES': (
'rest_framework.renderers.JSONRenderer',
'rest_framework.renderers.BrowsableAPIRenderer',
),
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.SessionAuthentication',
),
}
add to urls.py
urlpatterns = [
...
path('api-auth/', include('rest_framework.urls', namespace='rest_framework')),
...
]

how to change permissions for current view overriding the DEFAULT_PERMISSION_CLASSES in django rest-framework

how to change permissions for current view overriding the DEFAULT_PERMISSION_CLASSES in django rest-framework
Here is how i set my defaultpermissions in my settings.py :
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.TokenAuthentication', # <-- And here
],
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.IsAuthenticated',
]
}
and i need to use AllowAny on the signUp method :
#permission_classes([AllowAny,])
#api_view(["POST", ])
def add_new_user(request):
if request.method == "POST":
lang = request.data["lang"]
..........
.........
.......
Still, it returns Authentication credentials were not provided. .. I mainly need to have permissions with a token with every request but not the register and login request. how to do it ??
A Way to do that is using Object Level Permissions in Django.
You just setup as normally in settings.py and add manually a permission into every class view.
For me is the best way to do it. Normally will be Views witch is are Admin only, Authenticated or just Open.
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.TokenAuthentication',
],
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.DjangoObjectPermissions',#Object Level Permission
]
}
After set this line into your settings.py just follow adding a permission_classes into view. Like:
class LoginUser(APIView):
permission_classes = [AllowAny, ]
...
References
DjangoObjectPermissions
Django Class Based Views
Here is how I solved this :
in my settings.py i added both permissions classes
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.TokenAuthentication', # <-- And here
],
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.IsAuthenticated', #both are mentioned
'rest_framework.permissions.AllowAny',
]
}
and in my view, I had to move the permission dictator to be the last thing before the view itself.
#api_view(["POST", ])
#permission_classes([AllowAny])
def login_user(request):
if request.method == "POST":
lang = request.data["lang"]
...

Django Rest - CSRF Failed: CSRF token missing or incorrect

Got a weird scenario. I am on the Django Rest browser api with a logged in user.
When I update it is okay. But when I try to create a user, this error shows:
CSRF Failed: CSRF token missing or incorrect.
it also auto logged out me every single time.
In views.py, I already have added
permission_classes = (permissions.IsAuthenticatedOrReadOnly,)
Still same error and scenario.
In my settings.py:
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.SessionAuthentication',
),
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.AllowAny',
],
}
Anyone experienced this?

Django rest framework not authenticating custom user model

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',
),
...
}

Secure creation of new applications in Django OAuth Toolkit

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

Categories

Resources