我在flutter应用程序中处理oauth2身份验证。我正在考虑当我的API中的任何一个发生401认证错误时刷新令牌。那么如何为所有的http请求添加认证服务呢?在android中,我们有okhttp authenticator来检测任何API调用过程中的身份验证错误,并且可以刷新令牌并继续之前的API调用。在flutter中如何实现这一点呢?我不认为在所有的API中处理401错误是一个好的做法。
发布于 2020-08-28 01:23:00
使用dio拦截器
下面是我的拦截器中的一段代码
dio.interceptors
.add(InterceptorsWrapper(onRequest: (RequestOptions options) async {
/* Write your request logic setting your Authorization header from prefs*/
String token = await prefs.accessToken;
if (token != null) {
options.headers["Authorization"] = "Bearer " + token;
return options; //continue
}, onResponse: (Response response) async {
// Write your response logic
return response; // continue
}, onError: (DioError dioError) async {
// Refresh Token
if (dioError.response?.statusCode == 401) {
Response response;
var data = <String, dynamic>{
"grant_type": "refresh_token",
"refresh_token": await prefs.refreshToken,
'email': await prefs.userEmail
};
response = await dio
.post("api/url/for/refresh/token", data: data);
if (response.statusCode == 200) {
var newRefreshToken = response.data["data"]["refresh_token"]; // get new refresh token from response
var newAccessToken = response.data["data"]["access_token"]; // get new access token from response
prefs.refreshToken = newRefreshToken;
prefs.accessToken = newAccessToken; // to be used in the request section of the interceptor
return dio.request(dioError.request.baseUrl + dioError.request.path,
options: dioError.request);
}
}
return dioError;
}));
return dio;
}
}发布于 2019-09-18 02:44:22
我倾向于在客户端使用参数化所有应用程序接口调用的模式,就像在this code snippet中一样。这种方法应该适用于任何技术,尽管在某些技术中,您可以选择通过某种拦截器类来实现它。
https://stackoverflow.com/questions/57941368
复制相似问题