Giter VIP home page Giter VIP logo

passport-vkontakte's Introduction

Passport-VKontakte

Build Status

Passport strategy for authenticating with VK using the OAuth 2.0 API.

This module lets you authenticate using VK in your Node.js applications. By plugging into Passport, VK authentication can be easily and unobtrusively integrated into any application or framework that supports Connect-style middleware, including Express.

Installation

$ npm install passport-vkontakte

Usage

Configure Strategy

Using this strategy, you can authenticate users who have a VK account and access their data, given their access permission.

In order to be used, a strategy must be configured with two parameters.

import Strategy as VKStrategy from "passport-vkontakte";
passport.use(new VKStrategy(options, verify));
Parameter Type Desciption
options object App credentials and callback URL
verify function Strategy verification callback

Strategy options

The options objects provides the strategy with the information it needs to represent your app to VK API. It includes your app credentials (application id and secret), as well as the callback URL to which the user will be redirected after they complete the authentication process.

Field Type Description
clientID string Your app's client id
clientSecret string Your app's secret
callbackURL string The full URL to your authentication completion handler
profileFields array A list of profile fields
apiVersion string The version of VK API implementation
lang string The language which should be used to represent the profile data

Strategy verify callback

A verify callback function is called after resource owner (the user) has accepted or declined the authorization request. In the example below, this function is called myVerifyCallbackFn.

It can have one of four signatures:

function(accessToken, refreshToken, profile, done) {}
function(accessToken, refreshToken, params, profile, done) {}
function(req, accessToken, refreshToken, params, profile, done) {}
Parameter Type Description
req object
accessToken string OAuth2 access token
refreshToken string OAuth2 refresh token
params object
profile object User profile
done function "Done" callback

The verify function can use the profile and params fields to find, create or update any kind of information that corresponds to now authenticated user.

After the user has been successfully authenticated, the done function should be called, to supply Passport with the user data as seen by the application.

return done(null, user);

In case of authentication error, false should be supplied instead.

return done(null, false);

Additional info object can be provided to indicate the reason for failure.

return done(null, false, { message: "User account is suspended" });

For transient errors, pass the error object as the first parameter.

return done(new Error("User database is not available, try later"));
const VKontakteStrategy = require("passport-vkontakte").Strategy;

// User session support middlewares. Your exact suite might vary depending on your app's needs.
app.use(require("cookie-parser")());
app.use(require("body-parser").urlencoded({ extended: true }));
app.use(
    require("express-session")({
        secret: "keyboard cat",
        resave: true,
        saveUninitialized: true,
    })
);
app.use(passport.initialize());
app.use(passport.session());

passport.use(
    new VKontakteStrategy(
        {
            clientID: VKONTAKTE_APP_ID, // VK.com docs call it 'API ID', 'app_id', 'api_id', 'client_id' or 'apiId'
            clientSecret: VKONTAKTE_APP_SECRET,
            callbackURL: "http://localhost:3000/auth/vkontakte/callback",
        },
        function myVerifyCallbackFn(
            accessToken,
            refreshToken,
            params,
            profile,
            done
        ) {
            // Now that we have user's `profile` as seen by VK, we can
            // use it to find corresponding database records on our side.
            // Also we have user's `params` that contains email address (if set in
            // scope), token lifetime, etc.
            // Here, we have a hypothetical `User` class which does what it says.
            User.findOrCreate({ vkontakteId: profile.id })
                .then(function (user) {
                    done(null, user);
                })
                .catch(done);
        }
    )
);

// User session support for our hypothetical `user` objects.
passport.serializeUser(function (user, done) {
    done(null, user.id);
});

passport.deserializeUser(function (id, done) {
    User.findById(id)
        .then(function (user) {
            done(null, user);
        })
        .catch(done);
});

Authenticate Requests

Use passport.authenticate(), specifying the 'vkontakte' strategy, to authenticate requests.

For example, as route middleware in an Express application:

//This function will pass callback, scope and request new token
app.get("/auth/vkontakte", passport.authenticate("vkontakte"));

app.get(
    "/auth/vkontakte/callback",
    passport.authenticate("vkontakte", {
        successRedirect: "/",
        failureRedirect: "/login",
    })
);

app.get("/", function (req, res) {
    //Here you have an access to req.user
    res.json(req.user);
});
Display Mode

Set display in passport.authenticate() options to specify display mode. Refer to the OAuth dialog documentation for information on its usage.

