【问题标题】:Unable to request with refreshed Token Retrofit无法使用刷新的令牌改造请求
【发布时间】:2020-11-22 21:36:52
【问题描述】:

我正在使用拦截器来刷新我过期的令牌。刷新后,我尝试使用新的刷新令牌发送原始请求。但是我无法使用新的 Token 发送请求。

如果令牌有效。应用程序运行良好。但是当 Token 无效时。我认为片段中的网络请求在刷新令牌请求之前......

请指导我...

拦截器

public class HttpInterceptor implements Interceptor {

@Override
public Response intercept(Chain chain) throws IOException {
    Request request = chain.request();

    //Build new request
    Request.Builder builder = request.newBuilder();
    builder.header("Accept", "application/json"); //if necessary, say to consume JSON

    String token = PrefUtils.getAppToken(HelloApplication.getContext()); //save token of this request for future
    setAuthHeader(builder, token); //write current token to request

    request = builder.build(); //overwrite old request
    Response response = chain.proceed(request); //perform request, here original request will be executed

    String body = response.peekBody(2048).string();
    try {
        APIStatus stat = new Gson().fromJson(body, APIStatus.class);
        Log.e("ARUL intercept: ", stat.getMessage());
        if (stat.getMessage().contains("Invalid Auth Token")) { //if unauthorized
            synchronized (this) { //perform all 401 in sync blocks, to avoid multiply token updates
                String currentToken = PrefUtils.getAppToken(HelloApplication.getContext()); //get currently stored token

                if (currentToken != null && currentToken.equals(token)) { //compare current token with token that was stored before, if it was not updated - do update

                    int code = refreshToken() / 100; //refresh token
                    if (code != 2) { //if refresh token failed for some reason
                        if (code == 4) //only if response is 400, 500 might mean that token was not updated
                            logout(); //go to login screen
                        return response; //if token refresh failed - show error to user
                    }
                }

                if (PrefUtils.getAppToken(HelloApplication.getContext()) != null) { //retry requires new auth token,
                    setAuthHeader(builder, PrefUtils.getAppToken(HelloApplication.getContext())); //set auth token to updated
                    request = builder.build();
                    return chain.proceed(request); //repeat request with new token
                }
            }
        }
    } catch (IllegalStateException | JsonSyntaxException exception) {
        Log.e("ARUL intercept: ", "GOT VALID REPSONSE!!! ");
    }

    return response;
}

private void setAuthHeader(Request.Builder builder, String token) {
    if (token != null) //Add Auth token to each request if authorized
        builder.header("auth_token", token);
}

private int refreshToken() {
    //Refresh token, synchronously, save it, and return result code
    //you might use retrofit here
    int status = 2;
    HelloApi mHelloApi = ServiceGenerator.provideHelloService();

    HashMap<String, RequestBody> partMap = new HashMap<>();
    String ID = PrefUtils.getUserID(HelloApplication.getContext());
    partMap.put("user_id", Utils.createPartFromString(ID));

    Call<APIStatus> register = mHelloApi.requestAccessToken(partMap);

    APIStatus mAPI = register.execute().body();
    PrefUtils.updateToken(HelloApplication.getContext(), mAPI.getToken());

    return status;
}

private int logout() {
    //logout your user
    return 4;
}

}

片段

@Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        mFactory = InjectorUtils.provideHomeFactory(getActivity());
        mViewModel = new ViewModelProvider(this, mFactory).get(HomeViewModel.class);

        if (mUser != null) {
            Log.e("User EMAIL > ", mUser.getEmail());
            Log.e("User ID > ", mUser.getUserID() + " > > " + mUser.getTokenAuthentication());

            fetchDashboard();
        }
    }
    
    
    private void fetchDashboard() {

        partMap.put("user_id", Utils.createPartFromString(mUser.getUserID()));

        mViewModel.getSnickers(partMap).observe(getActivity(), apiResponse -> {
            if (apiResponse != null) {
                mProgress.hide();
                mDiscoverRVAdapter.setItems(apiResponse.getEntityStickers());
                mDiscoverRVAdapter.notifyDataSetChanged();
            }
        });
    }

LOGCAT

