'How to verify a keycloak kcToken and kcIdToken fetched from browser's cookies after @react-keycloak/ssr login?

I am trying to secure NextJS API endpoints with keycloak. Keycloak authentication is already implemented on the front-end pages. The user is forced to sign in before they can view those pages. Two tokens are saved in the browser's cookies following keycloak authentication. They are kcToken and kcIdToken. Those same pages call on api endpoints, which also need to be secured, in case someone is trying to access them outside of the application pages.

I am trying to use the two tokens (kcIdToken and kcToken) to secure the APIs endpoints. I am not trying to require authentication again at the api level, but directly fetch these two tokens from the browser when an api endpoint is called and verify the tokens to check authentication status, etc.

Is there a way of verifying these two tokens ? I checked the format of these two tokens and they are not exactly jwt tokens with headers, payload, etc.

I am able to get these two tokens. I am not sure though what are their differences and uses.

What are the differences and uses of kcToken and kcIdToken, obtained using the @react-keycloak/ssr authentication for keycloak ?

Here is my api endpoint function:

const handler = async (req, res) => {  

    // Fetching the tokens from the request cookies  
    const { kcToken, kcIdToken } = req.cookies
    console.log(kcIdToken)
    console.log(kcToken)

   // If the tokens are undefined or non-existent in the browser
   if ( !kcIdToken || !kcToken) {
      return res.status(401).json({ success: false, message: "Unauthorized Access"})
   }

   // Verify kcToken and kcIdToken are valid 
   // Get user information, roles, etc, if the tokens are valid


    return res.status(401).json({ success: false, message: "Unauthorized Access"})
}

How do I verify these two tokens validate the correct authentication state ? What are the uses and differences between these two tokens ? Are these tokens coming directly from keycloak or from @react-keycloak/ssr ?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source