I have a problem with getting authenticated user. Before it I got token and user id. Now i need to get user from server using access token and id. I have header format
Now I'am trying to add header with user token and id using interceptor.
My code:
Interceptor interceptor = new Interceptor() {
@Override
public okhttp3.Response intercept(Chain chain) throws IOException {
Request newRequest = chain.request().newBuilder()
.addHeader("Accept", "application/json")
.addHeader("authorization", token) <-??
.addHeader("driver_id", id) <-??
.build();
return chain.proceed(newRequest);
}
};
OkHttpClient.Builder okHttpBuilder = new OkHttpClient.Builder();
okHttpBuilder.addInterceptor(interceptor);
OkHttpClient okHttpClient = okHttpBuilder.build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.client(okHttpClient)
.build();
Interface:
@GET("driver/v1/driver")
Call<Driver> getAuthorizedDriver();
Different variants throws 401 error, don't know what to do Log:
I/Response code: 401
I/Response message: Unauthorized`
In JWT token authentication, the server-provided token should always be sent as a header with the Authorization: Bearer <token> format. The website then should check the validity of the token when a request comes and handle it accordingly. Yes, the use of HTTPS is mandatory.
This allows attackers to obtain sensitive data such as usernames, passwords, tokens (authX), database details, and any other potentially sensitive data.
You will have to create a Request interceptor ( BasicAuthInterceptor ) which extends Interceptor class of OkHttp library. Then, override intercept function and add your credentials into the request. Generate basic credentials with Credentials class of package OkHttp by using its basic function.
I got it. It's must look like:
@GET("driver/v1/driver")
Call<Driver> getAuthorizedDriver(@Header("authorization") String auth);
And auth:
Call<Driver> call = apiInterface.getAuthorizedDriver("Token token=" + token + ", driver_id=" + id);
Try to pass the header values via the method call:
@GET("driver/v1/driver")
Call<Driver> getAuthorizedDriver(@Header("authorization") String token,
@Header("driver_id") Integer id);
You also wouldn't have to deal with this huge chunk of Interceptor code
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With