Next.js Discord

Discord Forum

Can't figure out how to use OIDC/OAuth2 with app router

Answered
Shivam posted this in #help-forum
Open in Discord
I have a REST API at http://backend/api/ which is a resource server, an Keycloak realm (oauth provider) at http://auth/realm/main.

I can't quite figure out how it'll all work out expecially with app router. Do I store the access token client side? How do I do that?

And how do I use that to fetch()? fetch needs to happen in server side right?

I also took a look at next-auth. It didn't look like an oauth2 client.

Please help me out. Thanks!
Answered by tafutada777
my poc proj could help. it uses Google OAuth, get a google access token, store it in JWT, grab it from session, invoke Google Calender API with the access toke from jwt. if it is what u wanna do.
https://github.com/tfutada/zenn-nextjs/blob/main/app/google-calendar/page.tsx
View full answer

9 Replies

For server-side fetching, we mostly use an API key (stored in environment variables).
For client-side fetching, just handle the access token on the client side
@Shivam Auth.js (next-auth) supports OAuth 2.0. Indeed, it works with Google, GitHub, FB and so on.
OAuth provider tokens can be stored in JWT or DB, so you can fetch it from session, pass it to upstream APIs such as Google Calender API.
https://authjs.dev/reference/core/providers_keycloak
my poc proj could help. it uses Google OAuth, get a google access token, store it in JWT, grab it from session, invoke Google Calender API with the access toke from jwt. if it is what u wanna do.
https://github.com/tfutada/zenn-nextjs/blob/main/app/google-calendar/page.tsx
Answer
okay I get it. I don't have callbacks. I guess that's why there's no access token in my session.
Thank you very much. I'll try this out.
@tafutada777 my poc proj could help. it uses Google OAuth, get a google access token, store it in JWT, grab it from session, invoke Google Calender API with the access toke from jwt. if it is what u wanna do. https://github.com/tfutada/zenn-nextjs/blob/main/app/google-calendar/page.tsx
Hey, I wrote something based on the code you shared. But accessToken gets expired. Isn't next-auth supposed to refresh it automatically like every oauth2 client does? Or am I missing some config?
in my sample code, refresh tokes is retrieved, so u can invoke Google API along with refresh token. then get a new token with the refresh token.
https://authjs.dev/guides/basics/refresh-token-rotation
@Shivam Hey, I wrote something based on the code you shared. But accessToken gets expired. Isn't next-auth supposed to refresh it automatically like every oauth2 client does? Or am I missing some config?
I having the same issue with refresh token where they are not refreshing for the Google Provider. Were you able to get it working?