使用remix-auth-auth0登录后如何重定向到原始页面



相关:在remix-auth中登录/注册后如何重定向回原始页面?

如果用户试图访问受保护的路由,我希望他登录,然后重定向到该路由。

使用remix-auth,我在protected route中设置了这个:

export let loader: LoaderFunction = async ({ request }) => {
return await authenticator.isAuthenticated(request, {
failureRedirect: "/login?redirectTo=/search",
});
};

然后在我的登录路由中:

export let loader: LoaderFunction = async ({ request }) => {
return await login(request);
};

函数login()为:

export async function login(request: Request) {
let url = new URL(request.url);
let returnTo = url.searchParams.get("redirectTo") as string | null;

try {
// call authenticate as usual, in successRedirect use returnTo or a fallback
return await authenticator.authenticate("auth0", request, {
successRedirect: returnTo ?? "/search",
failureRedirect: "/",
});
} catch (error) {
if (error instanceof Response && error.redirected) {
const returnToCookie = createCookie("returnToCookie");
error.headers.append(
"Set-Cookie",
await returnToCookie.serialize(returnTo)
);
}
throw error;
}
}

最后的回调路由是:

export let loader: LoaderFunction = async ({ request }) => {
//get the returnTo from the cookie
const returnToCookie = createCookie("returnToCookie");
const result = await returnToCookie.parse(request.headers.get("Cookie"));
let returnTo = (result) ?? "/";
return await authenticator.authenticate("auth0", request, {
successRedirect: returnTo,
failureRedirect: "/",
});
};

问题是login()函数当前将用户重定向到回调url(带有url中的代码),但在cookie中没有任何特殊内容,因此回调路由使用回调。

如果我在登录路由中尝试&catch login()函数,获得的错误是一个响应,但不是重定向,所以在cookie中也没有什么特别的(我真的不知道如何处理这个响应错误)

我不确定我在最初的帖子中错过了什么。

经过一些尝试,我找到了解决方案:
login()函数返回一个302 HTTP代码,这是一个重定向,但不触发if (error instanceof Response && error.redirected)

只要去掉&& error.redirected的条件就可以使重定向工作完美。

最新更新