【问题标题】:Android retrofit repeat request after token expired?令牌过期后Android改造重复请求?
【发布时间】: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,完成后,我再次调用我的请求。但是我希望有一个更简单的(带有拦截器的内置解决方案,所以我不必到处实现这个逻辑)

【问题讨论】:

标签: android rest retrofit


【解决方案1】:

登录响应后,保存token,然后携带此token与服务器通信,用户无需再次登录。

当应用在任何请求期间收到类似“401:expired token”的响应时,只需删除保存的令牌和所有用户数据,并显示一个对话框让用户跳转到 LoginActivity。然后重复。

【讨论】:

  • 我正在这样做,但是在 1 小时没有客户端-服务器通信后,令牌将过期。在这种情况下,我不希望用户手动登录。如果用户成功登录一次,我会保存数据,并在真正请求之前自动发出登录请求(如果令牌已经过期)
  • @CookieMonster 好的,我明白了,你需要一个刷新令牌的 API,这个 API 永远不会返回“过期令牌”,只需发送旧令牌,服务器返回新令牌,如果请求失败,仍需手动登录。通常我们不这样做,我们只是将令牌过期时间设置为一周甚至一个月。
猜你喜欢
  • 2011-05-04
  • 2019-03-21
  • 2017-01-10
  • 2016-12-15
  • 1970-01-01
  • 2019-09-05
  • 2015-02-21
  • 2016-09-06
  • 1970-01-01
相关资源
最近更新 更多