通过 Flutter App 和 JSON Web Token 在 Django 中验证用户身份



如何通过我的 Flutter App 在 Django-Rest-Framework 中验证用户?我以前在邮递员中做过这个,这就是我的做法:

  1. 将请求发布到 (IP:8000/get-token/(>返回 JSON Web 令牌
  2. 获取带有持有者令牌的请求到 (IP:8000/database/exercises/(> 返回 JSON 文件! - 请注意,如果我不使用令牌,我将得不到任何回报!

如何通过颤振 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-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',),
}

您可以通过使用 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。

最新更新