通过Flutter App和JSON Web令牌在Django中对用户进行身份验证

时间:2019-05-29 18:50:45

标签: api authentication flutter django-rest-framework jwt

如何通过Flutter应用在Django-Rest-Framework中对用户进行身份验证? 我以前在邮递员中这样做过,这是我做过的事情:

  1. 将请求发布到(IP:8000 / get-token /)>返回JSON Web令牌
  2. 获取带有承载令牌的请求到(IP:8000 / database / exercises /)>返回JSON文件! -请注意,如果我不使用令牌,我将一无所获!

如何通过Flutter http.post请求复制此内容?

这就是我进行注册过程的方式(在这种情况下,不使用令牌):

//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)
  }
)

我的问题是:如何从该请求中获取答复? (如果用户名和密码与数据库匹配)。

又该如何使用响应中获得的令牌来做将来的请求,以便在应用程序内部获取数据?

Django后端:

#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',),
}

1 个答案:

答案 0 :(得分:0)

您可以通过使用dart:convert解码响应来获得令牌。

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

要保留数据,您可以使用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 '';
    }
  }

或使用shared_preferences