Invalidate login when API authentication expires?
I'm trying to log a user out, and send them to the login page, if our API responds to say the session is invalid.
As an example, a login session is invalidated if someone logs in with the same account on a different browser/device.
Our API will start responding with a 401.
I can get the 401 via an axios interceptor. How can I kick the "check" login functionality at this point, to then handle the redirect to login?
5 Replies
Hey @johnwards! I'm the kapa.ai support bot. I've searched through the docs to try to answer your question. :wave:
----------------------
You can use the
useLogout
(https://refine.dev/docs/api-reference/core/hooks/auth/useLogout/) hook to call the logout
method of the authProvider
(https://refine.dev/docs/api-reference/core/providers/auth-provider/). This will log out the user and redirect them to the /login
page by default.
You can also provide a custom URL to the mutate
function of the useLogout
hook, which will override the one on the authProvider
.
Then, you can handle this URL in your logout
method of the authProvider
.
You can also use an axios interceptor (https://github.com/axios/axios#interceptors) to detect a 401 response from the API and call the logout
method.
----------------------useLogout | refine
useLogout data hook from refine is a modified version of react-query's useMutation for unauthentication.
GitHub
GitHub - axios/axios: Promise based HTTP client for the browser and...
Promise based HTTP client for the browser and node.js - GitHub - axios/axios: Promise based HTTP client for the browser and node.js
<@128446913274970112> kapa.ai is still learning and improving, please let us how it did by reacting below
stormy-gold•2y ago
@kapa.ai I don't think you can use useLogout in an axios interceptor. That looks to be breaking rules of hooks.
Ah!
Simply intercepting the error, deleting the local storage and then doing a
window.location.reload();
will do nicely
It's hacky, I'd rather redraw so I can pass a message. But it will do for now.
Any bright ideas about how to do this without reloading very welcome
I think it is a good solution 👏🏻