如何在 Flutter 移动应用程序的 API 调用中传递基本身份验证凭据? [英] How to pass basic auth credentials in API call for a Flutter mobile application?

查看:23
本文介绍了如何在 Flutter 移动应用程序的 API 调用中传递基本身份验证凭据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个简单的 Flutter 移动应用,该应用需要调用使用基本身份验证的 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?

推荐答案

假设您的服务器期望 username:password 组合将其编码为 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: <String, String>{'authorization': basicAuth});
  print(r.statusCode);
  print(r.body);
}

这篇关于如何在 Flutter 移动应用程序的 API 调用中传递基本身份验证凭据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