Android - Retrofit 2 - Authenticator Result

前端 未结 3 773
时光说笑
时光说笑 2020-12-29 15:46

I\'m trying to use Retrofit (2.0.0-beta3), but when using an Authenticator to add a token, I can\'t seem to get the data from the synchronous call. Our logging on the back-e

3条回答
  •  借酒劲吻你
    2020-12-29 16:28

    I managed to get a decent solution using the TokenAuthenticator and an Interceptor and thought I'd share the idea as it may help some others.

    Adding the 'TokenInterceptor' class that handles adding the token to the header is the token exists, and the 'TokenAuthenticator' class handles the case when there is no token, and we need to generate one.

    I'm sure there are some better ways to implement this, but it's a good starting point I think.

    public static class TokenAuthenticator implements Authenticator {
        @Override
        public Request authenticate( Route route, Response response) throws IOException {
        ...
        Session body = call.execute().body();
        Logger.d("Session token: " + body.token);
        // Storing the token somewhere.
        session.token = body.token;
        ...
    }
    
    
    private static class TokenInterceptor implements Interceptor {
    @Override
        public Response intercept( Chain chain ) throws IOException {
            Request originalRequest = chain.request();
    
            // Nothing to add to intercepted request if:
            // a) Authorization value is empty because user is not logged in yet
            // b) There is already a header with updated Authorization value
            if (authorizationTokenIsEmpty() || alreadyHasAuthorizationHeader(originalRequest)) {
                return chain.proceed(originalRequest);
            }
    
            // Add authorization header with updated authorization value to  intercepted request
            Request authorisedRequest = originalRequest.newBuilder()
                    .header("Auth-Token", session.token )
                    .build();
            return chain.proceed(authorisedRequest);
        }
    }
    

    Source:

    http://lgvalle.xyz/2015/07/27/okhttp-authentication/

提交回复
热议问题