feat: fallback to auto-login on token failure and improve redirect logic
- In `useAuthHeaders`, import `useAutoLogin` and trigger login if `getAccessToken` returns a falsy value. This handles edge cases where the token is expired or missing during an API call. - In `useAutoLogin`, set the default redirect URL to `window.location.pathname` to ensure users return to the page they were on before logging in.
This commit is contained in:
parent
9c9b3735cb
commit
de05ca2ecf
@ -1,13 +1,19 @@
|
||||
import { useLogto } from "@logto/react"
|
||||
import { useEffect, useState } from "react";
|
||||
import { LOGTO_RESOURCE } from "../utils/constants";
|
||||
import useAutoLogin from "./useAutoLogin";
|
||||
|
||||
export const useAuthHeaders = (): HeadersInit => {
|
||||
const { isAuthenticated, getAccessToken } = useLogto();
|
||||
const { login } = useAutoLogin();
|
||||
const [headers, setHeaders] = useState<HeadersInit>({});
|
||||
useEffect(() => {
|
||||
if (isAuthenticated) {
|
||||
getAccessToken(LOGTO_RESOURCE).then(token => {
|
||||
if (!token) {
|
||||
login();
|
||||
return;
|
||||
}
|
||||
setHeaders({ Authorization: `Bearer ${token}` })
|
||||
});
|
||||
}
|
||||
|
||||
@ -3,7 +3,7 @@ import { useNavigate } from "react-router";
|
||||
|
||||
const useAutoLogin = () => {
|
||||
const navigate = useNavigate();
|
||||
const login = useCallback((redirect?: string) => {
|
||||
const login = useCallback((redirect = window.location.pathname) => {
|
||||
if (redirect) {
|
||||
sessionStorage.setItem('redirect', redirect);
|
||||
}
|
||||
|
||||
Loading…
Reference in New Issue
Block a user