Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Authentication Apollo Graphql for android

I'm developing an android application that uses GraphQL as the back-end. I have the query and mutation part working perfectly. But I couln't find any documentations for authentication.

So how can I pass the username and password to the server and authenticate it?

LocalApolloClient.java :

public class LocalApolloClient {
    private static final String URL = "http://192.168.1.100/graphql/";
    private static ApolloClient apolloClient;
    private static String authHeader = "";


    public static ApolloClient getApolloClient(){
        //HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
        //loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .addInterceptor(chain -> {
                    Request original = chain.request();
                    Request.Builder builder = original.newBuilder().method(original.method(), original.body());
                    builder.header("Authorization", authHeader);
                    return chain.proceed(builder.build());
                })
                .build();

        apolloClient = ApolloClient.builder()
                .serverUrl(URL)
                .okHttpClient(okHttpClient)
                .build();

        return apolloClient;
    }
}

Please note :

  • This is not a duplicate question
  • There is no proper documentation for graphQl

So kindly Justify if you negative vote.

like image 378
Vimal Joe Avatar asked Jan 01 '23 20:01

Vimal Joe


1 Answers

You need to set the header on ApolloClient, not on the OkHttpClient. Something like this:

ApolloClient.builder()
            .serverUrl(context.getString(R.string.graphql_base_url))
            .addApplicationInterceptor(object: ApolloInterceptor {
                override fun interceptAsync(
                    request: ApolloInterceptor.InterceptorRequest,
                    chain: ApolloInterceptorChain,
                    dispatcher: Executor,
                    callBack: ApolloInterceptor.CallBack
                ) {
                    val newRequest = request.toBuilder().requestHeaders(RequestHeaders.builder().addHeader("Authorization", "Basic ...").build()).build()
                    chain.proceedAsync(newRequest, dispatcher, callBack)
                }

                override fun dispose() {
                }
            }).build()
like image 192
TpoM6oH Avatar answered Jan 13 '23 10:01

TpoM6oH