Posts

Showing posts with the label Next Auth

A New Collection of Thoughtful Learning Apps — Now Available on iOS & Android

Image
I’m excited to share a set of mobile apps I’ve recently completed and published on both the Google Play Store and the Apple App Store. These apps are designed with a simple goal in mind: to make meaningful, structured content more accessible, whether you’re studying theology or improving your English vocabulary. 📱 Now Available on Both Platforms All apps are live and available for download: Google Play Developer Page: https://play.google.com/store/apps/dev?id=5835943159853189043 Apple App Store Developer Page: https://apps.apple.com/ca/developer/q-z-l-corp/id1888794100 📖 Theology & Confession Study Apps For those interested in Reformed theology and classical Christian teachings, I’ve developed a series of apps that present foundational texts in a clean, focused reading format: The Belgic Confession Canons of Dort Heidelberg Catechism Westminster Shorter Catechism Each app is designed to provide a distraction-free experience, making it easier to read, reflect, and revisit these im...

Next.js + NextAuth.js — SSO Security Hardening and Best Practices

Next.js + NextAuth.js — SSO Security Hardening and Best Practices This final post in the Next.js Frontend SSO series focuses on security and best practices for production-grade SSO. Even with a working authentication flow, neglecting security can lead to token leaks, session hijacking, or unauthorized access. 1️⃣ Secure session cookies NextAuth.js stores session information in cookies (JWT or database sessions). Configure cookies properly: httpOnly: prevents JavaScript access to cookies secure: ensure cookies are sent only over HTTPS SameSite: protect against CSRF (use "lax" or "strict") cookies: { sessionToken: { name: `__Secure-next-auth.session-token`, options: { httpOnly: true, sameSite: 'lax', path: '/', secure: process.env.NODE_ENV === 'production' } } } 2️⃣ Refresh token rotation Refresh tokens should be rotated to prevent replay attacks...

Next.js + NextAuth.js — Manager Approval Flow with Popup Login

Next.js + NextAuth.js — Manager Approval Flow with Popup Login In some workflows, you need a manager to approve actions without logging out the current user. This post shows how to implement a Manager Approval Flow using NextAuth.js and a separate popup login, ensuring valid manager roles and token handling. 1️⃣ Overview of the flow The flow works like this: The user triggers an action requiring manager approval. A popup opens with a separate NextAuth.js client configured for manager login. The manager signs in. We get the access_token and validate that the manager has the required role. If valid, send a message to the opener and close the popup. If invalid or login fails, show an error in the popup and allow retry. Always log out the manager and clear cookies after each approval attempt. 2️⃣ Setting up a separate client for manager login You need a separate Keycloak client ID for the manager flow, but the same provider: p...

NextAuth.js — Ensuring Linked Accounts Always Have the Latest Access Token

NextAuth.js — Ensuring Linked Accounts Always Have the Latest Access Token By default, when a user logs out and signs in again in NextAuth.js, the linked account may retain an old access token. This can cause issues if the access token has expired. To always have the latest token, you need to update the linked account during the signIn callback. 1️⃣ The default behavior NextAuth.js stores linked accounts in the database. On subsequent logins: The account is matched Access token is reused if not expired No automatic refresh occurs unless you explicitly handle it > Problem: If the access token is expired, API calls using that token will fail. 2️⃣ Update linked account on sign-in You can use the signIn callback in NextAuth.js to refresh tokens and update the database: import { PrismaAdapter } from "@next-auth/prisma-adapter"; import NextAuth from "next-auth"; import KeycloakProvider from "next-auth/prov...

Next.js + NextAuth.js — Debugging SSO Authentication and Token Issues

Next.js + NextAuth.js — Debugging SSO Authentication and Token Issues After integrating Keycloak with NextAuth.js and managing sessions and roles, the most common challenge is debugging SSO issues in a frontend application. In this post, we’ll show systematic ways to troubleshoot authentication, token, and redirect issues in Next.js. 1️⃣ Common frontend SSO issues Redirect loops: caused by mismatched callback URLs or session misconfiguration 401 Unauthorized: access token missing or expired 403 Forbidden: roles not mapped correctly Session not found: JWT or cookie not persisted properly 2️⃣ Inspecting session objects Always log your session object to verify tokens and roles: import { useSession } from "next-auth/react"; export default function Dashboard() { const { data: session } = useSession(); console.log("Session:", session); if (!session) return <p>Access denied</p>; return <div>Wel...

Next.js + NextAuth.js — Session Management and Role-Based Access

Next.js + NextAuth.js — Session Management and Role-Based Access In the previous post, we integrated Keycloak with NextAuth.js. Now we’ll focus on **managing sessions, applying roles, and protecting pages and API routes** in a Next.js frontend. 1️⃣ Accessing the session NextAuth.js provides two main ways to access the session: Client-side: using useSession() hook Server-side: using getSession() in getServerSideProps or API routes Example (client-side): import { useSession } from "next-auth/react"; export default function Dashboard() { const { data: session } = useSession(); if (!session) return <p>Please sign in</p>; return <div>Welcome {session.user.name}</div>; } Example (server-side): import { getSession } from "next-auth/react"; export async function getServerSideProps(context) { const session = await getSession(context); if (!session) { return { redirect: { ...

Next.js + NextAuth.js — Keycloak SSO Integration

Next.js + NextAuth.js — Keycloak SSO Integration In the previous post, we introduced NextAuth.js and the basic SSO concepts for frontend apps. Now we will integrate Keycloak with NextAuth.js and implement a full login flow in Next.js. Step 1: Configure Keycloak client Assuming you already have a Keycloak realm: Create a client for your Next.js app (e.g., nextjs-app ) Set Access Type to public or confidential depending on your security strategy Add valid redirect URIs: http://localhost:3000/api/auth/callback/keycloak Optional: configure roles and mappers Step 2: Install NextAuth.js in Next.js npm install next-auth Create the authentication API route: pages/api/auth/[...nextauth].js Step 3: Configure Keycloak provider in NextAuth.js import NextAuth from "next-auth"; import KeycloakProvider from "next-auth/providers/keycloak"; export default NextAuth({ providers: [ KeycloakProvider({ clientId...

Next.js + NextAuth.js — Introduction to Frontend SSO

Next.js + NextAuth.js — Introduction to Frontend SSO After setting up SSO on the backend with Spring Boot and Keycloak, the next step is to handle authentication on the frontend. In modern React/Next.js apps, NextAuth.js is the go-to solution for integrating SSO with OAuth2/OpenID Connect providers. What is NextAuth.js? NextAuth.js is a complete authentication solution for Next.js apps: Supports OAuth2, OpenID Connect, SAML (via providers) Session management for React and Next.js pages JWT support for APIs Role-based access control via callbacks It allows you to authenticate users against your IdP (e.g., Keycloak) and manage their sessions easily. Step 1: Install NextAuth.js In your Next.js project: npm install next-auth Then create a folder for API routes: pages/api/auth/[...nextauth].js NextAuth.js uses this as a dynamic route to handle all authentication requests. Step 2: Configure a provider (Keycloak example) C...