Vk parser ошибка access token

https://api.vk.com/method/friends.get?user_id=babegone
{"error":{"error_code":5,"error_msg":"User authorization failed: no access_token passed.","request_params":[{"key":"oauth","value":"1"},{"key":"method","value":"friends.get"},{"key":"user_id","value":"babegone"}]}}


  • Вопрос задан

  • 23993 просмотра

Пригласить эксперта

Стоит ознакомиться с API ВКонтакте по их статье.

Ваше сообщение об ошибке однозначно указывает на её причину: User authorization failed: no access_token passed. – не авторизовать пользователя, выполняющего запрос по причине отсутствия access_token’а (ключа доступа).

Для выполнения friends.get() требуется ключ («access_token») либо сервисный – из настроек созданного вами Приложения ВК; либо пользователя – полученный в результате диалога авторизации пользователя.

Также обязательно стало указывать используемую версию API, параметр v. Сейчас актуальная версия 5.74

Чтобы просто попробовать, создайте приложение типа standalone и скопируйте из его Настроек значение Сервисного ключа:

скрин

5af6a32ecd7c0965325530.png

В итоге ваш запрос будет выглядеть примерно так:

https://api.vk.com/method/friends.get?user_id=babegone&v=5.74&access_token=supersecretsupersecret

Не указан токен авторизации


  • Показать ещё
    Загружается…

21 сент. 2023, в 20:54

10000 руб./за проект

21 сент. 2023, в 20:40

20000 руб./за проект

21 сент. 2023, в 19:28

10000 руб./за проект

Минуточку внимания

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

Closed

chikchik opened this issue

Oct 10, 2020

· 19 comments

Closed

VK authentication doesn’t work

#6936

chikchik opened this issue

Oct 10, 2020

· 19 comments

Comments

@chikchik

New Issue Checklist

  • I am not disclosing a vulnerability.
  • I am not just asking a question.
  • I have searched through existing issues.
  • I can reproduce the issue with the latest version of Parse Server.

Issue Description

VK authentication doesn’t work properly, because in source code used deprecated version of api (v5.8).
https://github.com/parse-community/parse-server/blob/master/src/Adapters/Auth/vkontakte.js: 14

On this page description of actual versions of api (strongly recommended v5.124)
https://vk.com/dev/constant_version_updates

It is a critical bug! Because I need to use VK auth on back4app, but I can’t/.

Steps to reproduce

No need to reproduce, just need to fix version of api in requests.

Actual Outcome

user_id and access_token are always valid.
Respose always returned ‘Vk auth is invalid for this user.’

Expected Outcome

Authentication without error.

Environment

Server

  • Parse Server version: 3.10.0
  • Operating system: Windows 10
  • Local or remote host (AWS, Azure, Google Cloud, Heroku, Digital Ocean, etc): back4app

Database

  • System (MongoDB or Postgres): MongoDB
  • Database version: N/A
  • Local or remote host (MongoDB Atlas, mLab, AWS, Azure, Google Cloud, etc): MongoDB

Client

  • SDK (iOS, Android, JavaScript, PHP, Unity, etc): Unity via rest api
  • SDK version:

Logs

@mtrezza
mtrezza

added
the

type:bug

Impaired feature or lacking behavior that is likely assumed

label

Oct 11, 2020

@mtrezza

Thank you for reporting. Well done, you have already identified the issue. Would you want to submit a PR?

Note that the version needs to be updated as you correctly pointed out, but the authentication should not fail yet, because it is not Oct 14. You may want to verify that there is no other issue in your code.

According to docs:

Requests made to the API with a version whose life cycle has expired will no longer be supported. The server will return an error to API requests with the old version.
From 14 October 2020, versions 5.80 and lower will be outdated.

@mtrezza
mtrezza

changed the title
VK authentication doesn’t work!

VK authentication doesn’t work

Oct 11, 2020

@chikchik

Note that the version needs to be updated as you correctly pointed out, but the authentication should not fail yet, because it is not Oct 14. You may want to verify that there is no other issue in your code.

