Flutter and Django Login with JWT Tokens by storing tokens not working

276 Views Asked by At

I want to log in on Flutter, but it does not remain Authenticated in Django as well as on Flutter.

I just want the user to stay logged in on Flutter by storing tokens so it remains authenticated, but if possible also on Django server.

Views.py

class LoginAPIView(APIView):
    def post(self, request):
        username = request.data.get('username')
        phonenumber = request.data.get('phonenumber')
        password = request.data.get('password')

        try:
            user = UserProfile.objects.get(
                username=username, phone_number=phonenumber)
        except UserProfile.DoesNotExist:
            # Handle the case where the user with the given username doesn't exist
            return Response({"message": "A user or phone number does not found."}, status=status.HTTP_400_BAD_REQUEST)
        print(user)
        if user.password == password:
            if user is not None:  # if user.check_password(password):
                # Password is correct, log in the user
                print(user)
                login(request, user)

        # Generate JWT token
            payload = {
                'user_id': user.id,
                'exp': datetime.datetime.utcnow() + datetime.timedelta(minutes=60),
                'iat': datetime.datetime.utcnow()
            }
            token = jwt.encode(payload, 'secret', algorithm='HS256')
            uname = username
        # Set the token as a cookie
            # print(token)"jwt": token,
            return Response({"message": "Successfully Login", "jwt": token, "uname": uname}, status=status.HTTP_200_OK)
            # response = Response(
            #     {"message": "Successfully Login", "uname": uname}, status=status.HTTP_200_OK)
            # response.set_cookie(key='jwt', value=token, httponly=True)

            return response
        else:
            # Password is incorrect
            raise AuthenticationFailed(
                {"message": "Password Incorrect"}, code=status.HTTP_401_UNAUTHORIZED)

Flutter Code:

 onPressed: () async {
                var username = usernameController.text;
                final phonenumber = phoneNumberController.text;
                final password = passwordController.text;
                const apiUrl = 'http://127.0.0.1:8000/Login/';
                AuthService authService = AuthService();
                var token;
                final response = await http.post(
                  Uri.parse(apiUrl),
                  headers: {'Content-Type': 'application/json'},
                  body: jsonEncode({
                    'Authorization': 'Bearer $token',
                    'username': username,
                    'phonenumber': phonenumber,
                    'password': password,
                  }),
                );
                if (response.statusCode == 200) {
                  // Handle successful response
                  final Map<String, dynamic> responseData =
                      json.decode(response.body);
                  final String token = responseData['jwt'];
                  print(token);
                  setState(() {
                    message = responseData['message'];
                    uname = responseData['uname'];
                  });
               

                 
                  const storage = FlutterSecureStorage();

                  // await storage.write(key: 'jwt', value: token);
               

             
              
1

There are 1 best solutions below

2
Rishabh Agrawal On

In General you would required 2 API

  • one API is for login
  • second API is for token refresh

Here is the Simple Process you can follow as a starting point

  1. Using login API you will provide username/password and if they are matched and right then you will return JWT token from your server.
  2. Once you receive the JWT token you will have to store as you're doing in the code you've provided.
  3. Now next time whenever you will be opening your app, you will have to fetch the saved JWT Token and deserialize it just to see if the JWT token is expired or not, if its not you can mark your user authenticated otherwise you can call 2nd API to refresh the token