same token is getting on token request in django - django

Hi I am using django rest-framework, i want to implement token base authentication,
i am using basic rest-framework token authentication module.
but it return same token on every request.
ex(87d97bb2df56e39c12b38131087bcfd232720d9a), i am getting this string on every request i sent to my server.
my setting.py file
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'restApp2', # Local Apps (My project's apps)
'rest_framework',
'rest_framework.authtoken',
'rest_auth',
]
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.TokenAuthentication', # <-- And here
],
}
urls.py file
from django.contrib import admin
from django.urls import path, include
from restApp2 import views
from rest_framework.authtoken.views import obtain_auth_token
urlpatterns = [
path('admin/', admin.site.urls),
path('hello/', views.HelloView.as_view(), name='hello'),
path('api-token-auth/', obtain_auth_token, name='api_token_auth'), # <-- And here
]
urlpatterns += [
path('accounts/', include('django.contrib.auth.urls')),
]
i am calling bellow url using post method from POSTMON.
POST http://localhost:7070/rest-auth/login/
and in response i get
87d97bb2df56e39c12b38131087bcfd232720d9a.
but i want different token on new request.
please help me, Thank You

If you check obtain_auth_token view, its either getting existing token or creating new one if there is no token in the database for the user.
If want new token on each login, then delete the previous tokens after logout.
django rest framework - token authentication logout

Related

Getting "CSRF token missing or incorrect" on obtain token request

We are using Django REST Framework and we are using user logins. From a web client we have a login screen and use obtain_auth_token from the REST Framework to obtain an api token. The web client uses XMLHttpRequest.
It starts out with working fine. The web client obtains a token using username+password and uses that token in the following API calls.
When I return the next day and open a new browser tab and try to log in I get a 403 Forbidden and the Django logs (and the body reply) says {"detail":"CSRF Failed: CSRF token missing or incorrect."}
I can see that the incoming request has a csrftoken cookie and a sessionid cookie. I can see the same cookies if I use the browser "Developer Tools". If I remove those two cookies, it works fine afterwards.
Also, if I launch a private browser window (= incognito), the web app works fine.
I am do not know why those cookies appear, when they appear exactly and why the REST framework do not like them.
I have two suspicions:
We also use the Django admin interface. Could it be that the login to the admin interface on the same domain will plant those cookies and somehow interfere with the REST Framework?
Something about time passes will make the problem appear? It seems to me that the problem does not appear until "the day after" if I clear the cookies. This might very well be other circumstances tricking me, like point 1 above.
Any suggestions on how to resolve this?
For reference, some snippes of our Django setting.py:
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'request_logging.middleware.LoggingMiddleware',
]
INSTALLED_APPS = [
'mybackend.apps.MybackendConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django_cleanup.apps.CleanupConfig',
'rest_framework',
'rest_framework.authtoken',
'adminsortable',
'corsheaders',
'django_filters',
'storages',
]
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.DjangoModelPermissions'
],
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.TokenAuthentication',
'rest_framework.authentication.SessionAuthentication',
),
'DEFAULT_FILTER_BACKENDS': (
'django_filters.rest_framework.DjangoFilterBackend',
),
}
From urls.py:
from rest_framework.authtoken import views as restviews
...
urlpatterns = [
path('admin/', admin.site.urls),
url(r'^api/token-auth/obtain_auth_token', restviews.obtain_auth_token),
url(r'^api/', include(router.urls)),
]
Seems like the SessionAuthentication is the culprit. My guess is that is was added to be able to play with the REST interface from a browser for testing purposes.
So if I remove SessionAuthentication it seems to work.
Now the config looks like this:
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.DjangoModelPermissions'
],
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.TokenAuthentication',
# 'rest_framework.authentication.SessionAuthentication',
),
'DEFAULT_FILTER_BACKENDS': (
'django_filters.rest_framework.DjangoFilterBackend',
),
}

Django REST Framework BasicAuthentication is not applied as default authentication class

I have a Django REST Framework project and I added
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.BasicAuthentication',
]
}
to settings.py and I expect BasicAuthentication is applied to all pages as default but still it does not require any authentication to display the content. that is weird. Do I have to do something I did not do?
urls.py:
urlpatterns = [
path('admin/', admin.site.urls),
path('student/', include('blogapp.urls')),
path('api/', include('api.urls')),
path('api-auth/', include('rest_framework.urls')),
]
setting.py:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'blogapp',
]
blog_app/urls:
urlpatterns = [
path('', StudentView.as_view()),
]
views.py:
class StudentView(generics.ListCreateAPIView):
queryset = Student.objects.all()
serializer_class = StudentSerializer
UPDATE 1:
Also per-view authentications not work!
UPDATE 2:
This is my project source code.
Authentication is not the same as permission. You'll also need to add a default permission class if you require all users to be authenticated (using one of the authentication methods you wish to use):
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.BasicAuthentication',
],
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.IsAuthenticated',
],
}
Also, make sure you're testing the right view (/api/list/). Your project (as you linked) has two StudentViews, one of which is a DRF view, the other (/student/) isn't. The latter will not be aware of DRF configuration.

