简体   繁体   中英

django what do i need for authentication after login?

I followed the example in: https://docs.djangoproject.com/en/3.0/topics/auth/default/#django.contrib.auth.login

from django.contrib.auth import authenticate, login

def my_view(request):
    username = request.POST['username']
    password = request.POST['password']
    user = authenticate(request, username=username, password=password)
    if user is not None:
        login(request, user)
        # Redirect to a success page.
        ...
    else:
        # Return an 'invalid login' error message.

This code doesn't seem to return any token or some sort to the client but just a redirection.

In other codes where django checks authentication, django checks request.user.is_authenticated . Do i need to set this by myself?

from django.conf import settings
from django.shortcuts import redirect

def my_view(request):
    if not request.user.is_authenticated:
        return redirect('%s?next=%s' % (settings.LOGIN_URL, request.path))

To get authenticated by decorators such as @login_required or have proper value for request.user.is_authenticated , what do I need to send and receive from the client(ReactJS)?

You can return a JsonResponse.

from django.http import JsonResponse

And after successful login

return JsonResponse ({
    'token': user.token,
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM