【发布时间】:2019-10-15 10:27:11
【问题描述】:
如何通过我的 Flutter 应用在 Django-Rest-Framework 中对用户进行身份验证? 我以前在 Postman 中这样做过,我就是这样做的:
- 将请求发布到 (IP:8000/get-token/) > 返回 JSON Web 令牌
- 使用承载令牌获取请求到 (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',),
}
【问题讨论】:
-
当服务器返回令牌时,您将其保存在客户端的localStorage中。然后,在后续请求中,您将在 http 请求标头中包含该 localStorage 对象。请注意,在生产环境中,您应该只在 HTTPS 中执行此操作。
标签: api authentication flutter django-rest-framework jwt