2

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.

Randy Leonard
  • 655
  • 7
  • 21

1 Answers1

3

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);
    }

}
Randy Leonard
  • 655
  • 7
  • 21
  • 1
    This solution works. Just to add, for Gradle projects we need to add this dependency in build.gradle compileOnly group: 'com.liferay', name: 'com.liferay.portal.security.sso.openid.connect.api', version: '5.0.7' No changes in bnd.bnd file – Dhruv Pandey Mar 01 '21 at 13:29
  • Keep in mind that the Access Token is not always a JWT, depending on the Provider. – Codebling Mar 25 '22 at 16:08