I use Retrofit to query the server and parse responses. It is necessary to implement authorization using JWT. As I understand it, some requests that now work for everyone will be superimposed with a filter for the presence of a token. How to use Retrofit with JWT?
1 answer
Often JWT is passed to the request header . You can add @Header annotation
@GET("secret") Call<User> getSecret(@Header("Authorization") String token) And pass the desired line with each request.
You can also use the Interceptor and add a header in it, then you can not change requests.
final class AuthorizationRequestInterceptor implements Interceptor { private String token public AuthorizationRequestInterceptor(String token) { this.token = token; } @Override public Response intercept(Interceptor.Chain chain) throws IOException { Request originalRequest = chain.request(); if (originalRequest.body() == null || originalRequest.header("Authorization") != null) { return chain.proceed(originalRequest); } Request authorizedRequest = originalRequest.newBuilder() .header("Authorization", token) .method(originalRequest.method(), originalRequest.body()) .build(); return chain.proceed(authorizedRequest); } } - and existing requests need to be changed? - Serhei Ivanov
- I added Interceptor to the answer. it allows you to add a token to all requests. - Mikhail Vaysman
- For reauthorization, it's better to use Authenticator, not Interceptor. Otherwise, with parallel requests, you will get a lot of trouble with multiple authorizations and tokens ... innodroid.com/blog/post/using-okhttp-authenticator - Yura Ivanov
- and how to use an instance of AuthorizationRequestInterceptor directly when creating a Retrofit client? - Serhei Ivanov
- @SerheiIvanov I will now look at the Authenticator, redo the answer and add how to use. - Mikhail Vaysman
|