如何在Flutter移动应用程序的API调用中传递基本身份验证凭据? [英] How to pass basic auth credentials in API call for a Flutter mobile application?
问题描述
我正在制作一个简单的Flutter移动应用程序,需要调用使用Basic Auth的API。
I'm working on a simple Flutter mobile app that needs to call out to an API that uses Basic Auth.
我可以使用电子邮件点击Postman中的API &安培;密码凭证,它编码电子邮件&在执行请求之前,Base64中的密码(我假设用:分隔)。
I can hit the API in Postman using email & password credentials and it encodes the email & password in Base64 (I assume with a ":" separating) before performing the request.
我不知道如何在Flutter / Dart中执行此操作...
I'm not sure how to do this in Flutter / Dart...
我已经修改了http包并尝试进行Base64编码......但我只是从服务器上找回错误。
I've tinkered with the http package and tried to do the Base64 encoding... but I just get back errors from the server.
任何人都可以为基本身份验证请求提供一些指导或示例吗?
Can anyone provide some guidance or an example for a basic auth request?
推荐答案
假设你的服务器期望用户名:密码
组合将其编码为UTF-8(参见 RFC 7617 了解更多详情)然后使用:
Assuming that your server expects that the username:password
combo will be encode it UTF-8 (see RFC 7617 for more details) then use this:
import 'dart:convert';
import 'package:http/http.dart';
main() async {
String username = 'test';
String password = '123£';
String basicAuth =
'Basic ' + base64Encode(utf8.encode('$username:$password'));
print(basicAuth);
Response r = await get('https://api.somewhere.io',
headers: {'authorization': basicAuth});
print(r.statusCode);
print(r.body);
}
这篇关于如何在Flutter移动应用程序的API调用中传递基本身份验证凭据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!