Skip to main content
The @vk-io/authorization package provides multiple ways to authorize users with VK, including direct authorization (login/password), implicit flow for users and groups, and account verification.

Installation

npm install @vk-io/authorization
Node.js 12.20.0 or newer is required. This package requires vk-io as a peer dependency.

Authorization Methods

The package supports four main authorization strategies:

Direct Authorization

Login with username and password using official app credentials

Implicit Flow User

Browser-based OAuth flow for user tokens

Implicit Flow Groups

Browser-based OAuth flow for group tokens

Account Verification

Verify account ownership during authorization

Direct Authorization

Direct authorization allows you to obtain access tokens using login and password. This method only works with official VK application credentials.

Basic Usage

import { VK, CallbackService } from 'vk-io';
import { DirectAuthorization, officialAppCredentials } from '@vk-io/authorization';

const callbackService = new CallbackService();

const direct = new DirectAuthorization({
  callbackService,
  scope: 'all',
  
  // Use official app credentials
  ...officialAppCredentials.android,
  
  login: process.env.LOGIN,
  password: process.env.PASSWORD,
  apiVersion: '5.199'
});

const response = await direct.run();

console.log('Token:', response.token);
console.log('User ID:', response.user);
console.log('Expires:', response.expires);
console.log('Email:', response.email);

Configuration

callbackService
CallbackService
required
VK-IO callback service for handling captcha and 2FA
clientId
string
required
Application client ID (use officialAppCredentials)
clientSecret
string
required
Application client secret (use officialAppCredentials)
login
string
User login (email or phone)
phone
string | number
User phone number
password
string
User password
scope
string | number | string[]
required
Permissions to request. Use 'all' for all permissions or an array of specific scopes
apiVersion
string
required
VK API version (e.g., ‘5.199’)
timeout
number
default:"10000"
Request timeout in milliseconds
headers
Record<string, string>
Custom HTTP headers

Official App Credentials

The package includes credentials for official VK applications:
import { officialAppCredentials } from '@vk-io/authorization';

// Available platforms:
const platforms = {
  android: officialAppCredentials.android,
  windows: officialAppCredentials.windows,
  windowsPhone: officialAppCredentials.windowsPhone,
  iphone: officialAppCredentials.iphone,
  ipad: officialAppCredentials.ipad,
  vkMe: officialAppCredentials.vkMe,
};

Response Type

interface DirectAuthResponse {
  email?: string;      // User email (if granted)
  user: number;        // User ID
  token: string;       // Access token
  expires: number;     // Token expiration time (0 for never)
}

Implicit Flow (User)

Implicit flow provides browser-based OAuth authorization for user accounts.

Usage

import { CallbackService } from 'vk-io';
import { ImplicitFlowUser } from '@vk-io/authorization';

const callbackService = new CallbackService();

const implicitFlow = new ImplicitFlowUser({
  callbackService,
  clientId: 'YOUR_APP_ID',
  scope: 'friends,photos,wall',
  login: process.env.LOGIN,
  password: process.env.PASSWORD,
  apiVersion: '5.199'
});

const response = await implicitFlow.run();

console.log('Token:', response.token);
console.log('User ID:', response.userId);
console.log('Expires:', response.expires);

Response Type

interface ImplicitFlowUserResponse {
  email?: string;         // User email (if granted)
  userId?: number;        // User ID
  token: string;          // Access token
  expires?: number;       // Token expiration time
}

Implicit Flow (Groups)

Get access tokens for managing community (group) accounts.

Usage

import { CallbackService } from 'vk-io';
import { ImplicitFlowGroups } from '@vk-io/authorization';

const callbackService = new CallbackService();

const implicitFlow = new ImplicitFlowGroups({
  callbackService,
  clientId: 'YOUR_APP_ID',
  groupIds: [123456789, 987654321],
  scope: 'messages,photos,manage',
  login: process.env.LOGIN,
  password: process.env.PASSWORD,
  apiVersion: '5.199'
});

const response = await implicitFlow.run();

for (const group of response.groups) {
  console.log('Group ID:', group.groupId);
  console.log('Token:', group.token);
  console.log('Expires:', group.expires);
}

Configuration

groupIds
number[]
required
Array of group IDs to authorize

Response Type

interface ImplicitFlowGroupsResponse {
  groups: Array<{
    groupId: number;      // Group ID
    token: string;        // Group access token
    expires: number;      // Token expiration time
  }>;
}

Account Verification

Verify account ownership during the authorization process.

Usage

import { CallbackService } from 'vk-io';
import { AccountVerification } from '@vk-io/authorization';

const callbackService = new CallbackService();

const verification = new AccountVerification({
  callbackService,
  login: process.env.LOGIN,
  phone: process.env.PHONE,
  agent: customHttpsAgent // optional
});

const redirectUri = 'https://oauth.vk.ru/authorize?...';
const response = await verification.run(redirectUri);

console.log('User ID:', response.userId);
console.log('Token:', response.token);

Response Type

interface AccountVerificationResponse {
  userId: number;        // User ID
  token: string;         // Access token
}

