How to use both simple jwt token authentication and BasicAuthentication? - django

I have an DRF api and I have implemented the simplejwt authentication system. It works well. It is usefull when I want to connect my api from external script (I don't need to store credential and just use the token).
However I also want to be able to use the DRF interface login when i reach my api from browser so I have implemented also the Basic and SessionAuthentication. Is it the good way to do that ?
in my settings.py
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework_simplejwt.authentication.JWTAuthentication',
'rest_framework.authentication.BasicAuthentication',
'rest_framework.authentication.SessionAuthentication',
]
}
SIMPLE_JWT = {
'ACCESS_TOKEN_LIFETIME': timedelta(days=1),
}
in my api views.py
from rest_framework.permissions import IsAuthenticated
from rest_framework.authentication import SessionAuthentication, BasicAuthentication
from rest_framework.decorators import permission_classes, authentication_classes
# Create your views here.
#api_view(['GET'])
##authentication_classes([SessionAuthentication, BasicAuthentication])
#permission_classes([IsAuthenticated])
def get_all(request):
# as a token is used, the user with this token is know in the requets
user = request.user
# show only mesures of user having the token provided
mesures = Mesure.objects.filter(user_id=user.id)
serializer = MesureSerializer(mesures, many=True)
return Response(serializer.data)
In my urls.py
from rest_framework_simplejwt.views import TokenObtainPairView, TokenRefreshView
urlpatterns = [
path('mesures/', views.get_all),
path('mesure-add/', views.add_mesure),
path('token/', TokenObtainPairView.as_view(), name='obtain_tokens'),
path('token/refresh/', TokenRefreshView.as_view(), name='refresh_token'),
path('api-auth/', include('rest_framework.urls'))
]
As you can see I had to comment the #authentication_classes decorator to make it work for both with token and login. Do you believe this is a good way to proceed ?

You should be fine with this because as per the DRF documentation -
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.
Source: Authenticating with the API
Ref: Line 109: rest_framework/views.py and Line 40: rest_framework/settings.py

Related

Integrating Django REST Framework and Django OAuth Toolkit Authentication

I have followed through the documentation on how to integrate both the REST framework and OAuth Toolkit, but when I run a request with a token I receive:
{"detail":"Authentication credentials were not provided."}
Here are my REST settings:
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'oauth2_provider.contrib.rest_framework.OAuth2Authentication',
'rest_framework.authentication.SessionAuthentication',
'rest_framework.authentication.TokenAuthentication',
),
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
'DEFAULT_PERMISSION_CLASSES': ('rest_framework.permissions.IsAuthenticated',),
'PAGE_SIZE': 20
}
An example view:
from django.contrib.auth.models import Group
from rest_framework import permissions, viewsets
from oauth2_provider.contrib.rest_framework import TokenHasScope, OAuth2Authentication
from data_commons_security.security.models import Permission, Profile, Role, User
from data_commons_security.security.serializers import (
GroupSerializer,
)
class GroupViewSet(viewsets.ReadOnlyModelViewSet):
authentication_classes = [OAuth2Authentication]
queryset = Group.objects.all()
serializer_class = GroupSerializer
permission_classes = [TokenHasScope]
required_scopes = ['read', 'groups']
And I do have 'oauth2_provider' in my INSTALLED_APPS. I'm able to request and receive tokens without issue. It's only when I use them that I get the above error.

using django permissions.IsAuthenticatedOrReadOnly with token authentication

