Custom Oauth Provider with NextAuth, with Nextjs only as the frontend and a custom backend?
situation
- Im using nextjs only as the frontend.
- with a custom java backend.
- with an arbitrary 3rd party oauth authorization server.
- with nextauth.
How do i implement the code flow of the custom oauth provider for frontend?
- IMOPRTANT: I dont use Nextjs on the backend. Its meant for frontend.
- Note:
Im not asking how to use CredentialsProvider with Email & Password on my backend server (I already had this implemented.);
Im asking on autentication with a 3rd party oauth authorization server.
All I can think of is following, but I have question on How on some steps:
attempt 1:
- the frontend sends the user to the url of the authorization server.
- (How the url should be constructed?)
- the frontend gets the authorization_code by redirection
- the frontend sends the authorization_code to the Java backend
- Do i just send a request immediately when the page is loaded, by
useEffect
?
- Do i just send a request immediately when the page is loaded, by
- the frontend gets a JWT (access token & refresh token) from the backend by response
- the frontend put the JWT & userInfo inside the user Session of nextauth.
- How? The code? In [...nextauth]/route.ts?
- (this is for: the frontend can then use
useSession
to determine if the user is login-ed,
also check if token is still valid & refresh if needed in thejwt
callback)
- the user session is established
attempt 2:
- the frontend sends the user to a backend url
- (or receive a redirect url from backend?)
- the backend deals with sending the user to the url of the authorization server, authorization_code, etc (things the frontend wont care)
- the backend redirect the frontend to a page.
- (For what, passing data or?)
- the frontend gets a JWT (access token & refresh token) from the backend.
- How? After those redirections, I dont think the frontend has any request-response connection with backend any more.
- the frontend put the JWT & userInfo inside the user Session of nextauth.
- How? The code? In [...nextauth]/route.ts?
- the user session is established
I dont trust GPT answers, because:
- They always mixing my nextjs into the backend, which I dont want to, because I have a Java backend that should be dealing with security.
- They fail to explain how the function works in NextAuth.
- They fail to explain the redirecting and data flow.
- The answers are insecure, especially after many redirections. After questioning couple more times they either give hacks or denying themselves.
version
"next": "15.1.6",
"next-auth": "^4.24.11",
"react": "^19.0.0",