William Abrahamsson
William Abrahamsson

Reputation: 229

Authenticate User In Django via Flutter App and JSON Web Token

How do I Authenticate User in Django-Rest-Framework via my Flutter App? I did this in Postman before and this is how I did it:

  1. Post Request to (IP:8000/get-token/) > Returns JSON Web Token
  2. Get Request with Bearer Token to (IP:8000/database/exercises/) > Returns JSON file! - Note that if I don't use the token I will get nothing in return!

How do I replicate this via a Flutter http.post Request?

This is how I will do the signup process (In this case not with the token):

//text-field controllers
TextEditingController usernameController = TextEditingController();
TextEditingController passwordController = TextEditingController();

//post request
postRequest() async {
String _url = "IP:8000/get-token/";
var response = await http.post(
  Uri.encodeFull(_url),
  headers: { "Accept" : "application/json"},
  body: {
    "username": "${usernameController.text}",
    "password": "${passwordController.text}",
  },
  encoding: Encoding.getByName("utf-8"),
);

//Name TextField (Simplified Code)
Container(
  margin: EdgeInsets.only(bottom: 2, top: 25),
    child: TextField(
    controller: nameController,
      decoration: InputDecoration(
      hintText: "Name..."             
      ))
)

//Password TextField (Simplified Code)
Container(
  margin: EdgeInsets.only(bottom: 2, top: 25),
    child: TextField(
    controller: passwordController,
      decoration: InputDecoration(
      hintText: "Password..."             
      ))
)

//Simplified but you get what I mean
Inkwell(
  child: Container()
  onTap() 
  {
    postRequest(),
    Navigator.push(Into-App)
  }
)

My question is: How do I take the response from this request? (if username and password match the database).

And how do I use the token I get in response to do future request to get data inside the app?

The Django-Backend:

#urls
from rest_framework_simplejwt.views import TokenObtainPairView, TokenRefreshView

urlpatterns = [
    path('admin/', admin.site.urls),
    path('database/', include('PlanThatWorkout.urls')),
    path('get-token/', TokenObtainPairView.as_view()),
    path('refresh-token/', TokenRefreshView.as_view())
]

#settings
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES' : ('rest_framework.permissions.IsAuthenticated',),
'DEFAULT_AUTHENTICATION_CLASSES' : ('rest_framework_simplejwt.authentication.JWTAuthentication',),
}

Upvotes: 4

Views: 5406

Answers (1)

Paulo Keller
Paulo Keller

Reputation: 148

You can get the token by decoding your response with dart:convert.

import 'dart:convert';
Map<String, dynamic> data = jsonDecode(reponse);
final jwt = data['jwt-key'];

To persist your data, you can save this on disk writing in file with path_provider:

import 'dart:async';
import 'dart:io';

import 'package:flutter/foundation.dart';
import 'package:path_provider/path_provider.dart';

Future<File> write(String jwt) async {
    final directory = await getApplicationDocumentsDirectory();
    final path = directory.path;
    final file = File('$path/jwt.txt');
    return file.writeAsString('$jwt');
}

Future<String> read() async {
    try { in a file or using 
      final directory = await getApplicationDocumentsDirectory();
      final path = directory.path;
      final file = File('$path/jwt.txt');
      String contents = await file.readAsString();
      return contents;
    } catch (e) {
      return '';
    }
  }

or using shared_preferences.

Upvotes: 0

Related Questions