app.get(
    "/auth/vkontakte",
    passport.authenticate("vkontakte", { display: "mobile" }),
    function (req, res) {
        // ...
    }
);

Extended Permissions

If you need extended permissions from the user, the permissions can be requested via the scope option to passport.authenticate().

For example, this authorization requests permission to the user's friends:

app.get(
    "/auth/vkontakte",
    passport.authenticate("vkontakte", {
        scope: ["status", "email", "friends", "notify"],
    }),
    function (req, res) {
        // The request will be redirected to vk.com for authentication, with
        // extended permissions.
    }
);

Profile Fields

The VK.com profile may contain a lot of information. The strategy can be configured with a profileFields parameter which specifies a list of additional fields your application needs. For example, to fetch users's city and bdate configure strategy like this.

Notice that requesting the user's email address requires an email access scope, which you should explicitly list as in following example:

passport.use(
    new VKontakteStrategy(
        {
            ...{ clientID, clientSecret, callbackURL },
            scope: ["email" /* ... and others, if needed */],
            profileFields: ["email", "city", "bdate"],
        },
        myVerifyCallbackFn
    )
);

Profile fields language

By default, profile fields such as name are returned in English. The strategy can be configured with a lang parameter which specifies language of value returned.

For example, this would configure the strategy to return name in Russian:

passport.use(
    new VkontakteStrategy(
        {
            ...{ clientID, clientSecret, callbackURL },
            lang: "ru",
        },
        myVerifyCallbackFn
    )
);

API version

The VK.com profile structure can differ from one API version to another. The specific version to use can be configured with a apiVersion parameter. The default is 5.110.

passport.use(
    new VKontakteStrategy(
        {
            ...{ clientID, clientSecret, callbackURL },
            apiVersion: "5.17",
        },
        myVerifyCallbackFn
    )
);

Tests

$ npm install --dev
$ make test

Credits

Special Thanks

To all the people who had to cope with idiosyncrasies of OAuth2 and VK API!

License

(The MIT License)

Copyright (c) 2011 Jared Hanson

Copyright (c) 2012, 2016 Stepan Stolyarov

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

passport-vkontakte's People

Contributors

antonlukin avatar asinyagin avatar eugeniop avatar ivanmmm avatar jaredhanson avatar lbeschastny avatar maxkoryukov avatar negezor avatar olegmdev avatar siacomuzzi avatar stan-ros avatar staxmanade avatar stevebest avatar svlapin avatar yhaskell avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

passport-vkontakte's Issues

500 on access_denied

In strategy.js line 81:

return this.error(new VkontakteAuthorizationError(req.query.error_description, req.query.error, req.query.error_reason));

Please fix, should be this.fail for access denied, because this.error is meant for an "internal error while performing authentication".

That automatically resolves the issue with 500 on access denied.

From time to time does not work

Authentication works, but often there is an error .. I noticed the following errors:

InternalOAuthError: failed to fetch user profile
    at /home/www/workspace/node_modules/passport-vkontakte/lib/passport-vkontakte/strategy.js:144:28
    at ClientRequest.<anonymous> (/home/www/workspace/node_modules/passport-vkontakte/node_modules/passport-oauth2/node_modules/oauth/lib/oauth2.js:148:5)
    at ClientRequest.emit (events.js:107:17)
    at TLSSocket.socketErrorListener (_http_client.js:272:9)
    at TLSSocket.emit (events.js:129:20)
    at net.js:451:14
    at process._tickCallback (node.js:355:11)


InternalOAuthError: Failed to obtain access token
    at Strategy.OAuth2Strategy._createOAuthError (/home/www/workspace/node_modules/passport-vkontakte/node_modules/passport-oauth2/lib/strategy.js:349:17)
    at /home/www/workspace/node_modules/passport-vkontakte/node_modules/passport-oauth2/lib/strategy.js:171:43
    at /home/www/workspace/node_modules/passport-vkontakte/node_modules/passport-oauth2/node_modules/oauth/lib/oauth2.js:177:18
    at ClientRequest.<anonymous> (/home/www/workspace/node_modules/passport-vkontakte/node_modules/passport-oauth2/node_modules/oauth/lib/oauth2.js:148:5)
    at ClientRequest.emit (events.js:107:17)
    at TLSSocket.socketErrorListener (_http_client.js:272:9)
    at TLSSocket.emit (events.js:129:20)
    at net.js:451:14
    at process._tickCallback (node.js:355:11)

