Reputation: 2136
I am making an android app which has a django rest api as the backend and want to make authenticated network calls using the token given to the user when he/she has logged in.
I am using retrofit to make requests to the backend. Here is what I am doing right now to attempt to make an authenticated network call to the rest api.
@Override
public void loadAllUsers() {
Call<List<User>> call = userServiceApi.loadAllUsers();
call.enqueue(new Callback<List<User>>() {
@Override
public void onResponse(@NonNull Call<List<User>> call, @NonNull Response<List<User>> response) {
if (response.isSuccessful()) {
List<User> users = response.body();
eventBus.post(new LoadAllUsersEvent(users));
} else {
eventBus.post(new FailLoadAllUsersEvent());
Log.d(TAG, response.message());
}
}
@Override
public void onFailure(@NonNull Call<List<User>> call, @NonNull Throwable t) {
eventBus.post(new LoadUsersUnreachableServerEvent());
Log.d(TAG, t.toString());
}
});
}
Here is the retrofit interface relevant to this api request:
@GET("users/")
Call<List<User>> loadAllUsers(@Header("Authorization: Token ") Token token);
When I make this call passing the user's token in as the header, I get status code 401: Unauthenticated: "GET /users/ HTTP/1.1" 401 58
What am I doing wrong for django rest Token Authentication to work and to make an authenticated django rest api call?
Upvotes: 2
Views: 1372
Reputation: 2266
The quick fix for this would be to change your api interface:
@GET("users/")
Call<List<User>> loadAllUsers(@Header("Authorization") Token token);
Value you are passing in should be formated as "Token %s"
.
This is not a very good solution, because you'd have to pass the token around to all of your api calls.
Better way to solve your authorization issues is by using OkHttp client and implement authenticator, which takes care of everything for you.
OkHttp and Retrofit work together very well.
Upvotes: 4