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:
kyuuseiryuu 2026-03-16 12:51:39 +09:00
parent 9c9b3735cb
commit de05ca2ecf
2 changed files with 7 additions and 1 deletions

View File

@ -1,13 +1,19 @@
import { useLogto } from "@logto/react" import { useLogto } from "@logto/react"
import { useEffect, useState } from "react"; import { useEffect, useState } from "react";
import { LOGTO_RESOURCE } from "../utils/constants"; import { LOGTO_RESOURCE } from "../utils/constants";
import useAutoLogin from "./useAutoLogin";
export const useAuthHeaders = (): HeadersInit => { export const useAuthHeaders = (): HeadersInit => {
const { isAuthenticated, getAccessToken } = useLogto(); const { isAuthenticated, getAccessToken } = useLogto();
const { login } = useAutoLogin();
const [headers, setHeaders] = useState<HeadersInit>({}); const [headers, setHeaders] = useState<HeadersInit>({});
useEffect(() => { useEffect(() => {
if (isAuthenticated) { if (isAuthenticated) {
getAccessToken(LOGTO_RESOURCE).then(token => { getAccessToken(LOGTO_RESOURCE).then(token => {
if (!token) {
login();
return;
}
setHeaders({ Authorization: `Bearer ${token}` }) setHeaders({ Authorization: `Bearer ${token}` })
}); });
} }

View File

@ -3,7 +3,7 @@ import { useNavigate } from "react-router";
const useAutoLogin = () => { const useAutoLogin = () => {
const navigate = useNavigate(); const navigate = useNavigate();
const login = useCallback((redirect?: string) => { const login = useCallback((redirect = window.location.pathname) => {
if (redirect) { if (redirect) {
sessionStorage.setItem('redirect', redirect); sessionStorage.setItem('redirect', redirect);
} }