如何通过Flutter应用在Django-Rest-Framework中对用户进行身份验证? 我以前在邮递员中这样做过,这是我做过的事情:
如何通过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',),
}
答案 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 '';
}
}