2020-08-03 11:13:04.210 10708-10708/com.hello.helloapp E/User ID >: 70 > > %MoJCCdoVqrRipyYgFrCShBK#XX#jEhkebRWOUkUr#eRgOK
2020-08-03 11:13:04.231 10708-10734/com.hello.helloapp D/OkHttp: --> POST http://sandbox.hello.com/api/mapi/dashboard
2020-08-03 11:13:04.231 10708-10734/com.hello.helloapp D/OkHttp: Content-Type: multipart/form-data; boundary=3676a142-4869-46e1-b525-a3bdc72fe4a5
2020-08-03 11:13:04.231 10708-10734/com.hello.helloapp D/OkHttp: Content-Length: 240
2020-08-03 11:13:04.232 10708-10734/com.hello.helloapp D/OkHttp: --3676a142-4869-46e1-b525-a3bdc72fe4a5
2020-08-03 11:13:04.232 10708-10734/com.hello.helloapp D/OkHttp: Content-Disposition: form-data; name="user_id"
2020-08-03 11:13:04.232 10708-10734/com.hello.helloapp D/OkHttp: Content-Transfer-Encoding: binary
2020-08-03 11:13:04.232 10708-10734/com.hello.helloapp D/OkHttp: Content-Type: multipart/form-data; charset=utf-8
2020-08-03 11:13:04.232 10708-10734/com.hello.helloapp D/OkHttp: Content-Length: 2
2020-08-03 11:13:04.232 10708-10734/com.hello.helloapp D/OkHttp: 70
2020-08-03 11:13:04.232 10708-10734/com.hello.helloapp D/OkHttp: --3676a142-4869-46e1-b525-a3bdc72fe4a5--
2020-08-03 11:13:04.232 10708-10734/com.hello.helloapp D/OkHttp: --> END POST (240-byte body)
2020-08-03 11:13:04.238 10708-10734/com.hello.helloapp E/<HEADER>: Token Added > %MoJCCdoVqrRipyYgFrCShBK#XX#jEhkebRWOUkUr#eRgOK
2020-08-03 11:13:04.258 10708-10732/com.hello.helloapp I/OpenGLRenderer: Initialized EGL, version 1.4
2020-08-03 11:13:04.258 10708-10732/com.hello.helloapp D/OpenGLRenderer: Swap behavior 1
2020-08-03 11:13:04.259 10708-10732/com.hello.helloapp E/EGL_adreno: CreateContext rcMajorVersion:3, minorVersion:0
2020-08-03 11:13:04.272 10708-10732/com.hello.helloapp D/EGL_adreno: eglCreateContext: 0xb70052a0: maj 3 min 0 rcv 3
2020-08-03 11:13:04.313 10708-10732/com.hello.helloapp E/EGL_adreno: tid 10732: eglSurfaceAttrib(1582): error 0x3009 (EGL_BAD_MATCH)
2020-08-03 11:13:04.313 10708-10732/com.hello.helloapp W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0x9aa589e0, error=EGL_BAD_MATCH
2020-08-03 11:13:04.685 10708-10734/com.hello.helloapp E/ARUL intercept:: Invalid Auth Token
2020-08-03 11:13:04.714 10708-10734/com.hello.helloapp E/Current Token: %MoJCCdoVqrRipyYgFrCShBK#XX#jEhkebRWOUkUr#eRgOK
2020-08-03 11:13:04.719 10708-10734/com.hello.helloapp E/userID: > >70
2020-08-03 11:13:04.722 10708-10734/com.hello.helloapp D/OkHttp: --> POST http://sandbox.hello.com/api/mapi/get_token
2020-08-03 11:13:04.722 10708-10734/com.hello.helloapp D/OkHttp: Content-Type: multipart/form-data; boundary=810973ea-31be-4f2c-81c4-a7d57298d526
2020-08-03 11:13:04.722 10708-10734/com.hello.helloapp D/OkHttp: Content-Length: 240
2020-08-03 11:13:04.723 10708-10734/com.hello.helloapp D/OkHttp: --810973ea-31be-4f2c-81c4-a7d57298d526
2020-08-03 11:13:04.724 10708-10734/com.hello.helloapp D/OkHttp: Content-Disposition: form-data; name="user_id"
2020-08-03 11:13:04.724 10708-10734/com.hello.helloapp D/OkHttp: Content-Transfer-Encoding: binary
2020-08-03 11:13:04.724 10708-10734/com.hello.helloapp D/OkHttp: Content-Type: multipart/form-data; charset=utf-8
2020-08-03 11:13:04.724 10708-10734/com.hello.helloapp D/OkHttp: Content-Length: 2
2020-08-03 11:13:04.724 10708-10734/com.hello.helloapp D/OkHttp: 70
2020-08-03 11:13:04.724 10708-10734/com.hello.helloapp D/OkHttp: --810973ea-31be-4f2c-81c4-a7d57298d526--
2020-08-03 11:13:04.724 10708-10734/com.hello.helloapp D/OkHttp: --> END POST (240-byte body)
2020-08-03 11:13:05.140 10708-10734/com.hello.helloapp D/OkHttp: <-- 200 OK http://sandbox.hello.com/api/mapi/get_token (415ms)
2020-08-03 11:13:05.140 10708-10734/com.hello.helloapp D/OkHttp: Connection: Keep-Alive
2020-08-03 11:13:05.140 10708-10734/com.hello.helloapp D/OkHttp: X-Powered-By: PHP/7.2.29
2020-08-03 11:13:05.140 10708-10734/com.hello.helloapp D/OkHttp: Set-Cookie: ci_session=e06bfe493b4e0b656d5a2c5a7dfee86364307e78; expires=Mon, 03-Aug-2020 07:43:04 GMT; Max-Age=7200; path=/; HttpOnly
2020-08-03 11:13:05.141 10708-10734/com.hello.helloapp D/OkHttp: Expires: Thu, 19 Nov 1981 08:52:00 GMT
2020-08-03 11:13:05.141 10708-10734/com.hello.helloapp D/OkHttp: Cache-Control: no-store, no-cache, must-revalidate
2020-08-03 11:13:05.141 10708-10734/com.hello.helloapp D/OkHttp: Pragma: no-cache
2020-08-03 11:13:05.141 10708-10734/com.hello.helloapp D/OkHttp: Content-Type: text/html; charset=UTF-8
2020-08-03 11:13:05.141 10708-10734/com.hello.helloapp D/OkHttp: Vary: Accept-Encoding
2020-08-03 11:13:05.141 10708-10734/com.hello.helloapp D/OkHttp: Date: Mon, 03 Aug 2020 05:43:04 GMT
2020-08-03 11:13:05.141 10708-10734/com.hello.helloapp D/OkHttp: Server: LiteSpeed
2020-08-03 11:13:05.143 10708-10734/com.hello.helloapp D/OkHttp: {"message_code":1,"message":"Result found.","token_authentication":"UYCVHZkFKkMhqbR#tbZIOAboy%A#hvRVuecNC%mBjUBTk@H"}
2020-08-03 11:13:05.144 10708-10734/com.hello.helloapp D/OkHttp: <-- END HTTP (117-byte body)
2020-08-03 11:13:05.163 10708-10734/com.hello.helloapp D/OkHttp: <-- 200 OK http://sandbox.hello.com/api/mapi/dashboard (931ms)
2020-08-03 11:13:05.163 10708-10734/com.hello.helloapp D/OkHttp: Connection: Keep-Alive
2020-08-03 11:13:05.163 10708-10734/com.hello.helloapp D/OkHttp: X-Powered-By: PHP/7.2.29
2020-08-03 11:13:05.163 10708-10734/com.hello.helloapp D/OkHttp: Set-Cookie: ci_session=c7d4a52827268f0f33fe51594fb0c314a21129a6; expires=Mon, 03-Aug-2020 07:43:04 GMT; Max-Age=7200; path=/; HttpOnly
2020-08-03 11:13:05.164 10708-10734/com.hello.helloapp D/OkHttp: Expires: Thu, 19 Nov 1981 08:52:00 GMT
2020-08-03 11:13:05.164 10708-10734/com.hello.helloapp D/OkHttp: Cache-Control: no-store, no-cache, must-revalidate
2020-08-03 11:13:05.164 10708-10734/com.hello.helloapp D/OkHttp: Pragma: no-cache
2020-08-03 11:13:05.164 10708-10734/com.hello.helloapp D/OkHttp: Content-Type: text/html; charset=UTF-8
2020-08-03 11:13:05.164 10708-10734/com.hello.helloapp D/OkHttp: Vary: Accept-Encoding
2020-08-03 11:13:05.164 10708-10734/com.hello.helloapp D/OkHttp: Date: Mon, 03 Aug 2020 05:43:04 GMT
2020-08-03 11:13:05.164 10708-10734/com.hello.helloapp D/OkHttp: Server: LiteSpeed
2020-08-03 11:13:05.165 10708-10734/com.hello.helloapp D/OkHttp: {"message_code":404,"message":"Invalid Auth Token","response":"Invalid Auth Token"}
2020-08-03 11:13:05.165 10708-10734/com.hello.helloapp D/OkHttp: <-- END HTTP (83-byte body)
2020-08-03 11:13:05.171 10708-10708/com.hello.helloapp D/AndroidRuntime: Shutting down VM

更新

Refreshed Token 已成功存储在共享 Prefs 中。但是在重试原始请求时。它还在使用旧令牌吗?我该如何解决?

【问题讨论】:

  • 我建议做一个简单的复制并发布,请参阅sscce.org 其他人很难帮助解决这个问题。

标签: java android retrofit retrofit2 okhttp


【解决方案1】:

这个问题的原因是 refreshToken() 方法。您正在尝试进行异步调用,这意味着改造将创建另一个线程来执行刷新令牌 api。

而不是调用 register.enqueue 你应该调用它是异步的

register.execute 这将进行同步调用,并且应该从后台线程中使用。 例如查看此link

【讨论】:

  • 您的建议很有帮助。但是在重试原始请求时它仍然附加旧令牌?请检查更新....
  • @user3467240 您能否添加一个登录 setAuthHeader() 方法来确认我们是否确实从 sharedPreferences 获取了新令牌。
猜你喜欢
  • 2021-09-27
  • 2016-01-05
  • 2018-06-29
  • 1970-01-01
  • 1970-01-01
  • 2012-10-02
  • 2022-08-06
  • 2020-06-02
  • 1970-01-01
相关资源
最近更新 更多