But, unfortunately, fail happening.
If you make direct request from browser with same parameters (user_id and access_token) and version 5.8 you’ll get error.

if replace the version with at least 5.21 than no errors.

Thank you.

@mtrezza

Good that you found that out, so VK retired the 5.8 API earlier than documented.

Feel free to open a parse server PR and let me know if you need any guidance on how to do that.

@chikchik

I dont’t know how to make pull requests, because i’m stupid noob ).
Maybe I need any guidance on how to do that.

@mtrezza

The Contributing Guide should help to start with. If you have any questions, please let me know.

@mtrezza

@chikchik Would you be interested in making a PR? We have a blog article for first time contributors that is maybe less «technical» than the contribution guide.

@gadgetreviews

I have similar problems with current version. Currently latest VK API version is 5.131 and 5.124 is used in parse server. 5.124 is not too old, but I replaced 5.124 with 5.131 in parse server code in locally, and restarted parse server but it did not help and I still get «Vk auth is invalid for this user.» error. Several weeks ago, same code and same configuration was working fine, but now it does not.

I get following error when I try to run this flutter code:

var authData = {
	"id": vkUserId,
	"access_token": vkAccessToken,
};

final ParseResponse response = await ParseUser.loginWith(
        "vkontakte", authData,
      );
I/flutter ( 9656): ╭-- Parse Response
I/flutter ( 9656): Class: _User
I/flutter ( 9656): Function: ParseApiRQ.loginWith
I/flutter ( 9656): Status Code: 101
I/flutter ( 9656): Type: ObjectNotFound
I/flutter ( 9656): Error: Vk auth is invalid for this user.
I/flutter ( 9656): ╰-- 

Anyone else having same problem or I just made a mistake in my configuration or code?

Thanks for help

PS: I am using flutter and flutter_login_vk plugin for this project.

@mtrezza

@gadgetreviews We do not investigate issues with a modified version of Parse Server, so I suggest you try to reproduce the issue with the latest official version of Parse Server (and its vk auth adapter). From the issue description by @chikchik it seems that the vk auth adapter simply needs to be adapted to the latest VK API. Only changing the API endpoint version probably won’t help as the auth adapter itself may require adaptation.

To fix this, you could look into the changes of the API version and adapt the Parse Server VK auth adapter and its tests in AuthenticationAdapters.spec.js to work with the latest API. The process would be to determine whether this issue also exists with the alpha branch (presumably yes since the VK auth adapter has not changed). If it does, we will consider backporting the fix to the 4.x. branch.

@mtrezza
mtrezza

added

bounty:$10

Bounty applies for fixing this issue (Parse Bounty Program)

and removed

bounty:$5

Bounty applies for fixing this issue (Parse Bounty Program)

labels

Nov 9, 2021

@gadgetreviews

I don’t know how to proceed. Let me explain my problem in more detailed and share my code.
I am developing a mobile app with Flutter as front end and parse server as back end. I am using flutter_login_vk plugin to communicate with vk api.

Several weeks ago I tried login to vk with flutter_login_vk plugin v1.0.0 and it was working fine. Yesterday I upgraded flutter_login_vk plugin to v2.0.1 and I get this error log from parse-server:

I/flutter ( 9656): ╭-- Parse Response
I/flutter ( 9656): Class: _User
I/flutter ( 9656): Function: ParseApiRQ.loginWith
I/flutter ( 9656): Status Code: 101
I/flutter ( 9656): Type: ObjectNotFound
I/flutter ( 9656): Error: Vk auth is invalid for this user.
I/flutter ( 9656): ╰-- 

This is my simplified code in flutter:

void vkLogin() async {
    vk = VKLogin();
    await vk.initSdk();
    final res = await vk.logIn(scope: [
      VKScope.email,
      VKScope.photos,
    ]);
    if (! res.isError) {
      print("LoginView: vkLogin not error");
      final loginResult = res.asValue!.value;
      if (! loginResult.isCanceled) {
        print("LoginView: vkLogin not cancelled");
        var accessToken = loginResult.accessToken;
        vkAccessToken = accessToken!.token;
        vkUserId = accessToken.userId;
        await vkLoginWithToken();
      } else {
        print("Login cancelled");
      }
    } else {
      print("Login failed");
    }
}

