【发布时间】:2020-07-07 23:32:40
【问题描述】:
我正在使用 Retrofit 与我的服务器通信。 我必须先调用登录端点,然后我得到一个 cookie(身份验证令牌),我自动存储它,并且正在授权以下请求。 如果 1 小时内没有请求,则此“会话”过期。
我应该如何进行自动重新认证? 显然这不是一个好主意,我在每个“真实”请求之前使用用户名/密码 ping 登录端点,以确保我的客户端尚未过期。
我尝试向 okHttpClient 添加拦截器,并检查我的“真实”响应(不是登录)是否返回代码 401。在这种情况下,我应该调用登录端点,然后,我必须重复“真实”响应" 调用。
如何“保存”请求、调用登录,然后在再次通过身份验证时重复第一个请求?
private static Retrofit retrofit;
public static Retrofit getClient( final Context context ) {
if ( retrofit == null ) {
ClearableCookieJar cookieJar =
new PersistentCookieJar(new SetCookieCache(), new SharedPrefsCookiePersistor(context));
final OkHttpClient okHttpClient =
new OkHttpClient.Builder()
.followSslRedirects(false)
.followRedirects(false)
.cookieJar(cookieJar)
.addInterceptor(chain -> {
Request request = chain.request();
Response response = chain.proceed(request);
if ( response.code() == 401 ) {
if ( !response.message().contains("Incorrect") ) {
// THIS IS THE CASE, when I try to call an endpoint with expired token
// I need to call login again, and then repeat this failed request
}
}
return response;
})
.build();
retrofit = new Retrofit.Builder()
.baseUrl(URL)
.addConverterFactory(GsonConverterFactory.create())
.client(okHttpClient)
.build();
}
return retrofit;
}
显然我可以手动检查每个请求的响应代码,如果是 401,我调用 login,完成后,我再次调用我的请求。但是我希望有一个更简单的(带有拦截器的内置解决方案,所以我不必到处实现这个逻辑)
【问题讨论】:
-
只需进行网络调用即可在您捕获过期令牌的地方登录
-
谢谢,我不知道有这样的东西,但这正是我需要的。我无法在 cmets 中接受您的回答:/