Skip to content

Instantly share code, notes, and snippets.

@maitrungduc1410
Created July 8, 2023 03:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save maitrungduc1410/544ed4254a6f3cf632f41f0f26003ea5 to your computer and use it in GitHub Desktop.
Save maitrungduc1410/544ed4254a6f3cf632f41f0f26003ea5 to your computer and use it in GitHub Desktop.
Sync session between Next Auth and Keycloak
import { withAuth } from "next-auth/middleware";
export default withAuth(
{
pages: {
signIn: "/auth/signin",
},
callbacks: {
authorized: async ({ token }) => {
if (!(token as any)?.id_token) return false;
const headers = new Headers();
headers.append("Content-Type", "application/x-www-form-urlencoded");
const urlencoded = new URLSearchParams();
urlencoded.append("client_id", process.env.KEYCLOAK_CLIENT_ID || "");
urlencoded.append(
"client_secret",
process.env.KEYCLOAK_CLIENT_SECRET || ""
);
urlencoded.append("token", (token as any).id_token);
const requestOptions: RequestInit = {
method: "POST",
headers,
body: urlencoded,
redirect: "follow",
};
try {
const response = await fetch(
`${process.env.KEYCLOAK_ISSUER}/protocol/openid-connect/token/introspect`,
requestOptions
);
const json = await response.json();
if (!json.active) {
return false;
}
return true;
} catch (error) {
console.log(error);
return false;
}
},
},
}
);
export const config = {
// add your routes here
matcher: ["/"],
};
@maitrungduc1410
Copy link
Author

maitrungduc1410 commented Jul 8, 2023

This middleware is to ensure that we validate Keycloak Sessionon page load, if session is invalid/expired/revoke, we'll invalidate NextAuth session and force login.

Since this one is called from server side, so KEYCLOAK_ISSUER can be private hostname of keycloak for faster + more secure request

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment