Issue
What is the proper way of creating authentication in react native Login component with Django CBV Login (LoginView).
Do I need to write API using DRF?
Or can I just fetch POST request to .../login with username and password as body?
Solution
You would typically use Django Rest Framework (DRF) to handle the authentication over an API. For decoupling, security, and token-based-authentication.
For this, you would create a custom API endpoint for authentication. You can use DRF's TokenAuthentication
or third-party packages like dj-rest-auth
which provide a set of REST API views to handle authentication tasks.
Example code for DRF login func:
from rest_framework.authtoken.models import Token
from rest_framework.views import APIView
from rest_framework.response import Response
from django.contrib.auth import authenticate
class CustomLoginView(APIView):
def post(self, request, *args, **kwargs):
username = request.data.get('username')
password = request.data.get('password')
user = authenticate(username=username, password=password)
if user:
token, _ = Token.objects.get_or_create(user=user)
return Response({'token': token.key})
return Response({'error': 'Invalid Credentials'}, status=400)
On the React Native side, you would create a form that captures the username and password. When the user submits the form, the app makes a POST request to the Django server's authentication endpoint with the username and password.
Answered By - M Burak
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.