- Для авторизації додатків використовується відкритий протокол OAuth 2.0.
- Запити до API здійснюються без необхідності їх підписувати, завдяки використанню протоколу HTTPS.
Поїхали!
Підключаємо необхідні бібліотеки:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'oauth2' | |
require 'mechanize' |
Створюємо екземпляр класу OAuth2::Client:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@client = OAuth2::Client.new( | |
'client_id', | |
'client_secret', | |
:site => 'https://api.vk.com/', | |
:token_url => '/oauth/token', | |
:authorize_url => '/oauth/authorize' | |
) |
Для початку процесу авторизації необхідно створити вікно браузера і відкрити в ньому діалог авторизації за адресою, отриманою від клієнта OAuth2:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
auth_url = @client.auth_code.authorize_url( | |
:redirect_uri => 'http://api.vk.com/blank.html', | |
:scope => '', | |
:display => 'wap' | |
) | |
agent = Mechanize.new{|a| a.user_agent_alias = 'Linux Konqueror'} | |
login_page = agent.get(auth_url) |
В діалоговому вікні буде запропоновано ввести логін і пароль.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
login_form = login_page.forms.first | |
login_form.email = 'email' | |
login_form.pass = 'pass' | |
verify_page = login_form.submit |
Після успішного входу на сайт буде запропоновано авторизувати додаток(якщо це не так), дозволивши доступ до необхідних налаштувань, запитаних параметром scope(детальніше тут).
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
if verify_page.uri.path == '/oauth/authorize' | |
if /m=4/.match(verify_page.uri.query) | |
raise "Вказано невірний логін або пароль." | |
elsif /s=1/.match(verify_page.uri.query) | |
grant_access_page = verify_page.forms.first.submit | |
end | |
else | |
grant_access_page = verify_page | |
end |
Після успішної авторизації браузер буде перенаправлено за адресою :redirect_uri, вказаною при відкритті діалогу авторизації. При цьому код для отримання access_token буде переданий в URL-фрагменті посилання.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
code = /code=(?<code>.*)/.match(grant_access_page.uri.fragment)['code'] |
Отримуємо access_token:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@access_token = @client.auth_code.get_token(code) | |
@access_token.options[:param_name] = 'access_token' | |
@access_token.options[:mode] = :query |
Після успішної авторизації можна здійснювати запити до API.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@access_token.get('/method/getProfiles', :params => {:uids => '1', :fields => 'city,country'}).parsed |
P.S. Посилання на мою бібліотеку для авторизації ВКонтакте і здійснення запитів до API.
Немає коментарів:
Дописати коментар