code:

VKontakteStrategy = require('passport-vkontakte').Strategy
...
passport.use(new VKontakteStrategy({
      clientID:     VKONTAKTE_APP_ID, // VK.com docs call it 'API ID'
      clientSecret: VKONTAKTE_APP_SECRET,
      callbackURL:  "https://local/workspace/auth/vkontakte/callback/"
    },
    function(accessToken, refreshToken, profile, done) {
      console.log(profile);
    });
    });

app.get('/auth/vkontakte', passport.authenticate('vkontakte', { 
    successRedirect: '/workspace/', 
    failureRedirect: '/error'
    //scope: ['email'] 
  }));

  app.get('/auth/vkontakte/callback/',
      passport.authenticate('vkontakte', { 
        failureRedirect: '/workspace/auth/vkontakte'
        //scope: ['email'] 
      }),
        function(req, res) {
    console.log("[OAuth2:redirect:query]:", JSON.stringify(req.query));
      console.log("[OAuth2:redirect:body]:", JSON.stringify(req.body))
          // Successful authentication, redirect home.
          res.redirect('workspace/');
        });

In parallel, authentication is used by Facebook - works without a glitch. Construction and FB VK completely identical.

The error occurs randomly depending on track .. .. That could not work - it is not ..
Actually because of what autentifikatsiz VKontakte can behave this way?

InternalOAuthError: Failed to obtain access token

Добрый день, пытаясь запустить пример из репозитория при авторизации выходит такой стек ошибок:

InternalOAuthError: Failed to obtain access token
at Strategy.OAuth2Strategy._createOAuthError (D:\Work\sdb\node_modules\passport-oauth2\lib\strategy.js:370:17)
at D:\Work\sdb\node_modules\passport-oauth2\lib\strategy.js:166:45
at D:\Work\sdb\node_modules\oauth\lib\oauth2.js:177:18
at ClientRequest. (D:\Work\sdb\node_modules\oauth\lib\oauth2.js:148:5)
at emitOne (events.js:96:13)
at ClientRequest.emit (events.js:188:7)
at TLSSocket.socketErrorListener (_http_client.js:310:9)
at emitOne (events.js:96:13)
at TLSSocket.emit (events.js:188:7)
at emitErrorNT (net.js:1276:8)

В чем именно может быть проблема?

Is there any way to authorize?

Hello again :)
I am using several types of authentication in my app and I need to connect user's vk account to previously created account in db.
What do we have?

  1. User account created with basic auth
  2. User account in vk we want to connect.

If I use "passport.authenticate" I got new session for my user with all his vk data in req.user field. I want this data to be in req.account field and keep req.user untouched.

You can read more about third-party authorize here

Or may be is there any other way to get user's vk data without resetting user's session?

Code is invalid or expired

При самой первой авторизации на сайте получаю такую ошибку, но при этом авторизация выполняется у пользователя:
TokenError: Code is invalid or expired. at Strategy.OAuth2Strategy.parseErrorResponse (/srv/13case/node_modules/passport-oauth2/lib/strategy.js:320:12) at Strategy.parseErrorResponse (/srv/13case/node_modules/passport-vkontakte/lib/passport-vkontakte/strategy.js:176:54) at Strategy.OAuth2Strategy._createOAuthError (/srv/13case/node_modules/passport-oauth2/lib/strategy.js:367:16) at /srv/13case/node_modules/passport-oauth2/lib/strategy.js:166:45 at /srv/13case/node_modules/oauth/lib/oauth2.js:191:18 at passBackControl (/srv/13case/node_modules/oauth/lib/oauth2.js:132:9) at IncomingMessage.<anonymous> (/srv/13case/node_modules/oauth/lib/oauth2.js:157:7) at emitNone (events.js:91:20) at IncomingMessage.emit (events.js:185:7) at endReadableNT (_stream_readable.js:974:12)

Код обработчика:
passport.use(new VkStrategy( { clientID: config.get('vkID'), clientSecret: config.get('vkSecret'), callbackURL: config.get('vkCb') + '/auth/vk/callback' }, function verify(accessToken, refreshToken, params, profile, done) { process.nextTick(function () { return done(null, { userid: profile.id, username: profile.displayName, photoUrl: profile.photos[0].value, profileUrl: profile.profileUrl }); }); } ));

