Skip to content

Device authorization polling issue / question #239

@qVipoL

Description

@qVipoL

Hi, im having an question to authenticating a device,
i have this function to poll for a token on the client:

const pollForToken = async (deviceCode: string, initialInterval: number) => {
    let pollingInterval = initialInterval;

    const poll = async () => {
      try {
        const { data, error } = await authClient.device.token({
          grant_type: 'urn:ietf:params:oauth:grant-type:device_code',
          device_code: deviceCode,
          client_id: 'my-app',
        });

        const { data: sessionData } = await authClient.getSession({
          fetchOptions: {
            headers: {
              Authorization: `Bearer ${data?.access_token}`,
            },
          },
        });

        if (error) {
          switch (error.error) {
            case 'authorization_pending':
              // Continue polling
              break;
            case 'slow_down':
              pollingInterval += 5;
              break;
            case 'access_denied':
              setIsPolling(false);
              setUserCode(null);
              toast.error(t('auth.deviceAuthorizationDenied'));
              return;
            case 'expired_token':
              setIsPolling(false);
              setUserCode(null);
              toast.error(t('auth.deviceAuthorizationExpired'));
              return;
            default:
              setIsPolling(false);
              setUserCode(null);
              toast.error(
                error.error_description || t('auth.deviceAuthorizationFailed'),
              );
              return;
          }
        }

        if (!data?.access_token) {
          // Schedule next poll
          pollingTimeoutRef.current = setTimeout(poll, pollingInterval * 1000);
        }
      } catch (err) {
        setIsPolling(false);
        setUserCode(null);
        const errorMessage =
          err instanceof Error
            ? err.message
            : t('auth.deviceAuthorizationNetworkError');
        toast.error(errorMessage);
      }
    };

    // Start polling
    pollingTimeoutRef.current = setTimeout(poll, pollingInterval * 1000);
  };

it works ok until i call authClient.getSession, which sets only "better-auth_session_data" variable in local storage, but as i understand to get authenticated i need "better-auth_cookie" variable to have "better-auth.session_token" set, but i dont understand how it can be generated, which function / endpoint do i need to call after getting the access token?

thanks in advance

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions