在我的flutter项目中,我创建了一个api_service。dart发送用户名和密码,并返回令牌授权。
我目前无法在头中发送授权令牌以允许从dj-rest-auth/user获取信息,并且我正在获得Forbidden: /api/dj-rest-auth/user/
这是api_service.dart
:
class APIService {
static var client = http.Client();
static Future<bool> login(
LoginRequestModel model,
) async {
Map<String, String> requestHeaders = {
'Content-Type': 'application/json',
};
var url = Uri.parse(
Config.apiURL + Config.loginAPI,
);
print(url);
var response = await client.post(
url,
headers: requestHeaders,
body: jsonEncode(model.toJson()),
);
print(response.body);
if (response.statusCode == 200) {
await SharedService.setLoginDetails(
loginResponseJson(
response.body,
),
);
print(response.body);
return true;
} else {
return false;
}
}
下面是调用用户详细信息的函数:
Future<User> fetchUser() async {
final response = await http.get("url");
Map<String, String> requestHeaders = {
'Content-Type': 'application/json',
'Authorization': loginResponseJson(response.body),
};
if (response.statusCode == 200) {
return User.fromJson(jsonDecode(response.body));
} else {
throw Exception('Failed to load User');
}
}
我收到以下错误:
error: The element type 'LoginResponseModel' can't be assigned to the map value type 'String'.
loginResponseJson (response.body):
{"key":"............."}
我的问题:
在header中添加token以允许用户认证从Django Rest框架中获取数据的最好方法是什么?如何修复此错误?
也许您想先将访问令牌存储到SharedPreferences中。然后,对于每个请求,从store中获取这个令牌并添加到header中。目前,我使用砍刀https生成器为:
class AuthenticatedClient extends http.BaseClient {
final http.Client _inner;
final FlutterSecureStorage secureStorage;
AuthenticatedClient(this._inner, {required this.secureStorage});
@override
Future<http.StreamedResponse> send(
http.BaseRequest request,
) async {
if (request.headers["Content-Type"] != null) {
request.headers["Content-Type"] = "application/json";
}
final token = await secureStorage.read(key: PrefKeys.accessToken);
if (token != null) {
request.headers['Authorization'] = 'Bearer $token';
}
return _inner.send(request);
}
}
确保你的Authorization
头有一个有效的结构
Map<String, String> requestHeaders = {
'Content-Type': 'application/json',
'Authorization': 'Bearer ${your_token}',
};