Permission Scopes

The package provides predefined permission scopes:

User Scopes

import { userScopes } from '@vk-io/authorization';

// Available scopes:
// notify, friends, photos, audio, video, pages, link, status,
// notes, messages, wall, ads, offline, docs, groups,
// notifications, stats, email, market

Group Scopes

import { groupScopes } from '@vk-io/authorization';

// Available scopes:
// stories, photos, messages, docs, manage

Using Scopes

const auth = new DirectAuthorization({
  scope: 'all', // Request all available permissions
  // ...
});

Error Handling

The package provides detailed error codes for different failure scenarios:
import { AuthErrorCode } from '@vk-io/authorization';

try {
  const response = await direct.run();
} catch (error) {
  if (error.code === AuthErrorCode.USERNAME_OR_PASSWORD_IS_INCORRECT) {
    console.error('Invalid credentials');
  } else if (error.code === AuthErrorCode.FAILED_PASSED_CAPTCHA) {
    console.error('Captcha verification failed');
  } else if (error.code === AuthErrorCode.FAILED_PASSED_TWO_FACTOR) {
    console.error('Two-factor authentication failed');
  } else if (error.code === AuthErrorCode.TOO_MUCH_TRIES) {
    console.error('Too many attempts, try again later');
  }
}

Error Codes

PAGE_BLOCKED
string
User page is blocked
INVALID_PHONE_NUMBER
string
Invalid or missing phone number
AUTHORIZATION_FAILED
string
General authorization failure
FAILED_PASSED_CAPTCHA
string
Failed to pass captcha verification
FAILED_PASSED_TWO_FACTOR
string
Failed two-factor authentication
USERNAME_OR_PASSWORD_IS_INCORRECT
string
Invalid login credentials
TOO_MUCH_TRIES
string
Too many authorization attempts
WRONG_OTP
string
Incorrect two-factor code
OTP_FORMAT_IS_INCORRECT
string
Invalid two-factor code format

Handling Captcha and 2FA

Use VK-IO’s CallbackService to handle captcha and two-factor authentication:
import { CallbackService } from 'vk-io';

const callbackService = new CallbackService();

// Handle captcha
callbackService.onCaptcha(async ({ src, type }, retry) => {
  console.log('Captcha image:', src);
  
  const key = await solveCaptcha(src); // Your captcha solving logic
  
  return retry(key);
});

// Handle 2FA
callbackService.onTwoFactor(async ({ phoneMask, type }, retry) => {
  console.log('Enter code sent to:', phoneMask);
  
  const code = await getCodeFromUser(); // Your code input logic
  
  return retry(code);
});

Best Practices

1

Use Environment Variables

Store credentials securely in environment variables, never hardcode them
const direct = new DirectAuthorization({
  login: process.env.VK_LOGIN,
  password: process.env.VK_PASSWORD,
  // ...
});
2

Request Minimal Permissions

Only request the permissions your application actually needs
scope: 'friends,photos', // Only what you need
3

Handle Errors Gracefully

Implement proper error handling for all authorization scenarios
try {
  const response = await direct.run();
} catch (error) {
  // Handle specific error codes
}
4

Store Tokens Securely

Save obtained tokens securely and reuse them instead of re-authenticating
const { token, expires } = await direct.run();
await secureStorage.save({ token, expires });

Complete Example

import { VK, CallbackService } from 'vk-io';
import { DirectAuthorization, officialAppCredentials, AuthErrorCode } from '@vk-io/authorization';

const callbackService = new CallbackService();

// Handle 2FA
callbackService.onTwoFactor(async ({ phoneMask }, retry) => {
  console.log(`Enter code sent to ${phoneMask}:`);
  const code = await getUserInput();
  return retry(code);
});

// Handle captcha
callbackService.onCaptcha(async ({ src }, retry) => {
  console.log(`Solve captcha: ${src}`);
  const key = await solveCaptcha(src);
  return retry(key);
});

const direct = new DirectAuthorization({
  callbackService,
  scope: 'messages,friends,wall',
  ...officialAppCredentials.android,
  login: process.env.VK_LOGIN,
  password: process.env.VK_PASSWORD,
  apiVersion: '5.199'
});

async function authorize() {
  try {
    const response = await direct.run();
    
    console.log('Authorization successful!');
    console.log('Token:', response.token);
    console.log('User ID:', response.user);
    
    // Use the token with VK-IO
    const vk = new VK({ token: response.token });
    const [user] = await vk.api.users.get({});
    console.log(`Logged in as: ${user.first_name} ${user.last_name}`);
    
  } catch (error) {
    if (error.code === AuthErrorCode.USERNAME_OR_PASSWORD_IS_INCORRECT) {
      console.error('Invalid credentials');
    } else if (error.code === AuthErrorCode.TOO_MUCH_TRIES) {
      console.error('Too many attempts. Try again in a few hours.');
    } else {
      console.error('Authorization failed:', error.message);
    }
  }
}

authorize();

Build docs developers (and LLMs) love