I have a NextJs Application and want to integrate Authentication with Keycloak. The Application runs in Docker Containers. I created an API Route that should handle the Login with Keycloak. The page itself works. The Login Button from Keycloak is displayed but when i click on this Button an Error is displayed that the connection to the Keycloak URL was refused. I cant figure out what the Problem is.
I use NextJs 14 and Keycloak 25.0.1
This is my docker-compose.yml:
version: '3.8'
services:
nextjs:
build: .
ports:
- '3000:3000'
depends_on:
- mysql
volumes:
- .:/app
command: sh -c "npm run dev"
mysql:
image: mysql:8.0
ports:
- '3306:3306'
command: ["mysqld", "--init-file=/docker-entrypoint-initdb.d/init.sql"]
volumes:
- mysql-data:/var/lib/mysql
- ./docker-entrypoint-initdb.d:/docker-entrypoint-initdb.d
keycloak:
image: quay.io/keycloak/keycloak:latest
depends_on:
- mysql
ports:
- 8080:8080
volumes:
- keycloak-data:/opt/keycloak/data
- ./keycloak-config:/opt/keycloak/data/import
command: ["start-dev", "--import-realm"]
volumes:
mysql-data:
keycloak-data:
This is my pages/api/auth/[…nextauth].ts API Route:
import NextAuth from "next-auth"
import KeycloakProvider from "next-auth/providers/keycloak"
export const authOptions = {
debug: true,
secret: process.env.NEXT_AUTH_SECRET,
providers: [
KeycloakProvider({
clientId: process.env.KEYCLOAK_CLIENT_ID || "",
clientSecret: process.env.KEYCLOAK_CLIENT_SECRET || "",
issuer: process.env.KEYCLOAK_ISSUER || "",
// profile(profile) {
// return {
// id: profile.sub,
// name: profile.name ?? profile.preferred_username,
// email: profile.email,
// }
// },
}),
],
}
export default NextAuth(authOptions)
…and these are the values in my .env:
KEYCLOAK_CLIENT_ID=nextjs_client
KEYCLOAK_CLIENT_SECRET=abcdefghijklmnopqrs
KEYCLOAK_ISSUER=http://localhost:8080/realms/nextjs
And finally this is the error in my container log that occurs when i click the keycloak-signin-button:
nextjs-1 | https://next-auth.js.org/errors#signin_oauth_error connect ECONNREFUSED 127.0.0.1:8080 {
nextjs-1 | error: {
nextjs-1 | message: 'connect ECONNREFUSED 127.0.0.1:8080',
nextjs-1 | stack: 'Error: connect ECONNREFUSED 127.0.0.1:8080n' +
nextjs-1 | ' at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1607:16)n' +
nextjs-1 | ' at TCPConnectWrap.callbackTrampoline (node:internal/async_hooks:130:17)',
nextjs-1 | name: 'Error'
nextjs-1 | },
nextjs-1 | providerId: 'keycloak',
nextjs-1 | message: 'connect ECONNREFUSED 127.0.0.1:8080'
nextjs-1 | }
I…
- …tried replacing
localhost
withkeycloak
in my .env File for theKEYCLOAK_ISSUER
to reference to the container but when i then clicked on Sign in with Keycloak i was redirected to the URLhttp://keycloak:8080/…
which of course did not work in the Browser. - …tried setting the Node Option:
--dns-result-order=ipv4first
which i found from another post about this Problem. But it did not work - …tried searching for the Problem but didnt find any working solution