Future<void> vkLoginWithToken() async {
    print("LoginView: vkLoginWithToken");
    if (vkAccessToken == null) return;
    if (await vk.isLoggedIn) {
      email = await vk.getUserEmail();
      var profile1 = await vk.getUserProfile();
      var profile = await profile1.asFuture;
      firstName =  profile!.firstName;
      lastName =  profile.lastName;
      pictureUrl = profile.photo200!;
      // Login to parse with vk
      var authData = {
        "id": vkUserId!,
        "access_token": vkAccessToken!
      };
/////////////
// I get error here
// response.success is false
////////////
      final ParseResponse response = await ParseUser.loginWith(
        "vkontakte", authData,
      );
      if (response.success) {
        // User is logged in, test with ParseUser.currentUser()
        currentUser = await ParseUser.currentUser();
      } else {
        print("Login failed");
      }
    } else {
      print("Unexpected error");
    }
}

I am not sure if it is related to parse-server or flutter_login_vk plugin. So I reported this problem both on parse-server and flutter_login_vk plugin github pages.

I get error log from parse server when ParseUser.loginWith was executed. And response.success returns as false.

How should I proceed?
Thanks for help.

@mtrezza

So I reported this problem both on parse-server and flutter_login_vk plugin github pages.

Please post the link when cross-posting, to avoid unnecessary work on either side.

Several weeks ago I tried login to vk with flutter_login_vk plugin v1.0.0 and it was working fine. Yesterday I upgraded flutter_login_vk plugin to v2.0.1 and I get this error log from parse-server:

If you downgrade to flutter_login_vk plugin v1.0.0 does it work? If so, you’d have to look at their changelog, because 2.0.1 is a major version jump and may contain a breaking change. That breaking change may cause an incompatibility with Parse Server.

@gadgetreviews

So I reported this problem both on parse-server and flutter_login_vk plugin github pages.

Please post the link when cross-posting, to avoid unnecessary work on either side.

Several weeks ago I tried login to vk with flutter_login_vk plugin v1.0.0 and it was working fine. Yesterday I upgraded flutter_login_vk plugin to v2.0.1 and I get this error log from parse-server:

If you downgrade to flutter_login_vk plugin v1.0.0 does it work? If so, you’d have to look at their changelog, because 2.0.1 is a major version jump and may contain a breaking change. That breaking change may cause an incompatibility with Parse Server.

If I downgraded to 1.0.0, it did not work but this time I can’t even start the app. App crashes as soon as opens.

This is the link that I opened case at flutter_login_vk plugin:

Innim/flutter_login_vk#17

@mtrezza

Thanks; it’s interesting that you say that the project was working fine some weeks ago. Did you change anything since then, the Parse Server version? Maybe try a fresh new minimum-example project. You can also try to delete node_modules and package-lock.json.

@gadgetreviews

I tested the same code with iOS simulator and it worked without any problems. I guess in this case the problem should not be related to parse server. I think it should be with flutter_login_vk plugin.

What do you think? Are there any differences between iOS and Android from parse-server’s point of view?

@gadgetreviews

This problem occurs only at android devices, and does not occur at iOS devices.

@mtrezza

I tested the same code with iOS simulator and it worked without any problems. I guess in this case the problem should not be related to parse server.

Good investigation! So I assume we can close this issue here?

What do you think? Are there any differences between iOS and Android from parse-server’s point of view?

I can’t see any difference from the server side, both are sending their requests via the REST API and Parse Server should react SDK-agnostic in this case.

@andrew-samara

About this issue.
Since some time VK starts checking iP address for given token, and if ip address of the authorised device and server (which tries to use that token) is different you will get this error. Token will be denied. So, now when you making auth within your device you have to add .offline scope key, to generate token with no IP binding.

Example for iOS (added Scopes.offline) :

