Posts

Showing posts with the label SSO

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...

SSO for Spring WebFlux — Reactive Authentication and Authorization

SSO for Spring WebFlux — Reactive Authentication and Authorization Reactive applications introduce new challenges for SSO. Spring WebFlux does not use thread-local security context like MVC, so you must handle authentication and authorization differently. 1️⃣ Reactive context vs thread-local In Spring MVC: SecurityContextHolder uses thread-local storage Filters populate authentication before reaching controllers In WebFlux: No thread-local — reactive chains pass context via Reactor Context Logging or accessing SecurityContextHolder.getContext() outside the reactive chain often returns null Debug tip: Always log authentication inside Mono/Flux using deferContextual . 2️⃣ Integrating Keycloak with WebFlux Use keycloak-spring-boot-starter with spring-security-webflux dependencies. Key steps: Configure reactive security adapter Set SecurityWebFilterChain bean Map Keycloak roles to reactive authorities ...

Debugging SSO Authentication — Common Issues in Spring Boot

Debugging SSO Authentication — Common Issues in Spring Boot After integrating Keycloak (or any SSO provider) with Spring Boot, the most common question developers face is: “My SSO login works sometimes, but other times I get 403, redirect loops, or the roles are wrong. How do I debug this?” This post shows **systematic ways to debug SSO authentication issues** and avoid guessing. 1️⃣ Token not being parsed or expired SSO usually involves JWTs or tokens issued by the IdP. Common mistakes: Token expired — default Keycloak token is 5 minutes Token not sent in Authorization header Token audience mismatch Debug tip: Log the raw token and validate it using jwt.io or Keycloak admin console. 2️⃣ Roles not mapped correctly Even if the token is valid, access can fail if roles/authorities are missing: Check Keycloak client and realm roles Ensure Spring Security maps Keycloak roles to authorities Remember hasRole("ADMIN...

Integrating Keycloak with Spring Boot — A Practical Guide

Integrating Keycloak with Spring Boot — A Practical Guide After understanding the core concepts of SSO, it’s time to see a **real implementation**. In this post, we integrate **Keycloak** with a Spring Boot application, showing login flows, adapters, and configuration. What is Keycloak? Keycloak is an open-source Identity and Access Management (IAM) solution that supports: Single Sign-On (SSO) OAuth2 and OpenID Connect LDAP / Active Directory integration User federation, roles, and fine-grained authorization It acts as the **Identity Provider (IdP)**, while your Spring Boot app acts as the **Service Provider (SP)**. Step 1: Set up Keycloak 1. Download and run Keycloak (standalone or container): docker run -p 8080:8080 -e KEYCLOAK_ADMIN=admin -e KEYCLOAK_ADMIN_PASSWORD=admin quay.io/keycloak/keycloak:latest start-dev 2. Log in to Keycloak admin console: http://localhost:8080/ 3. Create a realm (e.g., springboot-sso ) 4. Cre...

Understanding SSO: Concepts and Protocols

Understanding SSO: Concepts and Protocols Single Sign-On (SSO) is one of the most common authentication strategies in modern enterprises. Instead of logging into multiple applications separately, SSO allows a user to: Authenticate once Access multiple applications without re-login This post explains the **core concepts**, popular protocols, and why SSO is widely used. What is SSO? SSO is a user authentication process that permits a user to access multiple applications with **one set of credentials**. Benefits include: Improved user experience — fewer logins Centralized authentication management Reduced password fatigue and security risks How SSO works — high-level flow The typical SSO flow: User tries to access an application (Service Provider / SP) SP redirects to an Identity Provider (IdP) User authenticates at IdP IdP issues a token or assertion SP validates token and grants access After th...