如何通过我的 Flutter 应用在 Django-Rest-Framework 中对用户进行身份验证? 我之前在 Postman 中这样做过,我是这样做的:
我如何通过 Flutter http.post 请求复制它?
这就是我将如何进行注册过程(在这种情况下不使用 token ):
//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)
}
)
我的问题是:如何从这个请求中获取响应? (如果用户名和密码与数据库匹配)。
我如何使用我获得的 token 来响应 future 的请求以获取应用内的数据?
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 解码您的响应来获取 token .
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 .
关于api - 通过 Flutter App 和 JSON Web Token 在 Django 中验证用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56366828/
给定这段代码defcreate@upgrades=User.update_all(["role=?","upgraded"],:id=>params[:upgrade])redirect_toadmin_upgrades_path,:notice=>"Successfullyupgradeduser."end我如何在该操作中实际验证它们是否已保存或未重定向到适当的页面和消息? 最佳答案 在Rails3中,update_all不返回任何有意义的信息,除了已更新的记录数(这可能取决于您的DBMS是否返回该信息)。http://ar.ru
我想安装一个带有一些身份验证的私有(private)Rubygem服务器。我希望能够使用公共(public)Ubuntu服务器托管内部gem。我读到了http://docs.rubygems.org/read/chapter/18.但是那个没有身份验证-如我所见。然后我读到了https://github.com/cwninja/geminabox.但是当我使用基本身份验证(他们在他们的Wiki中有)时,它会提示从我的服务器获取源。所以。如何制作带有身份验证的私有(private)Rubygem服务器?这是不可能的吗?谢谢。编辑:Geminabox问题。我尝试“捆绑”以安装新的gem..
尝试通过RVM将RubyGems升级到版本1.8.10并出现此错误:$rvmrubygemslatestRemovingoldRubygemsfiles...Installingrubygems-1.8.10forruby-1.9.2-p180...ERROR:Errorrunning'GEM_PATH="/Users/foo/.rvm/gems/ruby-1.9.2-p180:/Users/foo/.rvm/gems/ruby-1.9.2-p180@global:/Users/foo/.rvm/gems/ruby-1.9.2-p180:/Users/foo/.rvm/gems/rub
我希望我的UserPrice模型的属性在它们为空或不验证数值时默认为0。这些属性是tax_rate、shipping_cost和price。classCreateUserPrices8,:scale=>2t.decimal:tax_rate,:precision=>8,:scale=>2t.decimal:shipping_cost,:precision=>8,:scale=>2endendend起初,我将所有3列的:default=>0放在表格中,但我不想要这样,因为它已经填充了字段,我想使用占位符。这是我的UserPrice模型:classUserPrice回答before_val
我正在使用puppet为ruby程序提供一组常量。我需要提供一组主机名,我的程序将对其进行迭代。在我之前使用的bash脚本中,我只是将它作为一个puppet变量hosts=>"host1,host2"我将其提供给bash脚本作为HOSTS=显然这对ruby不太适用——我需要它的格式hosts=["host1","host2"]自从phosts和putsmy_array.inspect提供输出["host1","host2"]我希望使用其中之一。不幸的是,我终其一生都无法弄清楚如何让它发挥作用。我尝试了以下各项:我发现某处他们指出我需要在函数调用前放置“function_”……这
我有一个表单,其中有很多字段取自数组(而不是模型或对象)。我如何验证这些字段的存在?solve_problem_pathdo|f|%>... 最佳答案 创建一个简单的类来包装请求参数并使用ActiveModel::Validations。#definedsomewhere,atthesimplest:require'ostruct'classSolvetrue#youcouldevencheckthesolutionwithavalidatorvalidatedoerrors.add(:base,"WRONG!!!")unlesss
我正在编写一个gem,我必须在其中fork两个启动两个webrick服务器的进程。我想通过基类的类方法启动这个服务器,因为应该只有这两个服务器在运行,而不是多个。在运行时,我想调用这两个服务器上的一些方法来更改变量。我的问题是,我无法通过基类的类方法访问fork的实例变量。此外,我不能在我的基类中使用线程,因为在幕后我正在使用另一个不是线程安全的库。所以我必须将每个服务器派生到它自己的进程。我用类变量试过了,比如@@server。但是当我试图通过基类访问这个变量时,它是nil。我读到在Ruby中不可能在分支之间共享类变量,对吗?那么,还有其他解决办法吗?我考虑过使用单例,但我不确定这是
我的最终目标是安装当前版本的RubyonRails。我在OSXMountainLion上运行。到目前为止,这是我的过程:已安装的RVM$\curl-Lhttps://get.rvm.io|bash-sstable检查已知(我假设已批准)安装$rvmlistknown我看到当前的稳定版本可用[ruby-]2.0.0[-p247]输入命令安装$rvminstall2.0.0-p247注意:我也试过这些安装命令$rvminstallruby-2.0.0-p247$rvminstallruby=2.0.0-p247我很快就无处可去了。结果:$rvminstall2.0.0-p247Search
我将应用程序升级到Rails4,一切正常。我可以登录并转到我的编辑页面。也更新了观点。使用标准View时,用户会更新。但是当我添加例如字段:name时,它不会在表单中更新。使用devise3.1.1和gem'protected_attributes'我需要在设备或数据库上运行某种更新命令吗?我也搜索过这个地方,找到了许多不同的解决方案,但没有一个会更新我的用户字段。我没有添加任何自定义字段。 最佳答案 如果您想允许额外的参数,您可以在ApplicationController中使用beforefilter,因为Rails4将参数
我在理解Enumerator.new方法的工作原理时遇到了一些困难。假设文档中的示例:fib=Enumerator.newdo|y|a=b=1loopdoy[1,1,2,3,5,8,13,21,34,55]循环中断条件在哪里,它如何知道循环应该迭代多少次(因为它没有任何明确的中断条件并且看起来像无限循环)? 最佳答案 Enumerator使用Fibers在内部。您的示例等效于:require'fiber'fiber=Fiber.newdoa=b=1loopdoFiber.yieldaa,b=b,a+bendend10.times.m