func vkNeedsScopes(for sessionId: String) -> Scopes {
// Called when SwiftyVK attempts to get access to user account
// Should return a set of permission scopes
return [Scopes.email, Scopes.wall,  Scopes.photos, Scopes.offline]
}

Example for Android (added VKScope.OFFLINE):

ArrayList<VKScope> permissions = new ArrayList<>();
permissions.add(VKScope.WALL);
permissions.add(VKScope.PHOTOS);
permissions.add(VKScope.EMAIL);
permissions.add(VKScope.OFFLINE);
VK.login(activity, permissions);

There is no error with Parse server implementation.
Just need to implement right auth request from the device.

@gadgetreviews

About this issue. Since some time VK starts checking iP address for given token, and if ip address of the authorised device and server (which tries to use that token) is different you will get this error. Token will be denied. So, now when you making auth within your device you have to add .offline scope key, to generate token with no IP binding.

Example for iOS (added Scopes.offline) :

func vkNeedsScopes(for sessionId: String) -> Scopes {
// Called when SwiftyVK attempts to get access to user account
// Should return a set of permission scopes
return [Scopes.email, Scopes.wall,  Scopes.photos, Scopes.offline]
}

Example for Android (added VKScope.OFFLINE):

ArrayList<VKScope> permissions = new ArrayList<>();
permissions.add(VKScope.WALL);
permissions.add(VKScope.PHOTOS);
permissions.add(VKScope.EMAIL);
permissions.add(VKScope.OFFLINE);
VK.login(activity, permissions);

There is no error with Parse server implementation. Just need to implement right auth request from the device.

This problem occurs only android devices but I tried this method and it looks like it is working.

Thanks for this valuable information.

@mtrezza

Can this issue be closed, or do we need to make a change in Parse Server or any of the Parse client SDKs?

@andrew-samara

At current point, there is no issue with the parse server implementation.
So, this ticket can be closed.

Не могу выполнить метод groups.get. VK API
возвращает:

[error_code] => 5 [error_msg] => User authorization failed: no
access_token passed

При этом другие методы (getCities, getCountries) работают.

Вот эта строка неверно работает:

$groups = json_decode(@file_get_contents('https://api.vk.com/method/groups.get?uid'.$token[user_id].'')); 

Может проблема в том, что при получении token [expires_in] => 0?

Вот сам код:

<?
require_once('common_use.php');
session_start();
$client_id = '***';
$client_secret = '****';
$redirect_uri = 'http://site/outh.php';
$result = false;

if (isset($_GET['code'])) {
        $params = array(
            'client_id' => $client_id,
            'client_secret' => $client_secret,
            'code' => $_GET['code'],
            'redirect_uri' => $redirect_uri
        );

        $token = json_decode(@file_get_contents('https://oauth.vk.com/access_token' . '?' . urldecode(http_build_query($params))), true);    
        if (isset($token['access_token'])) {
            $params = array(
                    'uids'  => $token['user_id'],
                    'fields' => 'uid,city,country,first_name,last_name,screen_name,sex,bdate,photo_big,photo_rec,contacts',
                    'access_token' => $token['access_token']
            );

            $userInfo = json_decode(@file_get_contents('https://api.vk.com/method/users.get?' . urldecode(http_build_query($params))), true);               

            if (isset($userInfo['response'][0]['uid'])) {
                    $userInfo = $userInfo['response'][0];
                    $result = true;

                    // Вот тут ошибка
                    $groups = json_decode(@file_get_contents('https://api.vk.com/method/groups.get?uid'.$token[user_id].''));

                $sig = md5("api_id=".$client_id."method=getCitiesv=2.0api_secret=".$client_secret."");
                $res = json_decode(@file_get_contents('https://api.vk.com/method/getCities?api_id='.$client_id.'&sig='.$sig.'&v=2.0&cids='.$userInfo[city].''));
                $city = $res -> response[0] -> name;
            }
        }
}
?>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
app_id = 'ваш app_id'
access_token = 'ваш_ token'
user_id = 'user_id вашей vk страницы '
 