DoesNotExist at /admin/

DoesNotExist at /admin/
URL matching query does not exist.
I copy code form old study-project and i haven't similar problem in old project.
settings.py INSTALLED_APPS:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'cutter',
]
admin.py:
from .models import URL
from django.contrib import admin
admin.site.register(URL)
urls.py:
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('', include('cutter.urls')),
path('admin/', admin.site.urls),
]
All another functions work.

Django Oscar Dashboard link not accessible

I have developed oscar /django applications before but I am completely stumped by this issue:
I can see the dashboard url in the supported urls list but I am not able to access it.
404 Page
I have forked a few apps from oscar like voucher, shipping, checkout, reviews and customized them in various ways(None of these are dashboard related) . This is my INSTALLED_APPS:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.sites',
'django.contrib.flatpages',
'oscar.config.Shop',
'oscar.apps.analytics.apps.AnalyticsConfig',
'iirns.checkout.apps.CheckoutConfig',
'oscar.apps.address.apps.AddressConfig',
'iirns.shipping.apps.ShippingConfig',
'oscar.apps.catalogue.apps.CatalogueConfig',
'iirns.catalogue.reviews.apps.CatalogueReviewsConfig',
'oscar.apps.communication.apps.CommunicationConfig',
'oscar.apps.partner.apps.PartnerConfig',
'oscar.apps.basket.apps.BasketConfig',
'iirns.payment.apps.PaymentConfig',
'oscar.apps.offer.apps.OfferConfig',
'oscar.apps.order.apps.OrderConfig',
'oscar.apps.customer.apps.CustomerConfig',
'oscar.apps.search.apps.SearchConfig',
'iirns.voucher.apps.VoucherConfig',
'oscar.apps.wishlists.apps.WishlistsConfig',
'oscar.apps.dashboard.apps.DashboardConfig',
'oscar.apps.dashboard.reports.apps.ReportsDashboardConfig',
'oscar.apps.dashboard.users.apps.UsersDashboardConfig',
'oscar.apps.dashboard.orders.apps.OrdersDashboardConfig',
'oscar.apps.dashboard.catalogue.apps.CatalogueDashboardConfig',
'oscar.apps.dashboard.offers.apps.OffersDashboardConfig',
'oscar.apps.dashboard.partners.apps.PartnersDashboardConfig',
'oscar.apps.dashboard.pages.apps.PagesDashboardConfig',
'oscar.apps.dashboard.ranges.apps.RangesDashboardConfig',
'oscar.apps.dashboard.reviews.apps.ReviewsDashboardConfig',
'oscar.apps.dashboard.vouchers.apps.VouchersDashboardConfig',
'oscar.apps.dashboard.communications.apps.CommunicationsDashboardConfig',
'oscar.apps.dashboard.shipping.apps.ShippingDashboardConfig',
# 3rd-party apps that oscar depends on
'widget_tweaks',
'haystack',
'treebeard',
'sorl.thumbnail',
'django_tables2',
'mailer',
'extra',
]
and this is my root url file:
from django.conf.urls import url
from django.contrib import admin
from django.apps import apps
from django.urls import include, path
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('',include('extra.urls')),
path('', include(apps.get_app_config('oscar').urls[0])),
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Using the URLconf defined in TEST_PAGE, Django tried these URL patterns, in this order:

I've reviewed other posts related to my question, but I'm unable to find an answer for my question.
When I try to access "http://127.0.0.1:8000/TEST_PAGE" I get the following error:
"Using the URLconf defined in TEST_PAGE, Django tried these URL patterns, in this order:
^admin/
^$
^TEST_PAGE/
The current URL, TEST_PAGE, didn't match any of these."
Here is what I have for Mysite/Mysite/urls.py:
from django.conf.urls import url, include
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^$', include('Main_Page.urls')),
url(r'^TEST_PAGE/', include('TEST_PAGE')),
]
I have the APP installed in Mysite/Mysite/settings.py:
INSTALLED_APPS = [
'TEST_PAGE',
'Main_Page',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
Here is what I have for Mysite/TEST_PAGE/urls.py:
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^TEST_PAGE', views.index, name='TEST_PAGE'),
]
And here is what I have for Mysite/TEST_PAGE/views.py:
from django.shortcuts import render
def index(request):
return render(request, 'TEST_PAGE/TEST_PAGE.html')
The main/index/home app works fine, I'm just trying to access the second app.
I'm new to this, so any help would be appreciated.
By including 'TEST_PAGE' twice(in both urls.py), you have defined a url:
/TEST_PAGE/TEST_PAGE
So
django can find url /TEST_PAGE/TEST_PAGE but not /TEST_PAGE
Your Mysite/TEST_PAGE/urls.py should be:
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index, name='TEST_PAGE'), # maps to /TEST_PAGE/
]