Python авторизация на yandex

Get a token

This example shows getting an OAuth token in the web service. Recommendations for other types of applications (desktop or mobile) are given in the Yandex OAuth documentation.

Installing additional libraries

The pip utility is included in Python 2 beginning with version 2.7.9, and in Python 3 beginning with version 3.4. If you are using an earlier version of Python, you need to install pip. For example, you can use the script https://bootstrap.pypa.io/get-pip.py.

Callback URL

When registering or editing application parameters on the Yandex OAuth service, you must set the Callback URL to the URL of the script that is receiving the token. For example:

Procedure

The token request requires specifying the application ID and password that were generated during registration on the Yandex OAuth service.

https://oauth.yandex.com/authorize?response_type=code&client_id=APPLICATION_ID

Yandex OAuth performs a redirect to the address from Callback URL . In addition, the code parameter is appended to the address. For example:

 http://site.ru/get_token?code=AUTHORIZATION_CODE

Yandex OAuth sends a response in JSON format. The access_token key contains the OAuth token. For example:

Читайте также:  Какие виды форм бывают html

Run the script

Flask allows you to specify just the IP address and port to run the script on. There are several options for running the script:

Run the application on a public IP address (one that other devices on the internet can see). This IP address must be specified for your domain in DNS, and the application must be running on the correct port (443 for HTTPS).

Use a web server for proxying requests. For example, you can use Nginx with the following configuration:

Script code

To use this example, specify the application ID and password.

# -*- coding: utf-8 -*-\nfrom flask import Flask, request, jsonify, redirect\nfrom requests import post\n\n# URL encoding method both in Python 3 and in Python 2\nimport sys\n\nif sys.version_info < (3, 0): # Pytohn2.x\n from urllib import urlencode\nelse: # Python3.x\n from urllib.parse import urlencode\n\n# Application ID\nclient_id = 'APPLICATION_ID'\n# Application password\nclient_secret = 'APPLICATION_PASSWORD'\n# Address of the Yandex OAuth server\nbaseurl = 'https://oauth.yandex.ru/'\n\napp = Flask (__name__)\n\n\n@app. route('/')\ndef index ():\n if request.args.get('code', False):\n #If the script was called with the "code" parameter in the URL,\n #it executes a request to get a token\n print(request.args)\n print(request.data)\n data = \n data = urlencode(data)\n # Save the token to use in requests to the Yandex Direct API\n return jsonify (post (baseurl + "token", data). json())\nelse:\n # If the script was called without the "code" parameter,\n # the user is redirected to the access request page\n return redirect(baseurl + "authorize?response_type=code&client_id=<>".format(client_id))\n\n\nif __name__ == '__main__':\n # Debugging information\n # app.debug = True\n # Start the web server with access on port 8000\n app.run(host='127.0.0.1', port=8000)

Источник

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

Authorization on Yandex via a regular web form with the help of Python’s script. It is necessary in order to parse data from Yandex service, that doesn’t have an API. RUS: Авторизация через обычную веб-форму на Яндексе через Python-скрипт. Это нужно для того, что распарсить данные с Яндекс-сервиса у которого нет API.

leontyev-anton/passport.yandex.ru-web_auth

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

Authorization on Yandex via a regular web form with the help of Python’s script. It is necessary in order to parse data from Yandex service, that doesn’t have an API. Example work with PyQuery.

Go to the page https://passport.yandex.ru/auth in browser, open the browser’s Inspect (Network -> Preserve log -> All | XHR).

First, enter the login — as you can see, a request has gone to the ‘start’ url. Then enter a password — a request has gone to the ‘commit_password’ url.

Learn carefully what goes where (Inspector: Headers, Preview) and implement a similar behavior in the script (there are additional comments in the code).

RUS: Авторизация через обычную веб-форму на Яндексе через Python-скрипт. Это нужно для того, что распарсить данные с Яндекс-сервиса, у которого нет API. Пример работы с PyQuery.

Заходим в браузере на страницу https://passport.yandex.ru/auth, открываем отладчик в браузере (Network -> Preserve log -> All | XHR).

Сначала вводим логин — видим что ушел запрос на страницу start. Потом вводим пароль — ушел запрос на страницу commit_password.

Изучаем внимательно что куда отправляется (в отладчике Headers, Preview) и реализуем подобное поведение в скрипте (в коде есть дополнительные комментарии).

About

Authorization on Yandex via a regular web form with the help of Python’s script. It is necessary in order to parse data from Yandex service, that doesn’t have an API. RUS: Авторизация через обычную веб-форму на Яндексе через Python-скрипт. Это нужно для того, что распарсить данные с Яндекс-сервиса у которого нет API.