I have this Django API view that I want to allow authorized and unauthorized users access it, I have set Django token-authentication as the default authentication class, however, whenever I try to access the view as unauthenticated user,I get error Unauthorized: which is weird coz am making a get request in the view
my code is here
#api_view(['GET'])
#permission_classes([permissions.IsAuthenticatedOrReadOnly])
def all_Search(request):
print(request.headers)
src = request.GET.get('q')
my settings for rest framework is
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.TokenAuthentication',
'rest_framework.authentication.SessionAuthentication',
]
}
is there a way to work around this? will appreciate any help, thanks
I've tried to reproduce your error but I failed.
This is my configuration:
settings.py
INSTALLED_APPS = [
...
'rest_framework',
'rest_framework.authtoken'
]
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.TokenAuthentication',
'rest_framework.authentication.SessionAuthentication',
]
}
urls.py
urlpatterns = [
path('search/', api.all_search, name="search")
]
api.py
from rest_framework import permissions
from rest_framework.decorators import api_view, permission_classes
from rest_framework.response import Response
#api_view(['GET'])
#permission_classes([permissions.IsAuthenticatedOrReadOnly])
def all_Search(request):
print(request.headers)
src = request.GET.get('q')
return Response()
test.py
from rest_framework import status
from rest_framework.test import APILiveServerTestCase
from rest_framework.reverse import reverse
class TestTokenAuthorization(APILiveServerTestCase):
def test_can_search_without_token(self):
url = reverse('search', kwargs={})
response = self.client.get(url, {}, format='json')
self.assertEqual(response.status_code, status.HTTP_200_OK)
and this is the result of the test:
Creating test database for alias 'default'...
System check identified no issues (0 silenced).
{'Cookie': '', 'Content-Type': 'application/octet-stream'}
Destroying test database for alias 'default'...
I'm using djangorestframework==3.10.3 and python3.7
As you can see, I didn't authenticate the request (no token is passed) and the headers were printed as expected from the permissions.
Maybe your issue is caused by something else in your code. Try to include more details in your question.
By the way, your all_Search function is missing the return Response()
Okey I just decided to try something and it seams to be working, at least for now. I somehow believed that DEFAULT_AUTHENTICATION_CLASSES was the issue in this case and in deed it was, so I had to just remove the
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.TokenAuthentication',
'rest_framework.authentication.SessionAuthentication',
]
}
#opt to use
#authentication_classes = [TokenAuthentication, SessionAuthentication]
#in my views that requires authentications
in my settings, this was not all though, but now I could access the view either authorized or not: (having auth token or not). but this was not getting authenticated user by default
so I did this
make a view to get a user based on a given token
from django.contrib.auth.models import AnonymousUser
from rest_framework.authtoken.models import Token
def get_user(token):
try:
token = Token.objects.select_related('user').get(key=token)
return token.user
except:
return AnonymousUser
and get user in my view if token exists in the headers
#api_view(['GET'])
#permission_classes([permissions.IsAuthenticatedOrReadOnly])
def all_Search(request):
auth = request.headers.get('Authorization').split(' ')[1]
key = request.headers.get('Authorization').split(' ')[0]
if key == 'Token' and auth != 'null': #used null coz my frontend sends null if key is not available
user = get_user(auth)
print(user)

Authentication credentials were not provided drf

when i trying to access api i'm getting this error:
"detail": "Authentication credentials were not provided."
i have included this in settings.py:
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES':(
'rest_framework.authentication.TokenAuthentication',
'rest_framework.authentication.SessionAuthentication',
),
'DEFAULT_PERMISSION_CLASSES':(
'rest_framework.permissions.IsAuthenticated',
)
}
my app api urls.py:
from django.urls import path,include
from . import views
from rest_framework import routers
router = routers.SimpleRouter()
router.register(r'',views.UserViewSet, 'user_list')
urlpatterns = router.urls
my views.py:
class UserViewSet(viewsets.ModelViewSet):
queryset = User.object.all()
serializer_class = serializers.UserSerializers
serializers.py:
from rest_framework import serializers
from users.models import User
class UserSerializers(serializers.ModelSerializer):
class Meta:
model = User
fields = ('email','password')
my main urls.py:
urlpatterns = [
path('admin/', admin.site.urls),
path('',include(urls)),
path ('', include(user_urls)),
path('api/',include(api_urls)),
when i running localhost:8000/api i'm getting the error
You can't access the api from the browsers url if you are using TokenAuthentication.
as said by #DarkOrb TokenAuthentication expects a authorization header with token as it's value.
So You must pass token whenever you call the api.
You can test your api using postman.
In above image i have passed token in headers of postman to access my api.
When you call your api from frontend side,pass your token along with the request.
If you just want to use your api in only desktop's browser,in that case you can use SessionAuthentication only.For mobile devices Tokenauthentication must be done.
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES':(
'rest_framework.authentication.TokenAuthentication',
'rest_framework.authentication.SessionAuthentication',
),
'DEFAULT_PERMISSION_CLASSES':(
'rest_framework.permissions.IsAuthenticated',
)
}
use this in your settings.py file, what is happening is that rest_framework.authentication.TokenAuthentication expects a authorization header with token as it's value, but you can't send that with your browser, to browse API from browser you must have SessionAuthentication enabled.

unable to make a successful call from android using retrofit with csrf token