Код роутерингов:
app.get('/auth/vk', passport.authenticate('vkontakte'), function(req, res){}); app.get('/auth/vk/undefined', passport.authenticate('vkontakte'), function(req, res){}); app.get('/auth/vk/callback', passport.authenticate('vkontakte', { failureRedirect: '/' }), function(req, res) { res.redirect(req.headers.referer); });

В чем проблема?

Publish new release

As I can see, the latest release 0.3.2 published on github and npm does not include latest commits from the master branch. It would be great to publish the new version.

I currently use github link in my package.json file in order to get the latest version.

Bump minimum API version

According new API Version Life Cycle we should bump minimum API version to prevent current error:

{"success":false,"message":"Invalid request: versions below 5.21 are deprecated. Version param should be passed as \"v\". \"version\" param is invalid and not supported. For more information go to https://vk.com/dev/constant_version_updates"}

Not working login to VK from aws.

Hi,
could you please help me with my issue?

Now I'm working on login through VK using passport-vkontakte. On my local machine all working well.
In vk app settings "Site address": "http://localhost:1337",
callbackUrl is "http://localhost:1337/auth/vkontakte/callback".

If I move my app to amazon server, login is broken.
"Site address": "http://my-amazon-domain.tk:1337"
callbackUrl: "http://my-amazon-domain.tk:1337/auth/vkontakte/callback"

When I make attempt to login, I received exception
error

It's some strange exception, and I can't find possibility to fix them.
Maybe you have some suggestions for resolving this problem?

Ошибка при нажатии отмены из мобильной версии когда мы не авторизованы в вк

Последовательность действий следующая:
  1. Мы не авторизованы в ВК. Пытаемся войти на свой сайт через вк, идёт редирект в вк и в мобильной версии нам предлагают войти в кабинет, или нажать отмену.
  2. Жмём отмену и выпадает error

VkontakteAuthorizationError: User denied your request at Strategy.authenticate (/www/xxx/node_modules/passport-vkontakte/lib/passport-vkontakte/strategy.js:81:23) at attempt (/www/xxx/node_modules/passport/lib/middleware/authenticate.js:348:16) at authenticate (/www/xxx/node_modules/passport/lib/middleware/authenticate.js:349:7) at Layer.handle [as handle_request]

Думаю в этом случае надо обрабатывать сие событие не как ошибку, а как failureRedirect

VKontakteStrategy - object is not a function

VKontakteStrategy = require('passport-vkontakte'),
....

passport.use(new VKontakteStrategy({
        clientID:     VKONTAKTE_APP_ID, 
        clientSecret: VKONTAKTE_APP_SECRET,
        callbackURL:  "https://local:8081/auth/vkontakte/callback"
      },
      function(accessToken, refreshToken, profile, done) {
            // asynchronous verification, for effect...
            process.nextTick(function () {

              // To keep the example simple, the user's Facebook profile is returned to
              // represent the logged-in user.  In a typical application, you would want
              // to associate the Facebook account with a user record in your database,
              // and return that user instead.
              return done(null, profile);
            });
          }
        ));

When start apps:

