Flutter HTTP Authorized Requests
In every day practise of programming you will need to do authorized requests to your server (API calls). One can use the differents libraries for this, but I really liked the Chopper
(https://pub.dev/packages/chopper). There is a conception of Request
and Response
interceptors (just like in Retrofit), which allows you to easily create the network layer.
So, when you are setting up your WebService using the Chopper
you will write something like this:
interceptors: [
// Auth Interceptor
(Request request) async => applyHeader(request, 'authorization',
SharedPrefs.localStorage.getString(tokenHeader),
override: false),
(Response response) async {
if (response?.statusCode == 401) {
SharedPrefs.localStorage.remove(tokenHeader);
// Navigate to some login page or just request new token
}
return response;
},
HttpLoggingInterceptor(),
]
In this example wer are adding header with token, if it is present in our local storage. And we can also intercept the incoming response and check if the token is expired.