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

[Bug]: Invalid code_challenge on exchangeCode for VKID SDK + OneTap (workaround included) #24

Open
anetrebskii opened this issue Aug 3, 2024 · 4 comments
Labels
bug Something isn't working

Comments

@anetrebskii
Copy link

Описание

Summary

The codeVerifier parameter passed to VKID.Config.init is not used by the SDK. The SDK generates a new codeVerifier token every time, and it does not save it in cookies as it should, according to the source code. As a result, when I call VKID.Auth.exchangeCode, it receives the error Invalid code_challenge.

Workaround

Pass codeChallenge to VKID.Config.init instead of the codeVerifier parameter, and save codeVerifier somewhere yourself.

Шаги воспроизведения

Steps

According to the documentation to get access and refresh tokens it's enough to do the following

  1. Init VKID SDK.
VKID.Config.init({
  app: 00000000, // Идентификатор приложения.
  redirectUrl: 'http://mydomen/vkAuth', // Адрес для перехода после авторизации.
  state: 'dj11fnsadjsd82', // Произвольная строка состояния приложения.
  
  codeVerifier: 'FGH767Gd65sdkjsaju32jdf243huifskdfh32fjJs73fhGgy3Dfgsd2'
  scope: 'email phone', // Список прав доступа, которые нужны приложению.
  mode: VKID.ConfigAuthMode.Redirect, // По умолчанию авторизация открывается в новой вкладке.
});
  1. Init OneTab
    const oneTapTmp = new VKID.OneTap();
    // Получение контейнера из разметки.
    const container = document.getElementById('VkIdSdkOneTap');

    if (container) {
      // Отрисовка кнопки в контейнере с именем приложения APP_NAME, светлой темой и на русском языке.
      oneTapTmp
        .render({
          container: container,
          scheme: VKID.Scheme.LIGHT,
          lang: VKID.Languages.RUS
        })
        .on(VKID.WidgetEvents.ERROR, handleError); // handleError — какой-либо обработчик ошибки.
    }
  1. Exchange code
    const code = query.get('code')!;
    const device_id = query.get('device_id')!;
    const state = query.get('state');

    (async function () {
      const authTokens = await VKID.Auth.exchangeCode(responseCode, device_id);
      console.log('Access Token:', authTokens.access_token);
      const userInfo = await VKID.Auth.userInfo(authTokens.access_token);
    })();

Result

Error received

{
    "error": "invalid_request",
    "error_description": "invalid code_challenge",
    "state": "dj29fnsadjsd82"
}

Версия vkid/sdk

2.1.0

В каких браузерах воспроизводится проблема?

Chrome

Ожидаемое поведение

Refresh, access, and other tokens are received.

Скриншоты

image

Пример с воспроизведением

No response

@anetrebskii anetrebskii added the bug Something isn't working label Aug 3, 2024
@tolkensak
Copy link

tolkensak commented Aug 19, 2024

I have the same problem.

$result = (object) array(
   'error' => 'invalid_request',
   'error_description' => 'invalid code_challenge',
   'state' => 'xxxxxxxxxxxxxxxxxxxxxxxx',
);

The above error occurs in both cases: in SDK (version 2.2.0) and when making a direct request.

And it's no use doing this, I tried many times.

Pass codeChallenge to VKID.Config.init instead of the codeVerifier parameter, and save codeVerifier somewhere yourself.

@zer0-dev
Copy link

zer0-dev commented Dec 5, 2024

has anyone figured it out?

@zer0-dev
Copy link

zer0-dev commented Dec 5, 2024

so, it looks like sdk just ignores predefined codeVerifier in Config.init(), or something like this. it just generates new codeVerifier every time and because of this code_challenge passed to /authorize doesnt match with code_verified passed to /auth (when trying to exchange code). codeChallenge predefined in Config.init() works just fine. so all you need to do is encode your codeVerifier manually and pass it as codeChallenge to config and then manually exchange code using your unencoded codeVerifier

@ohmyp
Copy link
Contributor

ohmyp commented Jan 13, 2025

The error was due to the fact that the installation of cookies on the domain was blocked (the most common reason is the public-suffix-list), which affected the storage and receipt of codeVerifier cookies. In release 2.4.1, the codeVerifier save mechanism was fixed. Now with responseMode: 'callback' and mode !== 'redirect' the codeVerifier value will be saved to a variable, not just a cookie. The Auth.exchangeCode method has also been expanded with the codeVerifier argument, which you can pass the value to yourself.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

No branches or pull requests

4 participants