简体   繁体   中英

Getting unauthorized error after setting the authorization token in the header of retrofit call

I am using retrofit2 with okhttp3. Here I have set my token but still, it shows unauthorized error. It did not go inside the try-catch of the below code.(ie) the token not get printed)

My approach is to use a single file for retrofit service and it will be used in all other calls.

Here is my code

public static Retrofit getClient() {
        Gson gson = new GsonBuilder()
                .setLenient()
                .create();
        OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder();
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        clientBuilder.addInterceptor(loggingInterceptor);

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(ApiConstant.SERVER_API)
                .client(createOkHttpClient())
                .client(clientBuilder.build())
                .addConverterFactory(GsonConverterFactory.create(gson))
                .build();

        return retrofit;
    }

 private static OkHttpClient createOkHttpClient() {
        final OkHttpClient.Builder httpClient = new OkHttpClient.Builder();

        if (isTokenRequired()) {
            if (!TextUtils.isEmpty(Profile.getToken())) {
                String token = Profile.getToken();
                httpClient.addInterceptor(
                        new Interceptor() {
                            @Override
                            public Response intercept(Interceptor.Chain chain) throws IOException {

                                Request newRequest = null;
                                try {
                                    System.out.println("token ==" + token);
                                     newRequest = chain.request().newBuilder()
                                            .header("Authorization", "Token " + token)
                                            .build();
                                    System.out.println("newRequest ===" + newRequest);

                                }  catch (Exception e) {
                                    e.printStackTrace();
                                }
                                return chain.proceed(newRequest);
                            }
                        });
            } else {
                throw new IllegalStateException("No Token");
            }
        }
        return httpClient.build();
    }

It's the Authorization Header which is incorrect (there is no such Authorization type). Token based Authentication is of the format Bearer <TOKEN> and not Token <TOKEN>

Also check if your Interceptor is actually added, which should work with the correction specified.

It worked after removing the HttpLoggingInterceptor

public static Retrofit getClient() {
        Gson gson = new GsonBuilder()
                .setLenient()
                .create();
     
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(ApiConstant.SERVER_API)
                .client(createOkHttpClient())
                .addConverterFactory(GsonConverterFactory.create(gson))
                .build();

        return retrofit;
    }

 private static OkHttpClient createOkHttpClient() {
        final OkHttpClient.Builder httpClient = new OkHttpClient.Builder();

        if (isTokenRequired()) {
            if (!TextUtils.isEmpty(Profile.getToken())) {
                String token = Profile.getToken();
                httpClient.addInterceptor(
                        new Interceptor() {
                            @Override
                            public Response intercept(Interceptor.Chain chain) throws IOException {

                                Request newRequest = null;
                                try {
                                    System.out.println("token ==" + token);
                                     newRequest = chain.request().newBuilder()
                                            .header("Authorization", "Token " + token)
                                            .build();
                                    System.out.println("newRequest ===" + newRequest);

                                }  catch (Exception e) {
                                    e.printStackTrace();
                                }
                                return chain.proceed(newRequest);
                            }
                        });
            } else {
                throw new IllegalStateException("No Token");
            }
        }
        return httpClient.build();
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM