question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Next.js does not render authentication state properly after keycloak login

See original GitHub issue

Describe the bug I have a basic next.js application that does two things:

  1. provide an authentication mechanism using keycloak
  2. talk to a backend server that authorizes each request using the keycloak-access-token

I use the @react-keycloak/ssr library to achieve this. The problem now is that after I login and get redirected back to my application the cookie that contains the kcToken is empty. After I refresh my page it works like expected.

I understand that maybe my entire process flow is wrong. If so, what is the “usual” way to achieve what is mentioned above?

To Reproduce

Add this stub code to a fresh next.js app:

export async function getServerSideProps(context) {
    const base64KcToken = context.req.cookies.kcToken // the cookie that keycloak places after login
    const kcToken = base64KcToken ? Buffer.from(base64KcToken, "base64") : ""

    // the backend server passes the token along to keycloak for role-based authorization
    const res = await fetch(`${BACKEND_URL}/info`, {
            headers: {
                "Authorization": "Bearer " + kcToken 
            }
        })

    const data = await res.json()

    // ... exception handling is left out for readability ...

    return {
        props: {
            data
        }
    }
}

export default function Home({data}) {
    const router = useRouter() // the next.js client side router to redirect to keycloak
    const { keycloak, initialized } = useKeycloak() // keycloak instance configured in _app.js
    if (keycloak && !keycloak.authenticated && keycloak.createLoginUrl) router.push(keycloak.createLoginUrl())
    return (
        <div> ... some jsx that displays data ... </div>
   )
}

This process basically works but it feels really bad because a user that gets redirected after login is not able to see the fetched data unless he refreshes the entire page. This is because when getServerSideProps() is called right after redirect the base64KcToken is not there yet.

Also everything related to the login-status (eg. logout button) only gets displayed after ~1sec, when the cookie is loaded by the react-keycloak library.

Expected behavior data is displayed in the div after being redirected by keycloak.

Desktop (please complete the following information):

  • OS: Windows
  • Browser Chrome
  • Version latest

Note: If this is not the right place to ask a question like this I also created a stackoverflow question for this: https://stackoverflow.com/questions/66764930/next-js-does-not-render-authentication-state-properly-after-keycloak-login

Issue Analytics

  • State:closed
  • Created 2 years ago
  • Reactions:4
  • Comments:11

github_iconTop GitHub Comments

8reactions
aakaycommented, Apr 20, 2021

Is there any progress or workaround on this? I’m struggling with this problem, too.

7reactions
filippomccommented, Apr 8, 2021

The need for refreshing the page can be avoided with the silent check, like this:

<SSRKeycloakProvider
       keycloakConfig={keycloakCfg}
       persistor={SSRCookies(cookies)}
            initOptions={{ silentCheckSsoRedirectUri: 'http://' + location + '/silent-check-sso.html' }}
       >
 ...

</SSRKeycloakProvider>

while I didn’t found a way to avoid the transitory unlogged status. I’d like to know whether to fix that transitory is in the plans. I think this a real blocker for any serious use of the library. I think a sustainable workaround would be to have a way to understand that the token parsing is someway “pending” in order to postpone the rendering of the page or show a kind of waiting spinner.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Next.js does not render authentication state ... - Stack Overflow
talk to a backend server that authorizes each request using the keycloak-access-token. I use the @react-keycloak/ssr library to achieve this.
Read more >
Next.js does not render authentication state properly after keycloak ...
I have a basic next.js application that does two things: provide an authentication mechanism using keycloak; talk to a backend server that authorizes...
Read more >
How to implement Keycloak authentication in React
Jumpstart your Keycloak authentication, from login/logout to protected routes, with this detailed implementation guide for React apps.
Read more >
The Ultimate Guide to Next.js Authentication with Auth0
Learn how and where to authenticate your user in the different deployment models that exist for Next.js. This guide explores the Custom ...
Read more >
NextJS / React SSR: 21 Universal Data Fetching Patterns ...
Why is there no simple way to universal data fetching in NextJS? ... Have you users login once, and they are authenticated on...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found