-
Notifications
You must be signed in to change notification settings - Fork 23
Make authenticated API calls #46
Description
Steps to reproduce
After authentication, I store the accessToken in my redux state (and after that redux-persist automatically stores it in localStorage).
What I want to achieve is: Make every feathers API call with the accessToken, if it's present in the redux state.
What I'm doing now:
export const app = feathers(); // + configure rest, hooks...
// Append accessToken in header if present.
// It would be better to take the accessToken from redux state,
// but for now we keep this solution (i.e. take directly from
// localStorage)
app.hooks({
before: hook => {
const item = window.localStorage.getItem('persist:myApp'); // This is where redux-persist saves the accessToken
if (item) {
const { auth } = JSON.parse(item);
const { accessToken } = JSON.parse(auth);
if (!accessToken) {
return;
}
hook.params.headers = {
Authorization: `Bearer ${accessToken}`,
...hook.params.headers
};
return hook;
}
}
});
So what I'm doing is, before each API request, retrieve the accessToken from the localStorage (and not from the in-memory store!).
Expected behavior
There should surely be a way to do this without retrieving localStorage and parsing JSON before each api request.
Actual behavior
Didn't find a clean way to pass state variables to the feathers app.
The only way I found is, on every api request, do
componentWillMount() {
this.props.findUsers({ // findUsers dispatches feathersRedux.users.find
headers: { Authorization: `Bearer ${this.props.auth.accessToken}` }
})
}
But doing this on every method is not viable.
System configuration
Tell us about the applicable parts of your setup.
Module versions 2.1.0
NodeJS version: Not relevant
Operating System: Not relevant
Browser Version: Not relevant
React Native Version: Not relevant
Module Loader: Not relevant