Источник

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

Библиотека для работы с OAuth сервисом Яндекс ID

License

LulzLoL231/YandexID

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

Библиотека для работы с API Яндекс ID (OAuth) для Python 3.10+. Поддерживает асинхронную работу.

pip install https://github.com/LulzLoL231/yandexid.git
git clone https://github.com/LulzLoL231/yandexid pip install ./yandexid
from yandexid import YandexOAuth yandex_oauth = YandexOAuth( client_id='', client_secret='', redirect_uri='' ) auth_url = yandex_oauth.get_authorization_url() # Тут нужно перейти по ссылке auth_url и получить код авторизации token = yandex_oauth.get_token_from_code('')
from yandexid import YandexID yandex_id = YandexID('') user_info = yandex_id.get_user_info_json()

Чтобы использовать асинхронность, используйте классы AsyncYandexOAuth и AsyncYandexID :

from yandexid import AsyncYandexID yandex_id = AsyncYandexID('') user_info = await yandex_id.get_user_info_json()

Название методов полностью совпадает с названием синхронных методов, не забывайте использовать await перед вызовом асинхронных методов.

Логотипы Яндекс ID и название сервиса «Яндекс ID» принадлежат Яндексу.

About

Библиотека для работы с OAuth сервисом Яндекс ID

Источник

Получение токена

Пример демонстрирует получение OAuth-токенa веб-сервисом. Рекомендации для других типов приложений (настольное, мобильное) приведены в документации Яндекс.OAuth.

Установка дополнительных библиотек

Утилита pip включена в Python 2 начиная с версии 2.7.9 и в Python 3 начиная с версии 3.4. Если вы используете более раннюю версию Python, установите pip, например, с помощью скрипта https://bootstrap.pypa.io/get-pip.py.

Callback URL

При регистрации или редактировании параметров приложения на сервисе Яндекс.OAuth необходимо в поле Callback URL указать URL скрипта, выполняющего получение токена. Например:

Последовательность действий

При запросе токена требуется указывать идентификатор и пароль приложения, сгенерированные при регистрации на сервисе Яндекс.OAuth.

https://oauth.yandex.ru/authorize?response_type=code&client_id=ИДЕНТИФИКАТОР_ПРИЛОЖЕНИЯ

Яндекс.OAuth осуществляет редирект на адрес из Callback URL . При этом к адресу добавляется параметр code . Например:

 http://site.ru/get_token?code=КОД_ПОДТВЕРЖДЕНИЯ

Запуск скрипта

Flask позволяет указать только IP-адрес и порт, на котором запускается скрипт. Существует несколько вариантов запуска скрипта:

Запустите приложение на публичном (то есть видимом из интернета) IP-адресе. Для вашего домена в DNS должен быть указан именно этот IP-адрес, а приложение должно быть запущено на корректном порту (443 для HTTPS).

Более подробную информацию вы можете найти на странице http://flask.pocoo.org/docs/0.12/deploying.

Код скрипта

Для использования примера укажите идентификатор и пароль приложения.

# -*- coding: utf-8 -*-\nfrom flask import Flask, request, jsonify, redirect\nfrom requests import post\n\n# Метод для кодирования URL как в Python 3, так и в Python 2\nimport sys\n\nif sys.version_info < (3, 0): # Pytohn2.x\n from urllib import urlencode\nelse: # Python3.x\n from urllib.parse import urlencode\n\n# Идентификатор приложения\nclient_id = 'ИДЕНТИФИКАТОР_ПРИЛОЖЕНИЯ'\n# Пароль приложения\nclient_secret = 'ПАРОЛЬ_ПРИЛОЖЕНИЯ'\n# Адрес сервера Яндекс.OAuth\nbaseurl = 'https://oauth.yandex.ru/'\n\napp = Flask(__name__)\n\n\n@app.route('/')\ndef index():\n if request.args.get('code', False):\n # Если скрипт был вызван с указанием параметра "code" в URL,\n # то выполняется запрос на получение токена\n print(request.args)\n print(request.data)\n data = \n data = urlencode(data)\n # Токен необходимо сохранить для использования в запросах к API Директа\n return jsonify(post(baseurl + "token", data).json())\n else:\n # Если скрипт был вызван без указания параметра "code",\n # то пользователь перенаправляется на страницу запроса доступа\n return redirect(baseurl + "authorize?response_type=code&client_id=<>".format(client_id))\n\n\nif __name__ == '__main__':\n # Отладочная информация\n # app.debug = True\n # Запуск веб-сервера с доступом по порту 8000\n app.run(host='127.0.0.1', port=8000)

Источник

Оцените статью