Example: getting a token for a web service

This section demonstrates how applications get an authorization token.

Note. Recommendations for various types of applications (desktop, mobile, and so on) are given in the OAuth guide.

Callback URI

When registering or editing application parameters on the Yandex OAuth server, you must fill in the Callback URI field with the URL of the script that is receiving the token. For example:

 http://site.ru/get_token.php

The code of the script is provided below.

Procedure

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

  1. The application redirects the user using a link in the format
    https://oauth.yandex.com/authorize?response_type=code&client_id=<application_ID>

    On the page that opens, the user clicks Allow.

  2. The Yandex OAuth server performs a redirect to the address from Callback URI. In addition, the code parameter is appended to the address. For example:
     http://site.ru/get_token.php?code=<authorization_code>
  3. The script sends a POST request to https://oauth.yandex.com/token, passing the following parameters:
    • grant_type = authorization_code
    • code = <authorization code>
    • client_id = <application_ID>
    • client_secret = <application_password>
  4. The OAuth server sends a response in JSON format. The access_token key contains the OAuth token. For example:
    {"access_token": "ea135929105c4f29a0f5117d2960926f"}

    The received token must be saved and used in requests to the Yandex Direct API.

Script code

# -*- coding: utf-8 -*-
from bottle import route, run, request
import httplib
import urllib
import json

#Application ID
client_id = 'YOUR_CLIENT_ID'
#Application password
client_secret = 'YOUR_CLIENT_SECRET'

@route('/')
def index ():
 #If the script was called with the "code" parameter in the URL,
 #the request to get a token is executed
    if request.query.get('code'):
 #Forming the parameters (body) of the POST request with the confirmation code
        query = {
            'grant_type': 'authorization_code',
            'code': request.query.get('code'),
            'client_id': client_id,
            'client_secret': client_secret,
        }
        query = urllib.urlencode(query)

        #Forming headers for the POST request
        header = {
            'Content-Type': 'application/x-www-form-urlencoded'
        }

        #Executing the POST request and outputting results
        connection = httplib.HTTPSConnection('oauth.yandex.ru')
        connection.request('POST', '/token', query, header)
        response = connection.getresponse()
        result = response.read()
        connection.close()
        
        # Save the token to use in requests to the Yandex Direct API
        return json.loads(result)['access_token']


#Starting the web server
run(host='localhost', port=80, quiet=True)