How to access URL params in the redirected URL

0

Hi guys,

I've a question/s. Imagine we launch the Cognito Hosted UI and we login ourselves, then Cognito redirect us to a redirect URL with the tokens (or code if we use Authorization Code Grant Flow), and here, how can we recover these params (for example the id and access token) from the redirected URL?, maybe through the response headers (as I see when I debug in Chrome) through the location object ? or directly through Javascript ? I've interested in recover these params from the redirected URL through Javascript and through React, can you help me ?, thanks in advance !!

Have a nice day ahead.

質問済み 1年前1258ビュー
5回答
1

Hello, I use a very Javascript line, but this is just for testing.

const code window.location.href.split("=").pop()

To find a good implementation, I think checking the Amplify JS repository help HERE. More specifically, clone the code and read this two files Auth.ts and OAuth.ts

	private async _handleCodeFlow(currentUrl: string) {
		/* Convert URL into an object with parameters as keys
    { redirect_uri: 'http://localhost:3000/', response_type: 'code', ...} */
		const { code } = (parse(currentUrl).query || '')
			.split('&')
			.map(pairings => pairings.split('='))
			.reduce((accum, [k, v]) => ({ ...accum, [k]: v }), { code: undefined });

		const currentUrlPathname = parse(currentUrl).pathname || '/';
		const redirectSignInPathname =
			parse(this._config.redirectSignIn).pathname || '/';

		if (!code || currentUrlPathname !== redirectSignInPathname) {
			return;
		}

		const oAuthTokenEndpoint =
			'https://' + this._config.domain + '/oauth2/token';

		dispatchAuthEvent(
			'codeFlow',
			{},
			`Retrieving tokens from ${oAuthTokenEndpoint}`
		);

		const client_id = isCognitoHostedOpts(this._config)
			? this._cognitoClientId
			: this._config.clientID;

		const redirect_uri = isCognitoHostedOpts(this._config)
			? this._config.redirectSignIn
			: this._config.redirectUri;

		const code_verifier = oAuthStorage.getPKCE();

		const oAuthTokenBody = {
			grant_type: 'authorization_code',
			code,
			client_id,
			redirect_uri,
			...(code_verifier ? { code_verifier } : {}),
		};

		logger.debug(
			`Calling token endpoint: ${oAuthTokenEndpoint} with`,
			oAuthTokenBody
		);

		const body = Object.entries(oAuthTokenBody)
			.map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(v)}`)
			.join('&');

		const { access_token, refresh_token, id_token, error } = await (
			(await fetch(oAuthTokenEndpoint, {
				method: 'POST',
				headers: {
					'Content-Type': 'application/x-www-form-urlencoded',
				},
				body,
			})) as any
		).json();

		if (error) {
			throw new Error(error);
		}

		return {
			accessToken: access_token,
			refreshToken: refresh_token,
			idToken: id_token,
		};
	}
hai
回答済み 1年前
1

Hi guys,

I just found this code at Internet that maybe has a possible solution:

const getIdToken = () => { const modifiedUrl = window.location.href.replace("#", "?") const url = new URL(modifiedUrl)

return url.searchParams.get("id_token") }

const idToken = getIdToken()

How do you think about, at least it's possible approach with Javascript !

回答済み 1年前
1

Hello,

Thank you for reaching out to AWS Support. I am Arpit from Deployment Team, and I have taken the ownership of the case forward.

I understand that you would like to access parameters from the redirected URL.

Looking into this, I found one stack overflow article regarding accessing the URL parameters. https://stackoverflow.com/questions/63650885/how-to-get-query-data-from-redirected-url

Can you please look into this, and check if the above fulfills your use-case.

Further, since code support is out of AWS Premium Support, and due to limited expertise with Javascript, we can assist you on best effort basis.

Hoping that the above helps.

AWS
サポートエンジニア
回答済み 1年前
0

Hi hai,

Thanks for your reply. The code above it's interesting, but as I see, we need to pass the URL to the _handleCodeFlow method, but what I mean is how to recover the URL from the redirection, as you told with a inline example with Javascript, maybe this would be a soluction for my problem, anyway I've searching a few solutions, and I found some examples, but I'm not sure. One example would be recover the URL from the fetch petition to the Hosted UI in the response object, I've seen that this request obtain a response and in the response there is an object called "location" with the complet URL inside, but I'll not check yet. Any other sugestion will be welcome. Have your more ideas ? thanks in advance !

Have a nice day ahead.

回答済み 1年前
0

Hi guys,

Thanks a lot for your help. I've checked the stackoverflow URL and it's more interesting. Now I'm wondering if when the hoster UI of Cognito redirects to the URL configured as redirect URL, maybe can we access to the response object of the corresponding request ? although of the redirection ?, I suppose when the redirect occurs we should have access to this object. What do you think about !

Thanks and have a nice day ahead.

回答済み 1年前

ログインしていません。 ログイン 回答を投稿する。

優れた回答とは、質問に明確に答え、建設的なフィードバックを提供し、質問者の専門分野におけるスキルの向上を促すものです。

質問に答えるためのガイドライン

関連するコンテンツ