Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Appsync Events: Can't pass authToken while using authMode: "lambda" #14062

Closed
3 tasks done
SteveAndreou opened this issue Dec 10, 2024 · 4 comments
Closed
3 tasks done
Assignees
Labels
Events Related to AppSync Events GraphQL Related to GraphQL API issues

Comments

@SteveAndreou
Copy link

SteveAndreou commented Dec 10, 2024

Before opening, please confirm:

JavaScript Framework

React, Next.js

Amplify APIs

GraphQL API

Amplify Version

v6

Amplify Categories

api

Backend

CDK

Environment information

# Put output below this line

 System:
    OS: Windows 11 10.0.26100
    CPU: (12) x64 12th Gen Intel(R) Core(TM) i7-1265U
    Memory: 11.51 GB / 31.44 GB
  Binaries:
    Node: 22.12.0 - C:\Program Files\nodejs\node.EXE
    npm: 10.8.3 - ~\source\...\node_modules\.bin\npm.CMD
    pnpm: 8.6.10 - C:\Program Files\nodejs\pnpm.CMD
  Browsers:
    Edge: Chromium (131.0.2903.86)
    Internet Explorer: 11.0.26100.1882

npmPackages:
"aws-amplify": "^6.10.2",

Describe the bug

While using the AWS Amplify provider, I can no provide an authToken while using authMode: "lambda".

I have deployed an AppSync Events API that is configured with an OIDC provider. (Auth0 in this case).
I can provide the Pub/Sub screen in the AppSync Console with a token and successfully connect & receive messages.

I'm now trying to connect my frontend application to the Events API and would like to pass along the token from the session to the server to authenticate the user. Trying to pass any token value (even placeholder strings) at any point is dropped from the provider options once the amplify code runs.

Expected behavior

When I pass a value via the authToken parameter, that value is sent to the server.

Reproduction steps

Following the developer guide will get you there.
https://docs.aws.amazon.com/appsync/latest/eventapi/build-amplify-app.html#configure-amplify-client

Code Snippet

// Put your code below this line.
Amplify.configure(
		{
			API: {
				Events: {
					endpoint: "https://example.appsync-api.eu-west-2.amazonaws.com/event",
					defaultAuthMode: "lambda",
				},
			},
		},
		{
			ssr: true,
		},
	);


//elsewhere, implementing a data hook as per documentation.
useEffect(() => {
		let channel: EventsChannel;

		const connectAndSubscribe = async () => {
			channel = await events.connect("/default/*", {
				authMode: "lambda", //this does nothing?
				authToken: token, //this does nothing?
			});

			channel.subscribe(
				{
					next: (data) => {
						console.log("received", data);
					},
					error: (err) => console.error("error", err),
				},
				{
					authMode: "lambda", //this also does nothing?
					authToken: token, //this also does nothing?
				},
			);
		};

		connectAndSubscribe();

		return () => channel?.close();
	}, [token]);

Log output

// Put your logs below this line
No auth token provided.

aws-exports.js

No response

Manual configuration

No response

Additional configuration

No response

Mobile Device

No response

Mobile Operating System

No response

Mobile Browser

No response

Mobile Browser Version

No response

Additional information and screenshots

No response

@github-actions github-actions bot added pending-triage Issue is pending triage pending-maintainer-response Issue is pending a response from the Amplify team. labels Dec 10, 2024
@cwomack cwomack added Events Related to AppSync Events GraphQL Related to GraphQL API issues labels Dec 10, 2024
@chrisbonifacio
Copy link
Member

Hi @SteveAndreou thanks for raising this issue.

While I attempt to reproduce, there's a potential workaround we've been able to use. Can you try adding a tokenProvider to the library argument of the Amplify configuration under Auth?

You will have to get your OIDC tokens from the getTokens function in the token provider and add refresh functionality if possible. This will allow the library to hydrate the client and WebSocket headers with the OIDC token.

You can do so similar to this example:

