Implement Auth Interceptor
This commit is contained in:
parent
c49efba57d
commit
d8f85844e6
@ -1,6 +1,9 @@
|
||||
package core.notevault.sync;
|
||||
|
||||
import android.content.Context;
|
||||
import android.content.SharedPreferences;
|
||||
import core.notevault.sync.auth.AuthInterceptor;
|
||||
import okhttp3.OkHttpClient;
|
||||
import retrofit2.Retrofit;
|
||||
import retrofit2.converter.gson.GsonConverterFactory;
|
||||
|
||||
@ -9,8 +12,14 @@ public class ApiClient {
|
||||
|
||||
public static Retrofit getRetrofitInstance(Context context) {
|
||||
if (retrofit == null) {
|
||||
SharedPreferences sharedPreferences = context.getSharedPreferences("app_prefs", Context.MODE_PRIVATE);
|
||||
OkHttpClient client = new OkHttpClient.Builder()
|
||||
.addInterceptor(new AuthInterceptor(sharedPreferences))
|
||||
.build();
|
||||
|
||||
retrofit = new Retrofit.Builder()
|
||||
.baseUrl("http://192.168.178.30:8080/")
|
||||
.client(client)
|
||||
.addConverterFactory(GsonConverterFactory.create())
|
||||
.build();
|
||||
}
|
||||
|
@ -0,0 +1,31 @@
|
||||
package core.notevault.sync.auth;
|
||||
|
||||
import android.content.SharedPreferences;
|
||||
import okhttp3.Interceptor;
|
||||
import okhttp3.Request;
|
||||
import okhttp3.Response;
|
||||
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
public class AuthInterceptor implements Interceptor {
|
||||
private SharedPreferences sharedPreferences;
|
||||
|
||||
public AuthInterceptor(SharedPreferences sharedPreferences) {
|
||||
this.sharedPreferences = sharedPreferences;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Response intercept(Chain chain) throws IOException {
|
||||
Request originalRequest = chain.request();
|
||||
|
||||
String token = sharedPreferences.getString("jwt_token", null);
|
||||
if (token == null) {
|
||||
return chain.proceed(originalRequest);
|
||||
}
|
||||
|
||||
Request authenticatedRequest = originalRequest.newBuilder()
|
||||
.header("Authorization", "Bearer " + token).build();
|
||||
return chain.proceed(authenticatedRequest);
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user