Search code examples
jwtopenid-connectliferay-7

How to get JWT token for current Liferay session


I have configured Liferay v7.3.4 CE to authenticate with AWS Cognito using OpenID Connect Provider, and that all works fine.

enter image description here

I would now like to invoke REST APIs in AWS, from within Liferay, using the JWT token obtained from Cognito during the sign-in process.

It would seem this JWT token should be available within Liferay, correct? If so, a source code example demonstrating how to access this would be very much appreciated.

This token would then be added to the Authorization header of API calls to an instance of the AWS API Gateway secured by the same Cognito instance from which the user has just signed in. But first things first... how would someone programmatically access the JWT token for the current Liferay session?

Hope this makes sense.


Solution

  • I've got this working.

    First, I am using Maven (not gradle) to build Liferay projects. To this end, I've added the following to my portlet's pom.xml file:

        <dependency>
            <groupId>com.liferay</groupId>
            <artifactId>com.liferay.portal.security.sso.openid.connect.api</artifactId>
            <scope>provided</scope>
        </dependency>
    

    Next, in my portlet's render method, I've added the following code:

    public void render(RenderRequest renderRequest, RenderResponse renderResponse) throws PortletException, IOException
    {
        try {
            // get the jwtToken from the renderRequest parameter
            String jwtToken = null;
            HttpSession session = PortalUtil.getOriginalServletRequest(PortalUtil.getHttpServletRequest(renderRequest)).getSession();
            if (session.getAttribute(OpenIdConnectWebKeys.OPEN_ID_CONNECT_SESSION) instanceof OpenIdConnectSession) {
                OpenIdConnectSession openIdConnectSession = (OpenIdConnectSession) session.getAttribute(OpenIdConnectWebKeys.OPEN_ID_CONNECT_SESSION);
                jwtToken = openIdConnectSession.getAccessTokenValue();
            }
    
            // call a REST API with the jwt token
            List<Organization> organizations = masterDataClient.fetchOrganizations(jwtToken);
    
            // do other stuff
    
            super.render(renderRequest, renderResponse);
        } catch (Exception e) {
            throw new PortletException(e);
        }
    
    }