我是 Flutter 新手,目前正在学习 http.dart 进行 api 调用,我正在使用带有 JWTToken Barrer 的 .net Web api 和/login 端点。
Future<AuthenticationResponse> Authenticate() async {
const loginEndpoint = "$baseURL/Login";
http.Response response = await http.get(Uri.parse(loginEndpoint));
if (response.statusCode == 200) {
// If the server did return a 200 OK response,
// then parse the JSON.
JwtToken = field from response ?? add to headers
return AuthenticationResponse.fromJson(jsonDecode(response.body));
} else {
// If the server did not return a 200 OK response,
// then throw an exception.
throw Exception('Failed to load players');
}
}
我的问题是如何从来自 c# 的 json 中获取 jwt token ,这通常是我的模型。
namespace Models
{
public partial class AuthenicationResponseOjbect {
public string Id { get; set; }
public int PlayerId { get; set; }
public Guid StoreId { get; set; }
public Guid UserId { get; set; }
public object FirstName { get; set; }
public object LastName { get; set; }
public string Username { get; set; }
public string JwtToken { get; set; }
public object RefreshToken { get; set; }
}
}
这是我的 Dart 模型
import 'package:flutter/gestures.dart';
class AuthenticationResponse {
final int userId;
final String JwtToken;
final String FirstName;
final String LastName;
const AuthenticationResponse({
required this.userId,
required this.JwtToken,
required this.FirstName,
required this.LastName,
});
Map<String, dynamic> toJson() => {
"userId": userId,
"firstName": FirstName,
"Lastname": LastName,
"JwtToken": JwtToken
};
factory AuthenticationResponse.fromJson(Map<String, dynamic> json) {
return AuthenticationResponse(
userId: json['userId'],
JwtToken: json['JwtToken'],
FirstName: json['firstName'],
LastName: json['LastName'],
);
}
}
另外,你如何通过 View 中的按钮加载它?显然,我需要将身份验证 token 添加到 header 中才能正常工作。我还需要将用户名和密码发送到/Login 端点。
感谢您的提前帮助
最佳答案
获取用户 token 并将其放入每个请求中的步骤如下:
1。登录登录端点并解析 json 正文。
注意:您正在使用 GET
端点。该端点无法处理请求正文。使用 POST
端点发送用户名
和密码
映射进行身份验证。否则,您当前的情况根本无法验证任何凭据。
Future<AuthenticationResponse> Authenticate() async {
const loginEndpoint = "$baseURL/Login";
http.Response response = await http.get(Uri.parse(loginEndpoint));
if (response.statusCode == 200) {
// If the server did return a 200 OK response,
// then parse the JSON.
Map<String, dynamic> user = jsonDecode(response.body);
return AuthenticationResponse.fromJson(user);
} else {
// If the server did not return a 200 OK response,
// then throw an exception.
throw Exception('Failed to load players');
}
}
2。将用户本地保存在安全存储或其他地方
Future saveUserLocally()async {
try {
final user = await Authenticate();
FlutterSecureStorage storage = FlutterSecureStorage();
storage.write(key: 'current_user', value: jsonEncode(user.toJson()));
} catch (e){
// handle errors here or in your providers, I use repository to handle this
}
}
3。创建一个全局 header 对象,其中包含您案例的所有 header (不包括 token )
Map<String, dynamic> get headers => <String, dynamic>{
'Content-Type':'application/json',
'Accept': 'application/json',
};
4。现在,在您的下一个请求中,在发出请求之前获取本地用户并更新 header 。
Future someRequest() async {
// get local user
FlutterSecureStorage storage = FlutterSecureStorage();
final user = jsonDecode(await storage.read('current_user'));
// Get global header
var header = headers;
// Add your token saved in user
header['access_token'] = user['JwtToken']; // key from your namespace
// Now, add the headers named header to http and make the call
await http.get('url here', headers: header);
...
}
这就是您通常调用 API 的方式。
注意:并非所有异常都在这里处理。您需要自己处理网络错误和PlatformExceptions
。此外,您还必须检查用户是否存在于本地存储中,并处理 401 未经授权的情况。如果出现 401 Unauthorized,您必须正常注销用户。
关于flutter - 了解 api 调用和 jwt token barrer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73213169/