Created
July 8, 2023 03:40
-
-
Save maitrungduc1410/544ed4254a6f3cf632f41f0f26003ea5 to your computer and use it in GitHub Desktop.
Sync session between Next Auth and Keycloak
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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: ["/"], | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.