I'm new to django and got struck with csrf tokens. I'm making a post request from android using retrofit to my django server which is using csrf protection. I had obtained the csrf token by making a get request first and then I'm passing this csrftoken from the body of POST request. However, my server is showing 'CSRF cookie not set' error. The server is responding well to the calls from POSTMAN but when I make calls from android, I get this error. I think there is some simple thing I'm missing, but I'm not able to figure it out.
Session based authorization is usually used in web-apps. In case of android apps which are backed by API.
So rather than you can do Token Based Authorization using rest_framework in Django.
In your settings.py
INSTALLED_APPS = [
...
'rest_framework',
]
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.TokenAuthentication', # <-- And here
],
}
Now migrate the migrations to the database.
python manage.py migrate
Run this command to generate token for the specific user.
python manage.py drf_create_token <username>
Now add this line to urls.py.
from rest_framework.authtoken.views import obtain_auth_token
urlpatterns = [
#Some other urls.
path('api-token-auth/', obtain_auth_token, name='api_token_auth'),
]
Using this you can obtain token for any user by using its username & password by just passing them in request body.
So this will be our protected api. Add this class based view in your views.py
from rest_framework.permissions import IsAuthenticated,AllowAny # <-- Here
from rest_framework.views import APIView
from rest_framework.response import Response
class DemoData(APIView):
permission_classes = (IsAuthenticated,)
def post(self, request):
content = {'data': 'Hello, World!'}
return Response(content)
Now pass a header with the api name as 'Authorization' & value be like something 'Token 5a2b846d267f68be68185944935d1367c885f360'
This is how we implement Token Authentication/Authorization in Django.
For more info, click here to see official documentation.

Authentication credentials were not provided with Django Rest Framework JWT

I am having trouble implementing token authentication with JWT in the Django rest framework with a Typscript frontend. I'm getting
{detail: "Authentication credentials were not provided."}
with my API call via Typescript, which is:
readonly BASE_URL = 'http://127.0.0.1:8000/'
api_url = this.BASE_URL + 'items/'
auth_url = this.BASE_URL + "api-token-auth/"
getItemsService(token) {
const headers = new HttpHeaders()
headers.append('Content-Type', 'application/json')
headers.append('Authorization', 'JWT ' + token.token)
return this.http.get(this.api_url, {headers: headers})
}
Logging in works fine. It's when I try to load the items that I have issues.
Here's my Django code:
views.py
from rest_framework import generics
from .models import Item
from .serializers import ItemSerializer
class ItemList(generics.ListCreateAPIView):
queryset = Item.objects.all()
serializer_class = ItemSerializer
class ItemDetail(generics.RetrieveUpdateDestroyAPIView):
queryset = Item.objects.all()
serializer_class = ItemSerializer
items/urls.py
from django.urls import path
from .views import ItemList, ItemDetail
urlpatterns = [
path('', ItemList.as_view()),
path('<int:pk>/', ItemDetail.as_view()),
]
project/urls.py
from django.contrib import admin
from django.urls import include, path
from rest_framework_jwt.views import obtain_jwt_token
urlpatterns = [
path('items/', include('groceries.urls')),
path('admin/', admin.site.urls),
path('api-auth/', include('rest_framework.urls')),
path('api-token-auth/', obtain_jwt_token),
]
settings.py
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticated',
),
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
),
}
I thought the issue would have to be with Django, but I am able to get what I expect with
curl -H "Authorization: JWT <token>" http://localhost:8000/items/
If my backend was not set up correctly, this wouldn't work. So it must be my frontend code.
Based on what you described, It may be a CORS issue. Because you have access to your api endpoint via curl command. But not with browser.
Cross-Origin Resource Sharing (CORS) is a mechanism that uses additional HTTP headers to tell a browser to let a web application running at one origin (domain) have permission to access selected resources from a server at a different origin. A web application makes a cross-origin HTTP request when it requests a resource that has a different origin (domain, protocol, and port) than its own origin.
I checked your Angular typescript code, It seems fine. I suggest to follow below instructions in your django project and see how it goes:
1) install it for pip via pip install django-cors-headers command.
2) In settings.py file, add this app to your installed apps:
INSTALLED_APPS = (
...
'corsheaders',
...
)
3) You will also need to add a middleware class to listen in on responses:
MIDDLEWARE = [ # Or MIDDLEWARE_CLASSES on Django < 1.10
...
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
...
]
remember CorsMiddleware should be placed as high as possible.
4) Add this line to your settings.py file.
CORS_ORIGIN_ALLOW_ALL = True
for full documentation refer to django-cors-headers.