Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set SharedPreference in Authenticator?

I'm using Android. I store my auth token using SharedPreferences.

In order to refresh auth tokens, I use the Authenticator class.

Now, I need to be able to set the new auth token in the SharedPreferences, however, in order to do this, SharedPreferences requires a context.

How can I set the new (refreshed) auth token from the Authenticator class when I don't have a context?

Here is my Authenticator class:

public class TokenAuthenticator implements Authenticator {
    private String authToken;

    public TokenAuthenticator(String authToken) {
        this.authToken = authToken;
    }

    @Override
    public Request authenticate(Route route, Response response) throws IOException {
        if (responseCount(response) >= 3) {
            return null;
        }

        ApiInterface apiService = ApiClient.createService(ApiInterface.class, authToken);
        Call<BasicResponse> call = apiService.refreshAuthToken();
        BasicResponse apiResponse = call.execute().body();

        String newToken = apiResponse.getData().getToken();

        // Set the new token in shared preferences (how to get context?)
        SharedPreferences sp = getSharedPreferences(context);
        sp.edit().putString("AUTH_TOKEN", token).apply();

        return response.request().newBuilder()
                .header("Authorization", "Bearer " + newToken)
                .build();
    }

    private int responseCount(Response response) {
        int result = 1;
        while ((response = response.priorResponse()) != null) {
            result++;
        }
        return result;
    }

}

And here is where the Authenticator class is called from:

public class ApiClient {

    public static final String API_URL = "http://www.user324211.com/";

    private static OkHttpClient.Builder httpClient =
            new OkHttpClient.Builder();

    private static Retrofit.Builder builder =
            new Retrofit.Builder()
                    .baseUrl(API_URL)
                    .addConverterFactory(GsonConverterFactory.create());

    private static Retrofit retrofit = builder.build();

    public static Retrofit getRetrofit() {
        return retrofit;
    }

    public static <S> S createService(Class<S> serviceClass) {
        return createService(serviceClass, null);
    }

    public static <S> S createService(Class<S> serviceClass, final String authToken) {
        if (authToken != null) {
            TokenAuthenticator tokenAuthenticator = new TokenAuthenticator(authToken);
            httpClient.authenticator(tokenAuthenticator);
        }

        builder.client(httpClient.build());
        retrofit = builder.build();

        return retrofit.create(serviceClass);
    }

}
like image 888
user324211 Avatar asked Mar 04 '26 19:03

user324211


1 Answers

just add 1 more param

public TokenAuthenticator(Context context,String authToken) {
        this.authToken = authToken;
        this.mContext = context;
}

usage

TokenAuthenticator tA = new TokenAuthenticator(this,YOUR_AUTH_TOKEN);

EDIT

if no context call, just pass SharedPreferences instead

public TokenAuthenticator(SharedPreferences shared,String authToken) {
       this.authToken = authToken;
       this.mShared = shared;
}
like image 156
ZeroOne Avatar answered Mar 06 '26 09:03

ZeroOne



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!