const myTokenProvider: TokenProvider = {
  async getTokens({ forceRefresh } = {}) {
    if (forceRefresh) {
      // try to obtain new tokens if possible
    }

    const accessTokenString = 'ADD_ACCESS_TOKEN_HERE';
    const idTokenString = 'ADD_ID_TOKEN_HERE';
    
    return {
      accessToken: decodeJWT(accessTokenString),
      idToken: decodeJWT(idTokenString),
    };
  },
};

Amplify.configure({
  API: {
    Events: {
      endpoint:
        'https://URL_FOR_APPSYNC/event',
      region: 'us-west-2',
      defaultAuthMode: 'lambda',
    }
  },
}, {  
  Auth: {
    tokenProvider: myTokenProvider
  }
});

@chrisbonifacio chrisbonifacio self-assigned this Dec 11, 2024
@chrisbonifacio chrisbonifacio added the to-be-reproduced Used in order for Amplify to reproduce said issue label Dec 11, 2024
@github-actions github-actions bot removed the pending-maintainer-response Issue is pending a response from the Amplify team. label Dec 11, 2024
@chrisbonifacio chrisbonifacio added pending-maintainer-response Issue is pending a response from the Amplify team. pending-community-response Issue is pending a response from the author or community. and removed pending-triage Issue is pending triage pending-maintainer-response Issue is pending a response from the Amplify team. labels Dec 11, 2024
@SteveAndreou
Copy link
Author

SteveAndreou commented Dec 11, 2024

Thanks for the guidance @chrisbonifacio.

I managed to authenticate my application using the suggestions you've provided 🙏

@github-actions github-actions bot added pending-maintainer-response Issue is pending a response from the Amplify team. and removed pending-community-response Issue is pending a response from the author or community. labels Dec 11, 2024
@sumeetswn
Copy link

sumeetswn commented Dec 13, 2024

Hello @chrisbonifacio, we are facing the same issue. We tried using the token provider fix, but it didn't worked. We have a custom token, which does not use OIDC token format.

Update:
After debugging and going through the SDK for a while, I found, I was passing authMode as lambda. I changed it to oidc and it worked. I had to override a decodeJWT function to make it work.

JS Code Snippet:

import { Amplify } from 'aws-amplify';
import { events } from 'aws-amplify/data';

const authToken = "<YOUR_AUTH_TOKEN>";

// Our auth token was not a JWT token, so we override the decodeJWT function with custom one.
function decodeToken(token) {
    try {

        // Optional: Set payload data 
        // let payload = {
        //     exp: 0,
        //     iss: "",
        //     aud: "",
        //     nbf: 0,
        //     iat: 0,
        //     scope: "",
        //     jti: "",
        //     sub: ""
        // }

        return {
            toString: () => token,
            payload: {}, // Optional: Set payload data
        };
    } catch (err) {
        console.log(err)
        throw new Error('JWT decode error');
    }
}

const myTokenProvider = {
    async getTokens({ forceRefresh } = {}) {
      if(forceRefresh) {
        // Refresh token logic to update authToken
      }

      return {
        accessToken: decodeToken(authToken),
        idToken: decodeToken(authToken),
      };
    },
  };

Amplify.configure({
    "API": {
        "Events": {
            "endpoint": "https://<APPSYNC_EVENTS_ENDPOINT_HOST>/event",
            "region": "<AWS_REGION>",
            "defaultAuthMode": "oidc"
        }
    }
  },
  {
    "Auth": {
        "tokenProvider": myTokenProvider
    }
  }
);

const channel = await events.connect(`/default/test`);

@chrisbonifacio
Copy link
Member

@sumeetswn thank you for providing your solution!

@github-actions github-actions bot removed the pending-maintainer-response Issue is pending a response from the Amplify team. label Dec 16, 2024
@chrisbonifacio chrisbonifacio removed the to-be-reproduced Used in order for Amplify to reproduce said issue label Dec 17, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Events Related to AppSync Events GraphQL Related to GraphQL API issues
Projects
None yet
Development

No branches or pull requests

4 participants