首页 > 解决方案 > 通过 Flutter App 和 JSON Web Token 在 Django 中验证用户

问题描述

如何通过我的 Flutter 应用程序在 Django-Rest-Framework 中对用户进行身份验证?我以前在 Postman 中这样做过,这就是我的做法:

  1. 将请求发布到 (IP:8000/get-token/) > 返回 JSON Web Token
  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',),
}

标签: apiauthenticationflutterdjango-rest-frameworkjwt

解决方案


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


推荐阅读