Hi,
Currently, I have an auth bloc which holds an access token when the user is logged in.
On many of my HTTP requests, I need to send the access token to my back-end.
I am creating a re-usable function to handle all protected HTTP requests that require an access token to be sent. This will be reusable so I don't have to keep passing the access token from my UI layer to my API layer. However, I'm not sure how to access the Auth Bloc from this function since it is not in the widget tree
Data flows like so when I make an HTTP request (based on felangel's flutter bloc tutorials):
UI -> bloc -> repository -> api
and then:
api -> repository -> bloc -> UI
I have a BlocProvider near the top of my app to provide the AuthBloc, like so:
return BlocProvider(
builder: (BuildContext context) =>
AuthBloc(authRepository: authRepository),
child: Scaffold(
...
And here is my re-usable function for protected requests. I need to access the Auth Bloc in this function, but I'm not entirely sure how to.
Future<dynamic> protectedRequest(
{accessToken, endpoint, dynamic body}) async {
final uri = Uri.https(baseUrl, endpoint);
final response = await http.post(uri,
body: body, headers: {'Authorization': 'Bearer ' + accessToken});
if (response.statusCode == 200 || response.statusCode == 201) {
return response;
} else {
throw Exception();
}
}
Any help is appreciated!
Thank You
Hi @theweiweiway 馃憢
Thanks for opening an issue!
Regarding your question, I would recommend handling this differently. Managing http tokens is a low level networking layer responsibility so I when you first request the token, I would write it to keystore/keychain using flutter_secure_storage and then I would use an interceptor to handle adding the token to every http request transparently.
Hope that helps 馃憤
Wow, thanks for the quick response. Thank you so much
Most helpful comment
Wow, thanks for the quick response. Thank you so much