<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Harsh Bhandari on Medium]]></title>
        <description><![CDATA[Stories by Harsh Bhandari on Medium]]></description>
        <link>https://medium.com/@harshbhandariv?source=rss-f6fa6277c449------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ex2GsGWA7g4Z-oAdhHCZZg.png</url>
            <title>Stories by Harsh Bhandari on Medium</title>
            <link>https://medium.com/@harshbhandariv?source=rss-f6fa6277c449------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 07:28:40 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@harshbhandariv/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Implementing Authentication in Next.js v13 Application with Keycloak(Part — 2)]]></title>
            <link>https://medium.com/inspiredbrilliance/implementing-authentication-in-next-js-v13-application-with-keycloak-part-2-6f68406bb3b5?source=rss-f6fa6277c449------2</link>
            <guid isPermaLink="false">https://medium.com/p/6f68406bb3b5</guid>
            <category><![CDATA[oauth]]></category>
            <category><![CDATA[keycloak]]></category>
            <category><![CDATA[authentication]]></category>
            <dc:creator><![CDATA[Harsh Bhandari]]></dc:creator>
            <pubDate>Thu, 08 Feb 2024 04:34:27 GMT</pubDate>
            <atom:updated>2024-02-08T04:34:30.054Z</atom:updated>
            <content:encoded><![CDATA[<h3>Implementing Authentication in Next.js v13 Application with Keycloak(Part — 2)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xrsU68Lhs-1lJ-KdY21swQ.png" /></figure><p>In the <a href="https://medium.com/inspiredbrilliance/implementing-authentication-in-next-js-v13-application-with-keycloak-part-1-f4817c53c7ef">last article</a>, I have discussed about bootrsapping keycloak server along with a basic setup of nextjs with next-auth. In this subsequent article, our focus will shift to configuring next-auth to enhance the user experience while keeping a security-first approach.</p><h3>Contents</h3><p>A. Bootstrapping keycloak server</p><p>B. Setting up nextjs along with next-auth</p><p>C. Refreshing access tokens</p><p>D. Federated logout</p><p>E. Securing pages with middleware</p><p>F. Customising sign in and sign out routes</p><p><em>(A &amp; B was discussed in the </em><a href="https://medium.com/inspiredbrilliance/implementing-authentication-in-next-js-v13-application-with-keycloak-part-1-f4817c53c7ef"><em>last part</em></a><em>, we will discuss C–F in this part)</em></p><h3>C. Refreshing access token</h3><h4>Understanding JWT session strategy</h4><p>By default next-auth uses JWT session strategy. This means, all the session data for a user to authenticate is stored in the browser in the form of encrypted cookies. The cookie is encrypted using NEXTAUTH_SECRET. next-auth provides features to use JWT session strategy to store session data such as access token, refresh token and id token and session metadata like name, image etc. in an encrypted form stored in the user’s browser as encrypted cookies. There is no requirement of database.</p><h4>Storing tokens and session metadata in Browser</h4><p>We will use <a href="https://next-auth.js.org/configuration/callbacks">callbacks</a> which taps into various steps in an authentication lifecycle to add our requirements.</p><p>Let’s add jwt and session callbacks to the authOptions which will help us store tokens and session metadata.</p><pre>// src/app/api/auth/[...nextauth]/route.ts<br>export const authOptions: AuthOptions = {<br>  ...<br>  ...<br>  session: {<br>    maxAge: 60 * 30<br>  },<br>  callbacks: {<br>    async jwt({ token, account }) {<br>      if (account) {<br>        token.idToken = account.id_token<br>        token.accessToken = account.access_token<br>        token.refreshToken = account.refresh_token<br>        token.expiresAt = account.expires_at<br>      }<br>      return token<br>    },<br>    async session({ session, token }) {<br>      session.accessToken = token.accessToken<br>      return session<br>    }<br>  }<br>}</pre><p>We define maxAge of Session based on default lifetime span of refresh token in keycloak.</p><p>We also require the accessToken to be renewed before its expiry. next-auth has a good <a href="https://authjs.dev/guides/basics/refresh-token-rotation">guide</a> to help us and we will also go over this now.</p><p>The access token has a short life span and needs to be refreshed before its expiry. The default lifespan of an access token in keycloak is 5 minutes.</p><p>We are given an additional token known as the refresh token, which has a longer lifespan. The primary function of this token is to renew or acquire a new access token until the refresh token itself expires. Once the refresh token also reaches the end of its validity period, users of the application will be required to re-authenticate with the keycloak authorization server.</p><p>We will setup a keycloak API call which would renew access token by taking client credentials and refresh token as input.</p><pre>// src/app/api/auth/[...nextauth]/route.ts<br>function requestRefreshOfAccessToken(token: JWT) {<br>  return fetch(`${process.env.KEYCLOAK_ISSUER}/protocol/openid-connect/token`, {<br>    headers: { &quot;Content-Type&quot;: &quot;application/x-www-form-urlencoded&quot; },<br>    body: new URLSearchParams({<br>      client_id: process.env.KEYCLOAK_CLIENT_ID,<br>      client_secret: process.env.KEYCLOAK_CLIENT_SECRET,<br>      grant_type: &quot;refresh_token&quot;,<br>      refresh_token: token.refreshToken!,<br>    }),<br>    method: &quot;POST&quot;,<br>    cache: &quot;no-store&quot;<br>  });<br>}</pre><p>We also need to setup the JWT callback in such a way that if access token has not expired we do not perform any action. If an access token is just about to expire(lets take a buffer of 1 minutes before its expiry) we would send the above request to keycloak authorisation server for a new access token.</p><p>We might also need to consider that even refresh token can expire, we request the user of the application to redo the process of authenticating with keycloak.</p><pre>// src/app/api/auth/[...nextauth]/route.ts<br>import { AuthOptions, TokenSet } from &quot;next-auth&quot;;<br>import { JWT } from &quot;next-auth/jwt&quot;;<br>import NextAuth from &quot;next-auth/next&quot;;<br>import KeycloakProvider from &quot;next-auth/providers/keycloak&quot;<br><br>function requestRefreshOfAccessToken(token: JWT) {<br>// ... Discussed in previous step<br>}<br><br>export const authOptions: AuthOptions = {<br>// ...<br>  callbacks: {<br>    async jwt({ token, account }) {<br>      if (account) {<br>        token.idToken = account.id_token<br>        token.accessToken = account.access_token<br>        token.refreshToken = account.refresh_token<br>        token.expiresAt = account.expires_at<br>        return token<br>      }<br>      // we take a buffer of one minute(60 * 1000 ms)<br>      if (Date.now() &lt; (token.expiresAt! * 1000 - 60 * 1000)) {<br>        return token<br>      } else {<br>        try {<br>          const response = await requestRefreshOfAccessToken(token)<br><br>          const tokens: TokenSet = await response.json()<br><br>          if (!response.ok) throw tokens<br><br>          const updatedToken: JWT = {<br>            ...token, // Keep the previous token properties<br>            idToken: tokens.id_token,<br>            accessToken: tokens.access_token,<br>            expiresAt: Math.floor(Date.now() / 1000 + (tokens.expires_in as number)),<br>            refreshToken: tokens.refresh_token ?? token.refreshToken,<br>          }<br>          return updatedToken<br>        } catch (error) {<br>          console.error(&quot;Error refreshing access token&quot;, error)<br>          return { ...token, error: &quot;RefreshAccessTokenError&quot; }<br>        }<br>      }<br>    },<br>// ...<br>  }<br>}<br><br>const handler = NextAuth(authOptions);<br><br>export { handler as GET, handler as POST }</pre><p>We will wrap our components with a SessionGuard and SessionProvider which would trigger the authentication flow if RefreshAccessTokenError occurs. The wrapping is done in layout component so that all pages/route would be wrapped around with a common root layout which contains the session guard.</p><p>The session provider would make sure that the session is kept alive by polling the nextjs server every 4 minutes. This is calculated by having one minute as buffer time.</p><pre>// src/app/Providers.tsx<br>&#39;use client&#39;<br><br>import { SessionProvider } from &quot;next-auth/react&quot;<br>import { ReactNode } from &quot;react&quot;<br><br>export function Providers({ children }: { children: ReactNode }) {<br>  return (<br>    &lt;SessionProvider refetchInterval={4 * 60}&gt;<br>      {children}<br>    &lt;/SessionProvider&gt;<br>  )<br>}</pre><pre>// src/components/SessionGuard.tsx<br>&quot;use client&quot;;<br>import { signIn, useSession } from &quot;next-auth/react&quot;;<br>import { ReactNode, useEffect } from &quot;react&quot;;<br><br>export default function SessionGuard({ children }: { children: ReactNode }) {<br>  const { data } = useSession();<br>  useEffect(() =&gt; {<br>    if (data?.error === &quot;RefreshAccessTokenError&quot;) {<br>      signIn(&quot;keycloak&quot;);<br>    }<br>  }, [data]);<br><br>  return &lt;&gt;{children}&lt;/&gt;;<br>}</pre><pre>// src/app/layout.tsx<br>import &#39;./globals.css&#39;<br>import { Providers } from &#39;./Providers&#39;<br>import SessionGuard from &#39;@/components/SessionGuard&#39;<br><br>// ...<br><br>export default function RootLayout({<br>  children,<br>}: {<br>  children: React.ReactNode<br>}) {<br>  return (<br>    &lt;html lang=&quot;en&quot;&gt;<br>      &lt;body className={inter.className}&gt;<br>        &lt;Providers&gt;<br>          &lt;SessionGuard&gt;<br>            {children}<br>          &lt;/SessionGuard&gt;<br>        &lt;/Providers&gt;<br>      &lt;/body&gt;<br>    &lt;/html&gt;<br>  )<br>}</pre><h3>D. Federated Logout</h3><p>You might notice that when we sign out of the application, it happens instantaneously. Also the subsequent sign in(s) does not prompt username and password. This is due to presence of session created by keycloak with the browser. The <a href="https://next-auth.js.org/getting-started/client#signout">signOut</a><em> </em>function provided by next-auth clears the session present in next application but fails to clear the session on the keycloak. There is a <a href="https://github.com/nextauthjs/next-auth/discussions/3938">discussion</a> in the next-auth repository to implement federated logout which will end session on the provider. Till then we will implement the functionality manually.</p><p>To logout from keycloak we need to redirect to the following end session endpoint:</p><p><a href="http://localhost:8080/realms/myrealm/protocol/openid-connect/logout">http://localhost:8080/realms/&lt;realm_name&gt;/protocol/openid-connect/logout</a></p><p>This endpoint requires following query parameters:</p><ol><li>id_token_hint<strong><em> - </em></strong>ID token of the user</li><li>post_logout_redirect_uri<strong><em> - </em></strong>Self explanatory</li></ol><blockquote>Make sure to setup the post_logout_redirect_uri in Keycloak security admin console</blockquote><p>Let us start by creating a GET /api/auth/federated-logout route which builds the end session endpoint URL with the required query parameters.</p><pre>// src/app/api/auth/federated-logout/route.ts<br>function logoutParams(token: JWT): Record&lt;string, string&gt; {<br>  return {<br>    id_token_hint: token.idToken as string,<br>    post_logout_redirect_uri: process.env.NEXTAUTH_URL,<br>  };<br>}<br><br>function handleEmptyToken() {<br>  const response = { error: &quot;No session present&quot; };<br>  const responseHeaders = { status: 400 };<br>  return NextResponse.json(response, responseHeaders);<br>}<br><br>function sendEndSessionEndpointToURL(token: JWT) {<br>  const endSessionEndPoint = new URL(<br>    `${process.env.KEYCLOAK_ISSUER}/protocol/openid-connect/logout`<br>  );<br>  const params: Record&lt;string, string&gt; = logoutParams(token);<br>  const endSessionParams = new URLSearchParams(params);<br>  const response = { url: `${endSessionEndPoint.href}/?${endSessionParams}` };<br>  return NextResponse.json(response);<br>}<br><br>export async function GET(req: NextRequest) {<br>  try {<br>    const token = await getToken({ req })<br>    if (token) {<br>      return sendEndSessionEndpointToURL(token);<br>    }<br>    return handleEmptyToken();<br>  } catch (error) {<br>    console.error(error);<br>    const response = {<br>      error: &quot;Unable to logout from the session&quot;,<br>    };<br>    const responseHeaders = {<br>      status: 500,<br>    };<br>    return NextResponse.json(response, responseHeaders);<br>  }<br>}</pre><p>Finally we replace signOut functions provided by next-auth with federatedLogout function</p><pre>// src/components/Logout.tsx<br>&quot;use client&quot;<br>import federatedLogout from &quot;@/utils/federatedLogout&quot;;<br><br>export default function Logout() {<br>  return &lt;button onClick={() =&gt; federatedLogout()}&gt;<br>    Signout of keycloak<br>  &lt;/button&gt;<br>}</pre><pre>// src/utils/federatedLogout.ts<br>import { signOut } from &quot;next-auth/react&quot;;<br><br>export default async function federatedLogout() {<br>  try {<br>    const response = await fetch(&quot;/api/auth/federated-logout&quot;);<br>    const data = await response.json();<br>    if (response.ok) {<br>      await signOut({ redirect: false });<br>      window.location.href = data.url;<br>      return;<br>    }<br>    throw new Error(data.error);<br>  } catch (error) {<br>    console.log(error)<br>    alert(error);<br>    await signOut({ redirect: false });<br>    window.location.href = &quot;/&quot;;<br>  }<br>}</pre><h3>E. Securing pages with middleware</h3><p>In our web application, we might want to keep certain routes accessible when the user is authenticated otherwise the user is redirected to a sign in page. In this section we will discuss the requirements and how to implement it in our application.</p><p>Let’s list down our requirements:</p><ol><li>If a user is authenticated, user is able to access both public and private routes.</li><li>If a user is not authenticated, user can access public routes. In case, the user tries to access private route — the user will be redirected to signin page.</li><li>After a successful sign in, user is redirected back to the former private route for better user experience.</li><li>The redirection in the requirement — 2 should not be a client side navigation i.e. the application should not load private component on the user’s browser and then realise that the user was not authenticated. Use of getServerSession() would do the work. However, can we do better?</li></ol><p>nextjs provides middleware which will run a snippet of code before processing any request. We can define routes which are protected and should be redirected to sign in page. next-auth provides a middleware snippet which can be applied to selected private routes by setting up the path matcher of the route. More details on path matchers can be found <a href="https://nextjs.org/docs/app/building-your-application/routing/middleware#matching-paths">here</a>.</p><pre>// src/middleware.ts<br>export { default } from &quot;next-auth/middleware&quot;<br><br>export const config = {<br>  matcher: [&quot;/private&quot;]<br>}</pre><p>Let us define a <strong>public</strong> and <strong>private</strong> routes/pages.</p><pre>// src/app/public/page.tsx<br>import { getServerSession } from &#39;next-auth&#39;;<br>import { authOptions } from &#39;@/app/api/auth/[...nextauth]/route&#39;;<br>import Logout from &#39;@/components/Logout&#39;;<br>import Login from &#39;@/components/Login&#39;;<br><br>export default async function Public() {<br>  const session = await getServerSession(authOptions)<br>  if (session) {<br>    return &lt;div className=&#39;flex flex-col space-y-3 justify-center items-center h-screen&#39;&gt;<br>      &lt;div&gt;You are accessing a public page&lt;/div&gt;<br>      &lt;div&gt;Your name is {session.user?.name}&lt;/div&gt;<br>      &lt;div&gt;<br>        &lt;Logout /&gt;<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  }<br>  return (<br>    &lt;div className=&#39;flex flex-col space-y-3 justify-center items-center h-screen&#39;&gt;<br>      &lt;div&gt;You are accessing a public page&lt;/div&gt;<br>      &lt;div&gt;<br>        &lt;Login /&gt;<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  )<br>}</pre><pre>// src/app/private/page.tsx<br>import { getServerSession } from &#39;next-auth&#39;;<br>import Logout from &#39;@/components/Logout&#39;;<br>import { authOptions } from &#39;@/app/api/auth/[...nextauth]/route&#39;;<br><br>export default async function Private() {<br>  const session = await getServerSession(authOptions)<br>  if (session) {<br>    return &lt;div className=&#39;flex flex-col space-y-3 justify-center items-center h-screen&#39;&gt;<br>      &lt;div&gt;You are accessing a private page&lt;/div&gt;<br>      &lt;div&gt;Your name is {session.user?.name}&lt;/div&gt;<br>      &lt;div&gt;<br>        &lt;Logout /&gt;<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  }<br>}</pre><p>Please note that private component will always have the session since unauthenticated request will be redirected by middleware and redirected to next-auth’s signin page.</p><h4><strong>Demo</strong></h4><p>If you try to open <a href="http://localhost:3000/private">http://localhost:3000/private</a>. You would notice in the browser’s network console that a redirection with status code 307 Temporary Redirection happens to sign in route. This redirection takes place as the /private route is matched as defined in src/middleware.ts and the middleware snippet defined by next-auth/middleware redirects to sign in route. The sign in route is provided by next-auth out of the box as discussed earlier.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ltkSwBNHbxf9jVXMuQeQcg.png" /></figure><p>This redirection does not take place with public route.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_Gm8a3ftXyTne0Lmmx-NnQ.png" /></figure><h3>F. Using custom Sign in and Sign out components</h3><p>There might be a requirement that the sign in and sign out routes provided by the next-auth should match you application’s design system. This can be done defining our own routes.</p><pre>// src/app/auth/signin/page.tsx<br>import { authOptions } from &quot;@/app/api/auth/[...nextauth]/route&quot;;<br>import Login from &quot;@/components/Login&quot;;<br>import { getServerSession } from &quot;next-auth&quot;;<br>import { redirect, useParams } from &quot;next/navigation&quot;;<br><br>const signinErrors: Record&lt;string | &quot;default&quot;, string&gt; = {<br>// ...<br>}<br><br>interface SignInPageProp {<br>  params: object<br>  searchParams: {<br>    callbackUrl: string<br>    error: string<br>  }<br>}<br><br>export default async function Signin({ searchParams: { callbackUrl, error } }: SignInPageProp) {<br>  const session = await getServerSession(authOptions);<br>  if (session) {<br>    redirect(callbackUrl || &quot;/&quot;)<br>  }<br>  return (<br>    &lt;div&gt;<br>      {error &amp;&amp; &lt;div&gt;<br>        {signinErrors[error.toLowerCase()]}<br>      &lt;/div&gt;}<br>      &lt;Login /&gt;<br>    &lt;/div&gt;<br>  )<br>}</pre><pre>// src/app/auth/signout/page.tsx<br>import { authOptions } from &quot;@/app/api/auth/[...nextauth]/route&quot;;<br>import Logout from &quot;@/components/Logout&quot;;<br>import { getServerSession } from &quot;next-auth&quot;;<br>import { redirect } from &quot;next/navigation&quot;;<br><br>export default async function SignoutPage() {<br>  const session = await getServerSession(authOptions);<br>  if (session) {<br>    return (<br>      &lt;div&gt;<br>        &lt;div&gt;Signout&lt;/div&gt;<br>        &lt;div&gt;Are you sure you want to sign out?&lt;/div&gt;<br>        &lt;div&gt;<br>          &lt;Logout /&gt;<br>        &lt;/div&gt;<br>      &lt;/div&gt;<br>    )<br>  }<br>  return redirect(&quot;/api/auth/signin&quot;)<br>}</pre><p>Finally we need to configure next-auth to use custom sign in and sign out routes. This can be done by configuring the right authOptions .</p><pre>// src/app/api/auth/[...nextauth]/route.ts<br>import { AuthOptions, TokenSet } from &quot;next-auth&quot;;<br>import NextAuth from &quot;next-auth/next&quot;;<br>import KeycloakProvider from &quot;next-auth/providers/keycloak&quot;<br><br>export const authOptions: AuthOptions = {<br>// ...<br>  pages: {<br>    signIn: &#39;/auth/signin&#39;,<br>    signOut: &#39;/auth/signout&#39;,<br>  },<br>// ...<br>}<br><br>const handler = NextAuth(authOptions);<br><br>export { handler as GET, handler as POST }</pre><p><strong>Demo</strong></p><p>If you try to access the private route you will be redirected to our custom sign in route.</p><p>Similarly if we try to access <a href="http://localhost:3000/auth/signout">http://localhost:3000/auth/signout</a>, the custom sign out route is shown.</p><h3>Conclusion</h3><p>I hope you have got an understanding of authentication in Nextjs v13 application.</p><p>We have discussed the following features/implementation in detail in this article.</p><p>A. Bootstrapping keycloak server</p><p>B. Setting up nextjs along with next-auth</p><p>C. Refreshing access tokens before they expire</p><p>D. Federated logout</p><p>E. Securing pages with middleware</p><p>F. Customising sign in and sign out routes</p><p>All code related to this article is available in this GitHub <a href="https://github.com/harshbhandarivs/nextjs-keycloak">repository</a>.</p><h3><strong>References</strong></h3><ol><li><a href="https://www.keycloak.org/getting-started/getting-started-docker">https://www.keycloak.org/getting-started/getting-started-docker</a></li><li><a href="https://www.keycloak.org/docs/latest/server_admin/index.html#core-concepts-and-terms">https://www.keycloak.org/docs/latest/server_admin/index.html#core-concepts-and-terms</a></li><li><a href="https://next-auth.js.org/configuration/initialization#route-handlers-app">https://next-auth.js.org/configuration/initialization#route-handlers-app</a></li><li><a href="https://next-auth.js.org/providers/keycloak">https://next-auth.js.org/providers/keycloak</a></li><li><a href="https://nodejs.org/docs/latest-v18.x/api/cli.html#--dns-result-orderorder">https://nodejs.org/docs/latest-v18.x/api/cli.html#--dns-result-orderorder</a></li><li><a href="https://nextjs.org/docs/getting-started/react-essentials">https://nextjs.org/docs/getting-started/react-essentials</a></li><li><a href="https://authjs.dev/guides/basics/refresh-token-rotation">https://authjs.dev/guides/basics/refresh-token-rotation</a></li><li><a href="https://github.com/nextauthjs/next-auth/discussions/3938">https://github.com/nextauthjs/next-auth/discussions/3938</a></li><li><a href="https://nextjs.org/docs/app/building-your-application/routing/middleware">https://nextjs.org/docs/app/building-your-application/routing/middleware</a></li><li><a href="https://next-auth.js.org/tutorials/securing-pages-and-api-routes#nextjs-middleware">https://next-auth.js.org/tutorials/securing-pages-and-api-routes#nextjs-middleware</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6f68406bb3b5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/inspiredbrilliance/implementing-authentication-in-next-js-v13-application-with-keycloak-part-2-6f68406bb3b5">Implementing Authentication in Next.js v13 Application with Keycloak(Part — 2)</a> was originally published in <a href="https://medium.com/inspiredbrilliance">inspiringbrilliance</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing Authentication in Next.js v13 Application with Keycloak(Part — 1)]]></title>
            <link>https://medium.com/inspiredbrilliance/implementing-authentication-in-next-js-v13-application-with-keycloak-part-1-f4817c53c7ef?source=rss-f6fa6277c449------2</link>
            <guid isPermaLink="false">https://medium.com/p/f4817c53c7ef</guid>
            <category><![CDATA[oauth2]]></category>
            <category><![CDATA[keycloak]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[authentication]]></category>
            <dc:creator><![CDATA[Harsh Bhandari]]></dc:creator>
            <pubDate>Wed, 07 Feb 2024 10:07:41 GMT</pubDate>
            <atom:updated>2024-02-07T10:07:41.788Z</atom:updated>
            <content:encoded><![CDATA[<h3>Implementing Authentication in Next.js v13 Application with Keycloak(Part — 1)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xrsU68Lhs-1lJ-KdY21swQ.png" /></figure><p>Authentication and authorization are the digital gatekeepers of a web app, playing pivotal roles in ensuring a secure and controlled user experience. One such tool which can help us do this task for us is <a href="https://keycloak.org/">Keycloak</a>.</p><p>Keycloak is an open-source Identity and Access Management (IAM) tool that handles authentication and authorisation of applications. It acts as an identity broker, allowing users to authenticate with their preferred identity provider and apply different authorisation mechanisms, such as role-based or attribute-based.</p><p>This article will guide you through the process of setting up a nextjs application with authentication using a widely-used library, next-auth. We will be using keycloak as our identity provider for next-auth application.</p><h3>Contents</h3><p>A. Bootstrapping keycloak server</p><p>B. Setting up nextjs along with next-auth</p><p>C. Refreshing access tokens</p><p>D. Federated logout</p><p>E. Securing pages with middleware</p><p>F. Customising sign in and sign out routes</p><p><em>(A &amp; B are discussed in this part, for C–F refer part 2 of this article)</em></p><h3>Prerequisites</h3><p>Make sure the following software tools with appropriate versions is available on your machine.</p><ol><li>Node.js ≥ v18</li><li>Docker ≥ v24</li></ol><p>To install node. I recommend using <a href="https://github.com/nvm-sh/nvm">nvm</a>.</p><h3>A. Bootstrapping keycloak server</h3><h4><strong>Step 1: </strong>Setup a keycloak server</h4><p>We will use docker to quickly provision a keycloak server. The below command will bootstrap a development keycloak server on port 8080 with default username and password as admin.</p><blockquote>We will be using keycloak version 22.0.4 in this article</blockquote><pre>docker run -p 8080:8080 -e KEYCLOAK_ADMIN=admin -e KEYCLOAK_ADMIN_PASSWORD=admin quay.io/keycloak/keycloak:22.0.4 start-dev</pre><p>Go to <a href="http://localhost:8080/admin">http://localhost:8080</a> to verify the keycloak server is running.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QTfmjgK3JK7csTu20pJsgA.png" /><figcaption>Keycloak landing page</figcaption></figure><blockquote><strong>Note</strong> that this method of running keycloak server should not be used in production.</blockquote><h4><strong>Step 2: </strong>Login to Keycloak security admin console</h4><p>Go to <a href="http://localhost:8080/admin">http://localhost:8080/admin</a>. Enter the username and password as admin. By default we will be logged in to master<strong> </strong>realm.</p><figure><img alt="Keycloak login screen" src="https://cdn-images-1.medium.com/max/1024/1*xz3nHY3eDUZCFjshZ3J0mA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8OfJAPHiiiEvzaflbya_rw.png" /><figcaption>Keycloak security admin console</figcaption></figure><h4><strong>Step 3: </strong>Create a new realm</h4><p>Keycloak comes with a default realm called master. A realm is like a tenant. Each realm manages a particular set of users, credentials, roles and groups. The default realm master<strong> </strong>must only be used to manage keycloak. To manage our applications, we will create a new realm. Use the following link to add a new realm. Let us name our realm myrealm.</p><p><a href="http://localhost:8080/admin/master/console/#/master/add-realm">http://localhost:8080/admin/master/console/#/master/add-realm</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Hg6axsfwFyWI7EAFX9Zy0w.png" /><figcaption>Create a new realm</figcaption></figure><p>Make sure to change from master realm to myrealm for subsequent steps.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rqW-Y-igTXy6cRr8BLBx_w.png" /><figcaption>myrealm</figcaption></figure><h4><strong>Step 4</strong>: Create a client under <strong>myrealm</strong></h4><p>Clients are entities which will request keycloak to authenticate user. In our case, the Next.js application will be the client.</p><p>Keycloak offers two types of clients: <a href="https://openid.net/developers/how-connect-works/">OpenID Connect</a> and <a href="https://en.wikipedia.org/wiki/Security_Assertion_Markup_Language">SAML</a>. In this article, we will only focus on OpenID Connect.</p><p>Go to <a href="http://localhost:8080/admin/master/console/#/myrealm/clients/add-client">http://localhost:8080/admin/master/console/#/myrealm/clients/add-client</a>.</p><p>Choose the client type as OpenID Connect and set the client id as “nextjs”. Click “Next” to proceed further.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CIwHreQkft6DFpM_AtjbSA.png" /></figure><p>To enable client authentication, select the standard flow for the authentication process. Then, click “Next” to configure the login settings.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3zeMKkOkQPJoXeVhRlqzKQ.png" /></figure><p>The details of redirect URIs can be found from <a href="https://next-auth.js.org/getting-started/rest-api">REST API</a> page of next-auth library.</p><p>Since we will be building our own logout functionality, we will provide URL of Nextjs application as post logout redirect URI. The URL will be <a href="http://localhost:3000/">http://localhost:3000</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2WD0YeAUi_t6DBuy31xCww.png" /></figure><p>Click save to create client.</p><h4><strong>Step 5</strong>: Get the client secret of the nextjs client id</h4><p>Get the client secret from Credentials tab of the client.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oltrTIKSDUSCz0j5Qfih6w.png" /></figure><h4><strong>Step 6</strong>: Create a user in myrealm</h4><p>Go to <a href="http://localhost:8080/admin/master/console/#/myrealm/users/add-user">http://localhost:8080/admin/master/console/#/myrealm/users/add-user</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nPD_xOulzOX9QBfkadF4sA.png" /></figure><p>Create a user with the given username.</p><p>Also go to credentials tab of the created user and set the password.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*02aQzZY82AxRCwlG_S8h-g.png" /></figure><p>The initial setup of keycloak is done. We will now proceed with creating a Next.js application.</p><h3>B. Setting up nextjs along with next-auth</h3><h4><strong>Step 1</strong>: Create a Next.js application</h4><p>We will use the create-next-app cli to bootstrap our nextjs application. We’ll be using the Nextjs 13 with the app router. This command will also prompt for the following options. To know more, refer to <a href="https://nextjs.org/docs/getting-started/installation">installation guide</a> of Next.js.</p><pre>npx create-next-app@13.5.4<br>✔ What is your project named? … nextjs-keycloak<br>✔ Would you like to use TypeScript? … No / Yes<br>✔ Would you like to use ESLint? … No / Yes<br>✔ Would you like to use Tailwind CSS? … No / Yes<br>✔ Would you like to use `src/` directory? … No / Yes<br>✔ Would you like to use App Router? (recommended) … No / Yes<br>✔ Would you like to customize the default import alias? … No / Yes</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qsthmXgZzXrTkmwHUSKSZA.png" /></figure><h4><strong>Step 2</strong>: Install <a href="https://next-auth.js.org/">next-auth</a> as a dependency</h4><pre>cd nextjs-keycloak<br>npm install next-auth@4.24.3</pre><h4><strong>Step 3</strong>: Configure the authOptions with KeycloakProvider for next-auth<strong><em> </em></strong>and initialize route handler.</h4><p>Create a file with the following command from the root of the project.</p><pre>mkdir -p &quot;src/app/api/auth/[...nextauth]&quot; &amp;&amp; touch &quot;src/app/api/auth/[...nextauth]/route.ts&quot;</pre><p>Add the following code to the file created. This will configure Keycloak provider from the environment variables.</p><pre>// src/app/api/auth/[...nextauth]/route.ts<br>import { AuthOptions } from &quot;next-auth&quot;;<br>import KeycloakProvider from &quot;next-auth/providers/keycloak&quot;<br>export const authOptions: AuthOptions = {<br>  providers: [<br>    KeycloakProvider({<br>      clientId: process.env.KEYCLOAK_CLIENT_ID,<br>      clientSecret: process.env.KEYCLOAK_CLIENT_SECRET,<br>      issuer: process.env.KEYCLOAK_ISSUER<br>    })<br>  ]<br>}<br>const handler = NextAuth(authOptions);<br>export { handler as GET, handler as POST }</pre><p>If you’re using an IDE like VS Code you might have red squiggly lines below clientId and clientSecret<em>. </em>You might need to extend the ProcessEnv interface. Create a file with the following command from the root of project.</p><pre>mkdir types &amp;&amp; touch types/node-env.d.ts</pre><p>Extend the ProcessEnv interface with the following code.</p><pre>// types/node-env.d.ts<br>declare namespace NodeJS {<br>  export interface ProcessEnv {<br>    KEYCLOAK_CLIENT_ID: string<br>    KEYCLOAK_CLIENT_SECRET: string<br>    KEYCLOAK_ISSUER: string<br>  }<br>}</pre><p>We can add the environment variables to a file named .env.local which will be automatically picked up by the Nextjs server.</p><pre>touch .env.local</pre><pre>KEYCLOAK_CLIENT_ID=&quot;nextjs&quot;<br>KEYCLOAK_CLIENT_SECRET=&quot;&lt;client_secret&gt;&quot;<br>KEYCLOAK_ISSUER=&quot;http://localhost:8080/realms/myrealm&quot;</pre><p>Replace the values &lt;client_secret&gt;<strong><em> </em></strong>collected from step 5 of previous section.</p><p>We also need to configure NEXTAUTH_URL and NEXTAUTH_SECRET. These are essential for configuring of next-auth. To know more, check the <a href="https://next-auth.js.org/configuration/options#environment-variables">guide</a>. Let’s add following environment variables to .env.local.</p><pre>NEXTAUTH_URL=&quot;http://localhost:3000&quot;</pre><p>For NEXTAUTH_SECRET<strong><em>, </em></strong>create a secret by running the following command and add it to .env.local. This secret is used to sign and encrypt cookies.</p><pre>openssl rand -base64 32</pre><pre>// .env.local<br>...<br>...<br>NEXTAUTH_SECRET=&quot;&lt;secret generated from previous command&gt;&quot;</pre><p>Let’s do some testing before integrating it with frontend.</p><pre>npm run dev</pre><p>Go to <a href="http://localhost:3000/api/auth/signin">http://localhost:3000/api/auth/signin</a>. We will see an un-branded signin page. This route is provided by next-auth library.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Fxu5hemXi92CcO9bqj22Cg.png" /></figure><p><strong>Troubleshooting</strong></p><p>At the time of writing this article, I was getting the following error while trying to sign in. This might be because of this <a href="https://github.com/nodejs/node/issues/40702">issue</a>.</p><pre>https://next-auth.js.org/errors#signin_oauth_error connect ECONNREFUSED ::1:8080 {<br>  error: {<br>    message: &#39;connect ECONNREFUSED ::1:8080&#39;,<br>    stack: &#39;Error: connect ECONNREFUSED ::1:8080\n&#39; +<br>      &#39;    at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1494:16)\n&#39; +<br>      &#39;    at TCPConnectWrap.callbackTrampoline (node:internal/async_hooks:130:17)&#39;,<br>    name: &#39;Error&#39;<br>  },<br>  providerId: &#39;keycloak&#39;,<br>  message: &#39;connect ECONNREFUSED ::1:8080&#39;<br>}</pre><p>This can be solved by passing the following Node CLI option. Start the server with the following options.</p><pre>NODE_OPTIONS=&#39;--dns-result-order=ipv4first&#39; npm run dev</pre><h4>Step 4: Setup Basic React Server component</h4><p>Let’s setup a basic server component which will show protected data when authenticated and would prompt login when unauthenticated.</p><p>Modify src/app/page.tsx<em> </em>with the following code.</p><pre>// src/app/page.tsx<br>import { getServerSession } from &#39;next-auth&#39;<br>import { authOptions } from &#39;./api/auth/[...nextauth]/route&#39;<br>import Login from &#39;../components/Login&#39;<br>import Logout from &#39;../components/Logout&#39;<br>export default async function Home() {<br>  const session = await getServerSession(authOptions)<br>  if (session) {<br>    return &lt;div&gt;<br>      &lt;div&gt;Your name is {session.user?.name}&lt;/div&gt;<br>      &lt;div&gt;&lt;Logout /&gt; &lt;/div&gt;<br>    &lt;/div&gt;<br>  }<br>  return (<br>    &lt;div&gt;<br>      &lt;Login /&gt;<br>    &lt;/div&gt;<br>  )<br>}</pre><p>Also create the Login and Logout component by creating the following files.</p><pre>mkdir src/components &amp;&amp;  touch src/components/Login.tsx &amp;&amp; touch src/components/Logout.tsx</pre><p>Add the following contents to Login and Logout component.</p><pre>// src/components/Login.tsx<br>&quot;use client&quot;<br>import { signIn } from &quot;next-auth/react&quot;;<br>export default function Login() {<br>  return &lt;button onClick={() =&gt; signIn(&quot;keycloak&quot;)}&gt;<br>    Signin with keycloak<br>  &lt;/button&gt;<br>}</pre><pre>// src/components/Logout.tsx<br>&quot;use client&quot;<br>import { signOut } from &quot;next-auth/react&quot;;<br>export default function Logout() {<br>  return &lt;button onClick={() =&gt; signOut()}&gt;<br>    Signout of keycloak<br>  &lt;/button&gt;<br>}</pre><blockquote>Notice the <em>use client</em> directive . This directive is a convention to declare a boundary between a Server and Client Component module graph.</blockquote><p><strong>Demo</strong></p><p>Go to <a href="http://localhost:3000/">http://localhost:3000</a>. You’ll be prompted to sign in with <em>keycloak.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y8vUb6iU1-ODUkGvJSKKdg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VSM6EcqBDIMfGCj0Zuh44A.png" /></figure><p>Once you sign in, you will see the name of the account used to sign in, with the logout component.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ldsYh20732KPaKx5TZOjaQ.png" /></figure><h3>Conclusion</h3><p>We have discussed the following features/implementation in detail in this article.</p><p><strong>A. Bootstrapping </strong><strong>keycloak server</strong></p><p><strong>B. Setting up </strong><strong>nextjs along with </strong><strong>next-auth</strong></p><p>C. Refreshing access tokens</p><p>D. Federated logout</p><p>E. Securing pages with middleware</p><p>F. Customising sign in and sign out routes</p><p>We will discuss the about how to configure next-auth to have better user experience while keeping security in mind in the second part of this article. I hope you find this article helpful. All code related to this article is available in this GitHub <a href="https://github.com/harshbhandarivs/nextjs-keycloak">repository</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f4817c53c7ef" width="1" height="1" alt=""><hr><p><a href="https://medium.com/inspiredbrilliance/implementing-authentication-in-next-js-v13-application-with-keycloak-part-1-f4817c53c7ef">Implementing Authentication in Next.js v13 Application with Keycloak(Part — 1)</a> was originally published in <a href="https://medium.com/inspiredbrilliance">inspiringbrilliance</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>