How logout from Djoser (installed with Django Rest Framework) - django

I have installed Djoser with Django Rest Framework, after loggin in as (url : /token/login ) I receive a token, but when I change url to '/token/logout/ ' it shows error as logging credential not provided.
I am using browser url section to interact with DRF.
Please advice me correct url to logout ? I can provide Token,username and password.

I was stuck on this too. What worked for me was to pass the token as normal through the authentication header AND pass it as json data.
export const logout = (token) => {
return url
.post('api/auth/token/logout/', token,
{
headers: {
Authorization: `Token ${token}`
}
})
.then(res => res.data)
}

Have you something like this
#urls.py
from django.contrib.auth import views as auth_views
path('logout/', auth_views.LogoutView.as_view(), name='logout'),

You need to include the Authorization Token with your POST request to the logout URL.

Related

How to use Postman to authenticate Google Login with dj_rest_auth

So I am following the official documentation for Google sign in with DjangoRestFramework using DJ Rest Auth (this link)
I intend to authenticate with Postman Oauth2 (by following the guide and generating an Access Token)
Postman is generating an access token successfully, but I cannot seem to use this authentication in my API calls. Please who knows which step I am missing - I want to handle everything in Postman.
urls.py
urlpatterns = [
path('', Home.as_view(), name='home'),
path('admin/', admin.site.urls),
path('accounts/', include(api_urls, namespace='api')),
path('accounts/login/', GoogleLogin.as_view(), name='google_login'),
path('accounts/', include('rest_framework.urls')),
]
views.py
class GoogleLogin(SocialLoginView):
adapter_class = GoogleOAuth2Adapter
callback_url = 'http://localhost:8080/accounts/google/login/callback/'
client_class = OAuth2Client
On calling an API endpoint, I get an invalid token error:
If I however visit the Google Login view in my RestFramework UI (in my case http://localhost:8080/accounts/login), I get an endpoint to make a POST, and on making a POST request, a key is generated. Only this key (if used as a Bearer token) works in my API calls.
How can I authenticate on Google, and make my API calls independent of the DRF UI?
Callback URL has been configured on my Google Developer Client.
PS: I feel the answer is in step 6 of the documentation, but I am unable to figure out how to do this in Postman
POST code or token to specified URL(/dj-rest-auth/google/)
What I did here is from postman go to headers then put Authorization = Token youraccesskey
which in your case Authorization = Token ef057......
Hope it helps

How to use DRF JWT resfresh

I can generate token,However, after the Web accesses me with the first token, I cannot give a new token
I set it in setting
'JWT_ALLOW_REFRESH': True,
But I don't know how to get a new one
Please let me know if you need anything else
I thought that after this setting is completed, the token will be changed automatically Medium expiration time,Looks like I'm wrong
based on this post, you have to do the following:
request the token http post http://127.0.0.1:8000/api/token/ username=vitor password=123
this returns a access token and a refresh token
use the access token to access the site
if the access token expires (site returns 403) use the refresh token to get a new valid access token http post http://127.0.0.1:8000/api/token/refresh/ refresh=REFRESHTOKEN
Note that the refresh token can also expire, then you would have to restart the flow.
EDIT: code snippets
install library
pip install djangorestframework_simplejwt
docs of the library
settings.py
REST_FRAMEWORK = {
...
'DEFAULT_AUTHENTICATION_CLASSES': (
...
'rest_framework_simplejwt.authentication.JWTAuthentication',
)
...
}
urls.py
from django.urls import path
from rest_framework_simplejwt import views as jwt_views
urlpatterns = [
# Your URLs...
path('api/token/', jwt_views.TokenObtainPairView.as_view(), name='token_obtain_pair'),
path('api/token/refresh/', jwt_views.TokenRefreshView.as_view(), name='token_refresh'),
]

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.

CSRF verification failed error with react, axios and DRF

I am trying to make a post request which looks like this
axios
.post(`http://127.0.0.1:8000/api/create/${this.props.id}`, {
headers: {
Authorization: `Token ${token}`
},
xsrfCookieName: "XSRF-TOKEN",
xsrfHeaderName: "X-CSRFToken"
})
.then();
I have added essential things in settings.py also, such as
CSRF_COOKIE_NAME = "XSRF-TOKEN"
I also have
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.TokenAuthentication',
'rest_framework.authentication.BasicAuthentication',
),
}
You may need to add ensure_csrf_cookie in your code.
A page makes a POST request via AJAX, and the page does not have an HTML form with a csrf_token that would cause the required CSRF cookie to be sent.
from django.views.decorators.csrf import ensure_csrf_cookie
#ensure_csrf_cookie
Read more about ensure_csrf_cookie. Let me know if that helps.

Django React Axios

I am trying to make a post request to a Django server using React with Axios. However, I am getting a redirect 302 on the server side.
Just followed all suggestions in this post here CSRF with Django, React+Redux using Axios
unsuccessfully :(
However, what I have done so far is the following:
Sat the default axios CookieName and HeaderName (on the javascript side):
axios.defaults.xsrfHeaderName = "X-CSRFToken";
axios.defaults.xsrfCookieName = "XCSRF-Token";
Got this in settings.py as well:
CSRF_COOKIE_NAME = "XCSRF-Token"
And here is how the post request looks like:
axios(
{
method: 'post',
url: `/api/${selectedEntryType}_entry`,
data: {
"test": "test"
},
headers: {
'X-CSRFToken': document.cookie.split('=')[1],
'X-Requested-With': 'XMLHttpRequest',
'Content-Type': 'application/json',
}
}
)
Another thing that I have tried is to make the post request from the Django rest api UI:
and it does work successfully.
The only differences in the Request Headers when I make the request from the UI and from JS are:
Accept, Content-Length, and Referer, which I don't see how could they be problematic.
Please help.
Managed to fix it by changing the url (url:'/en/api/endpoint/') I was posting to, because apparently for a POST request:
You called this URL via POST, but the URL doesn't end in a slash and you have APPEND_SLASH set. Django can't redirect to the slash URL while maintaining POST data. Change your form to point to 127.0.0.1:8000/en/api/endpoint/ (note the trailing slash), or set APPEND_SLASH=False in your Django settings
After that I started getting Forbidden 403, but by adding:
from django.views.decorators.csrf import csrf_protect
from django.utils.decorators import method_decorator
#method_decorator(csrf_protect)
def post(self, request):
return Response()
and also changed the defaults in JS to:
axios.defaults.xsrfHeaderName = "X-CSRFToken";
axios.defaults.xsrfCookieName = "csrftoken";
and removed CSRF_COOKIE_NAME = "XCSRF-Token" from settings.py.
It worked.
Hope this helps somebody in the future.