I’m implementing Sign in with Apple on my web app. Due to Apple’s OAuth flow, instead of directly redirecting to the front-end, Apple sends the authentication response to the configured redirect_uri.
To handle this, I set my redirect_uri to a FastAPI backend route, which then performs a 307 Redirect to my front-end, appending the received code, state, and id_token as query parameters.
Issue
When Apple sends the request to my FastAPI backend, the API responds with a 307 Redirect, but the front-end doesn’t navigate as expected. Instead:
- The page remains blank, and no navigation happens.
- Refreshing the page does not resolve the issue.
- In local development, I get an “Invalid URL” error.
- However, when I manually click the browser’s address bar and press Enter, the page loads correctly.
My FastAPI Redirect Code
from fastapi.responses import RedirectResponse
...
@user_router.post("/apple/callback")
async def apple_callback(response: Response,
code: str = Form(None),
id_token: str = Form(None),
state: str = Form(None),
db: Session = Depends(get_db)):
payload = decode_identity_token(id_token, webClientId)
return RedirectResponse(f"={code}&state={state}&id_token={id_token}")
...
This is the partial project structure of my nextjs
enter image description here
This is the page code
Nextjs version 15.2.1
'use client';
import { createAppleUserWeb } from '@/service/user';
import { useSearchParams, useRouter } from 'next/navigation';
import { useEffect } from 'react';
import { toast } from 'sonner';
import Cookies from 'js-cookie';
import { useUserContext } from '@/provider/user-provider';
const AppleCreatePage = () => {
const { refreshUserInfo } = useUserContext();
const searchParams = useSearchParams();
const router = useRouter();
const code = searchParams.get('code');
const id_token = searchParams.get('id_token');
const state = searchParams.get('state');
if (!code || !id_token || !state) {
throw new Error('token error');
}
const onCreateAppleUser = async () => {
const [res, err] = await utils.to(
createAppleUserWeb({
code: code,
id_token: id_token,
state: state,
})
);
if (err) {
router.push('/login');
return;
}
if (!res) {
router.push('/login');
}
Cookies.set('access_token', res!.access_token, {
expires: res!.expires_in / 1000,
});
Cookies.set('refresh_token', res!.refresh_token);
refreshUserInfo();
router.push('/dashboard');
};
useEffect(() => {
onCreateAppleUser();
}, []);
return (
<div className='flex h-screen w-full items-center justify-center px-4'>
...
</div>
);
};
export default AppleCreatePage;
Successfully login by Sign in with Apple.
The backend redirect response can successfully router to the nextjs page.
Or, is this resolution for the sign in with apple process has something wrong, how can I resolve this?
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744783143a4593463.html
评论列表(0条)