api - 通过 Flutter App 和 JSON Web Token 在 Django 中验证用户
问题描述
如何通过我的 Flutter 应用程序在 Django-Rest-Framework 中对用户进行身份验证?我以前在 Postman 中这样做过,这就是我的做法:
- 将请求发布到 (IP:8000/get-token/) > 返回 JSON Web Token
- 使用承载令牌获取请求到 (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',),
}
解决方案
您可以通过使用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 '';
}
}
推荐阅读
- c# - 如果我使用 NModbus4 在其中获取浮点值,如何读取 16 位寄存器
- javascript - 如何检查浏览器是否支持公钥凭据?
- mysql - magento 2 管理员密码更新失败错误 1064
- sugarcrm - assign_user_id 不会改变
- javascript - 如何在reactjs中按下按钮时将值传递给导入的模块
- python - 将列项转换为自己的列python
- objective-c - UINavigationBar - 右栏图像淡入淡出过渡
- vb.net - RichTextBox1 对非共享对象的引用需要对象引用
- angular - 'ion-title' 不是已知元素:在动态创建组件时
- opensuse - chkconfig 工具无法在 SUSE 15 上正常工作