def vk(method, **params):
    
    url  = 'https://api.vk.com/method/%s' % method
    data = {
        'users.get'         : {'user_ids':''},
        'users.search'      : {'q':''},
        'users.getFollowers': {'user_id':''},
        'friends.get'       : {'user_id':''},
        'friends.getOnline' : {'user_id':''},
        'friends.search'    : {'user_id':'','q':''},
        'groups.get'        : {'user_id':''},
        'groups.search'     : {'q':''},
        'groups.getMembers' : {'group_id':''},
        'groups.getById'    : {'group_id':'','fields':'contacts,description,members_count'},
        'photos.get'        : {'owner_id':''},
        'video.get'         : {'owner_id':''},
        'video.search'      : {'q':''},
        'wall.get'          : {'count':'100'},
        'wall.search'       : {'owner_id':'', 'query':''},
        'wall.getById'      : {'posts':''},
        'status.get'        : {'user_id':''},
        'messages.get'      : {'count':'200'},
        'messages.getById'  : {'message_ids':''},
        'stats.get'         : {'date_from':'','data_to':''},
        
    }.get(method,{})
    
    data.update(params)
    data.update({'access_token':access_token})
    
    resp  = requests.post(url,data=data)
    answer = resp.json()
   
    if 'error' in answer:
        print('error:',answer )
        return []
    return answer ['response']
 
 
if __name__ == "__main__":    
    print(vk('users.get'))
    print(vk('users.search',q="Вася Пупкин"))
    print(vk('users.getFollowers'))
    print(vk('friends.get'))
    print(vk('friends.search',user_id=user_id, q='Вася'))
    
    time.sleep(2)
    
    print(vk('groups.get'))
    print(vk('groups.search',q='python'))
    print(vk('groups.getById',group_id='python_community'))
    print(vk('groups.getMembers',group_id='python_community'))
    
    time.sleep(2)
    
    print(vk('photos.get',owner_id=user_id,album_id='profile'))
    print(vk('status.get',user_id=user_id))
    print(vk('wall.get', count=1))
    print(vk('wall.getById', posts=user_id + '_' + '8'))
    print(vk('wall.search', owner_id=user_id, query='статья'))
    
    time.sleep(2)
    
    print(vk('video.get',owner_id=user_id,album_id='0'))
    print(vk('messages.get',count="10"))
    print(vk('stats.get',app_id=app_id,date_from='2018-01-01',date_to='2018-02-19'))

За последние 24 часа нас посетили 17068 программистов и 1268 роботов. Сейчас ищут 497 программистов …


  1. denis01

    Команда форума
    Модератор

    он не возвращает json? только этот текст?


  2. kostes

    С нами с:
    7 май 2017
    Сообщения:
    4
    Симпатии:
    0

    вывожу переменную $getMessages и пишет ошибку выше.
    — Добавлено —

    весь текст:
    {«error»:{«error_code»:5,»error_msg»:»User authorization failed: no access_token passed.»,»request_params»:[{«key»:»oauth»,»value»:»1″},{«key»:»method»,»value»:»messages.get»},{«key»:»offset»,»value»:»1″},{«key»:»count»,»value»:»1″},{«key»:»client_secret»,»value»:»[тут client secret]»}]}}


  3. denis01

    Команда форума
    Модератор

    точно в curl передаётся все данные? как ты проверял это?


  4. kostes

    С нами с:
    7 май 2017
    Сообщения:
    4
    Симпатии:
    0

    вот curl

    1. curl_setopt($ch, CURLOPT_USERAGENT, ‘Opera/9.80 (Windows NT 6.1; WOW64) Presto/2.12.388 Version/12.14’);


  5. denis01

    Команда форума
    Модератор


  6. denis01

    Команда форума
    Модератор

    я давал ссылки на отладку, изучай, это поможет найти почти любую ошибку

Понравилась статья? Поделить с друзьями:
  • Vlt micro drive ошибка al13 как исправить
  • Vlt micro drive ошибка al31
  • Vlt micro drive ошибка al16
  • Vlt micro drive al29 ошибка
  • Virtualbox ошибка сегментирования