/home/app.js:349
    passport.use(new VKontakteStrategy({
                 ^
TypeError: object is not a function
    at Object.<anonymous> (/home/app.js:349:15)
    at Module._compile (module.js:460:26)
    at Object.Module._extensions..js (module.js:478:10)
    at Module.load (module.js:355:32)
    at Function.Module._load (module.js:310:12)
    at Module.runMain [as _onTimeout] (module.js:501:10)
    at Timer.listOnTimeout (timers.js:110:15)

what could be wrong?

Где хранится token?

Когда в стратегии получаешь accessToken, к нему можно как-то обратиться где-нибудь тут:

app.get("/page", function (req, res) {
// accessToken ?
});

Или его нужно сохранять отдельно и доставать когда надо пока он жив?

Unable to get user's email

At now Vkontakte allows to get user's email via specifying scope: ['email'] parameter:

app.get('/auth/vkontakte',
  passport.authenticate('vkontakte', scope: ['email']),
  function(req, res){
    // The request will be redirected to vk.com for authentication, so
    // this function will not be called.
});

But unfortunately I don't get this one:

passport.use(new VkontakteStrategy({
    clientID: /* clientID */,
    clientSecret: /* clientSecret */,
    callbackURL:  /* callbackURL*/
},
function(token, refreshToken, profile, done) {
      console.log(profile.email) // undefined;
});

What I'm doing wrong?

VKontakteStrategy: verify callback must take 4 or 5 parameters

Привет!

Я использую твой модуль с @nestjs/passport (это обвязка passport для фреймворка nest).

Вот так выглядит мой обработчик:

import { Strategy, VerifyCallback } from 'passport-vkontakte'
import { PassportStrategy } from '@nestjs/passport'
import { Injectable } from '@nestjs/common'
import { AuthService } from '../auth.service'

@Injectable()
export class VkStrategy extends PassportStrategy(Strategy, 'vk') {
    constructor(private authService: AuthService) {
        super({
            clientID:     1,
            clientSecret: '123',
            callbackURL:  'https://localhost/auth/vk/callback',
            scope: ['status', 'email', 'friends', 'notify']
        })
    }

    async validate (accessToken: string, refreshToken: string, params: string, profile: any, done: VerifyCallback): Promise<any> {
        console.log({ accessToken, refreshToken, params, profile })
        done(null, profile)
    }
}

И после прохождения авторизации в ВК получаю:

[ExceptionsHandler] VKontakteStrategy: verify callback must take 4 or 5 parameters +9700ms
Error: VKontakteStrategy: verify callback must take 4 or 5 parameters
    at VkStrategy.passportVerify [as _verify] (/root/backend/node_modules/passport-vkontakte/lib/strategy.js:95:18)
    at /root/backend/node_modules/passport-oauth2/lib/strategy.js:200:24
    at /root/backend/node_modules/passport-vkontakte/lib/strategy.js:177:7
    at passBackControl (/root/backend/node_modules/oauth/lib/oauth2.js:134:9)
    at IncomingMessage.<anonymous> (/root/backend/node_modules/oauth/lib/oauth2.js:157:7)
    at IncomingMessage.emit (events.js:327:22)
    at IncomingMessage.EventEmitter.emit (domain.js:485:12)
    at endReadableNT (_stream_readable.js:1224:12)
    at processTicksAndRejections (internal/process/task_queues.js:84:21)

Я перешел в node_modules/passport-vkontakte/lib/strategy.js,
в функции verifyWrapper поменял var arity = verify.length; на var arity = 5;
и все заработало, в своем обработчике я получил нужный ответ.

К сожалению, у меня нет возможности продебажить все самостоятельно, но очень надеюсь, что ты выпустишь фикс :)

P.S.: console.log(verify.length) отдает 0

Передача email адреса!

Если мы передаем
passport.authenticate('vk',{cope: ['email']})
то эмайл возвращается всместе с access_token, а не при запросе user.get.
и в дальнейшем теряется, на выходе мы получаем профайл без эмайла.

Пофикстите пожалуйста или я, что то не так делаю?

Промежуточный запрос
Результат

example/login не работает

После авторизации выдает ошибку
API версии 5.0, 5.17 и 5.63 (последняя)

@stevebest возможно ли обновить example?

package.json:

{
  "name": "passport-vkontakte-examples-login",
  "version": "0.0.0",
  "dependencies": {
    "cookie-parser": "^1.4.3",
    "ejs": "2.5.1",
    "express": "4.14.0",
    "express-session": "^1.15.6",
    "passport": "0.3.2"
  },
  "scripts": {
    "start": "node app"
  }
}
   at Strategy.OAuth2Strategy.parseErrorResponse (/Users/borapop/passport-vkontakte/node_modules/passport-oauth2/lib/strategy.js:329:12)
   at Strategy.parseErrorResponse (/Users/borapop/passport-vkontakte/lib/strategy.js:197:54)
   at Strategy.OAuth2Strategy._createOAuthError (/Users/borapop/passport-vkontakte/node_modules/passport-oauth2/lib/strategy.js:376:16)
   at /Users/borapop/passport-vkontakte/node_modules/passport-oauth2/lib/strategy.js:166:45
   at /Users/borapop/passport-vkontakte/node_modules/oauth/lib/oauth2.js:191:18
   at passBackControl (/Users/borapop/passport-vkontakte/node_modules/oauth/lib/oauth2.js:132:9)
   at IncomingMessage.<anonymous> (/Users/borapop/passport-vkontakte/node_modules/oauth/lib/oauth2.js:157:7)
   at emitNone (events.js:91:20)
   at IncomingMessage.emit (events.js:185:7)
   at endReadableNT (_stream_readable.js:974:12)```

Cannot get email address

Your documentation is little outdated and should be updated.

Verify callback function can accept from 4 to 5 arguments and if you use 4 arguments you cannot get an email address and token lifetime even if it's set in scope and fields.

You should use
function myVerifyCallbackFn(accessToken, refreshToken, params, profile, done){ ... }
and you can get both 'email' and 'expires_in' from 'params' field.

АВТАР ПИДАРАС ОШИБКА 500

АЛЁ.
СЛЫШ ДАУН
ЕСЛИ ВКАНТАКТИКЕ АТМЕНИТЬ ВХОД АШИПКА 500
С ДРУГИМ СОЦ СЕТЯМИ ВСЁ ОК.

БЫСТРА БЛЯТЬ ИСПРАВИЛ АУ #34

Ошибки в консоли

Постоянно получаю ошибки в консоль, вида:
VkontakteAuthorizationError: User denied your request
И т.п.
Как их вообще отключить?

Getting a phone number

Is there a way to get a phone number during authentication? For example, to receive an email, you need to specify scope: ['email']:

app.get('/auth/vkontakte', passport.authenticate('vkontakte', { scope: ['email'] }));

What you need to do to get a phone number?

No 'Access-Control-Allow-Origin' header is present on the requested resource.

I try to use passport-vkontakte.
I have created my application in VK.
I've set
website URL: http://localhost
home domain: localhost
Trusted redirect URI: http://localhost/auth/vkontakte/callback.
I'm using localhost:80 for local server.
But when I send request to URI '/auth/vkontakte' (https://github.com/stevebest/passport-vkontakte#authenticate-requests)
I get the error

XMLHttpRequest cannot load https://oauth.vk.com/authorize?response_type=code&redirect_uri=https...&scope=status%2Cemail%2Cfriends%2Cnotify&client_id=5675624. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access.

What do I wrong?

scope never gets set

I think line 131 of strategy.js is missing this:

var scope = options.scope || this._scope;

Otherwise, the original settings get lost and are never sent to vk.

Error handling bug

When user cancel auth request - server throw 5xx errors.
By design - it must redirected to failureRedirect.

504 gateway time-out

Ошибка вылетает раз в 10-15 попыток авторизации. Проблема не в провайдере - пробовалось из разных городов и разных стран. Скорее всего, это проблема самого ВК. Но, возможно, посоветуете какое-то решение. Или чтоб сам пасспорт как-то реагировал на это

Добавить require к примерам кода на GitHub

Если не слишком лениво добавьте способ объявления VKontakteStrategy к примерам во избежания недопониманий.
Имею ввиду строчку вроде
var VKontakteStrategy = require('passport-vkontakte').Strategy; (если код по большей части форк фб аналога).

passReqToCallback removing

Why are you removed support of the options.passReqToCallback introduced in 3873c1a? This, in particular, discards the ability to connect existing user account with VK account.

InternalOAuthError: Failed to obtain access token

Запустил пример
и получил ошибку

InternalOAuthError: Failed to obtain access token
    at Strategy.OAuth2Strategy._createOAuthError (/home/neo/node.js/test-modules/test-pasport/playground/passport-vkontakte/passport-vkontakte/examples/login/node_modules/passport-vkontakte/node_modules/passport-oauth2/lib/strategy.js:370:17)
    at /home/neo/node.js/test-modules/test-pasport/playground/passport-vkontakte/passport-vkontakte/examples/login/node_modules/passport-vkontakte/node_modules/passport-oauth2/lib/strategy.js:166:45
    at /home/neo/node.js/test-modules/test-pasport/playground/passport-vkontakte/passport-vkontakte/examples/login/node_modules/oauth/lib/oauth2.js:191:18
    at ClientRequest.<anonymous> (/home/neo/node.js/test-modules/test-pasport/playground/passport-vkontakte/passport-vkontakte/examples/login/node_modules/oauth/lib/oauth2.js:162:5)
    at ClientRequest.emit (events.js:182:13)
    at TLSSocket.socketErrorListener (_http_client.js:391:9)
    at TLSSocket.emit (events.js:182:13)
    at emitErrorNT (internal/streams/destroy.js:82:8)
    at emitErrorAndCloseNT (internal/streams/destroy.js:50:3)
    at process._tickCallback (internal/process/next_tick.js:63:19)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.