Yahoo OAuth 2.0

Published 11/4/2015 02:33:04 PM  |  Last update 11/9/2015 09:16:02 AM
Tags: oauth, yahoo, api, php, c#

Yahoo! have asked third-party developers to switch to OAuth 2.0 authentication for account sign-in beginning May 30, 2015. OAuth 2.0 puts user security in Yahoo!'s hands and will let them tell the user what the app wants to do and what it wants to access.

Yahoo! said that the change will better protect their customers and provide a more consistent experience across their apps. It is also a win for developers, as it reduces the amount of work developers need to do to access Yahoo identity authentication tools. According to Yahoo!, their APIs currently support OAuth 2.0, and the sooner developers transition the better. People who use Yahoo OAuth sign-in to access third-party apps may notice a change to the log-in process after May 30.

Use of Yahoo OAuth 2.0 is straightforward and more simple than that of version 1.0. Developers first need to sign-up for Yahoo OAuth API Key and Secret. Integration of Yahoo OAuth sign-in into apps can be done in two steps using http request to Yahoo OAuth endpoint at https://api.login.yahoo.com/oauth2/, as follows.

  1. Request for OAuth access token Send a GET or POST request to “/request_auth" with the following parameters
    "client_id=" + API_KEY
    "redirect_uri=" + URL_of_your_page_to_get_oauth_key,
    "response_type=code
    
    Once the user authorizes access, Yahoo! Will redirect the user to the "redirect_uri" you originally specified, adding the query parameter "code" which contains an assigned OAauth key.
  2. Get OAuth access token The assigned OAauth key is used in a POST request to “/get_token” with the following parameters
    "redirect_uri=" URL…
    "code=" oauth-key
    "grant_type=authorization_code";
    
    Yahoo! response this request using JSON format, with the following information
    access_token: The Access Token, that is used to make Yahoo! API calls. It has a 1-hour lifetime.
    refresh_token: The Refresh Token, that is used to renew access token when expired.
    xoauth_yahoo_guid: The GUID of the Yahoo user, that is used to get user’s profile.
    

Yahoo OAuth2 using PHP

The following PHP function was developed to support HTTP requests to Yahoo OAuth endpoint according to Yahoo OAuth platform. Please note that the field "Authorization" is added to HTTP requests headers, which contains the application information, in the format defined by Yahoo!.

/* $method: is either POST or GET
$url: the request URL
$httpParams: the parameters to be sent along with http request, in query string format
[$Consumer_Key, $Consumer_Secret] are for your application key and secret */
function httpRequest($method, $url, $httpParms)
{
  global $Consumer_Key, $Consumer_Secret;
  $kq = null;
  if ($method == "POST") {
    $metadatasent = array("Authorization: Basic " . base64_encode("$Consumer_Key:$Consumer_Secret"));
    $kq = getRemoteFile2($url, $httpParms, false, $metadatasent);
  } else {
    $metadatasent = array("Authorization: $httpParms");
    $kq = getRemoteFile2($url, '', false, $metadatasent);
  }
  return $kq;
}

In the above function, we use "getRemoteFile2" to invoke an http request, which is implemented as follow:

/* $url: the request URL
$postparams: parameters to be sent, in query string format
$metadata: =TRUE if only HTTP headers are accquired
$metadatasent: the header parameters to be sent with http request, in PHP array format */
function getRemoteFile2($url, $postparams=FALSE, $metadata=FALSE, $metadatasent=FALSE) {
  $handle = curl_init();
  curl_setopt($handle,CURLOPT_FRESH_CONNECT, true);
  curl_setopt($handle,CURLOPT_CONNECTTIMEOUT, 5);
  curl_setopt($handle,CURLOPT_TIMEOUT, 1200);
  curl_setopt($handle,CURLOPT_SSL_VERIFYPEER, FALSE);
  curl_setopt($handle,CURLOPT_RETURNTRANSFER, TRUE);
  curl_setopt($handle,CURLOPT_URL, $url);
  curl_setopt($handle,CURLOPT_FOLLOWLOCATION, TRUE);
  curl_setopt($handle,CURLOPT_HEADER, $metadata);
  curl_setopt($handle,CURLOPT_NOBODY, $metadata);
  $metadataheader = array(
    ("User-Agent: " . ((isset($_SERVER['HTTP_USER_AGENT'])) ? $_SERVER['HTTP_USER_AGENT']:'Mozilla/5.0')),
    "Accept: */*",
    "Accept-Language: en-us,en;q=0.5",
    "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7"
  );
  if ($metadatasent) $metadataheader = array_merge($metadataheader,$metadatasent);
  curl_setopt($handle,CURLOPT_HTTPHEADER, $metadataheader);

  if ($postparams) {
    curl_setopt($handle,CURLOPT_POST, TRUE);
    curl_setopt($handle,CURLOPT_POSTFIELDS, $postparams);
  }
  $urlResponse = curl_exec($handle);
  $retcode = curl_getinfo($handle,CURLINFO_HTTP_CODE);
  curl_close($handle);
  if ($retcode != 200) return false;
  if ($metadata) {
    // get only the meta data
    $urlResponse = parseHttpHeader($urlResponse);
  }
  return $urlResponse;
}

To start a Yahoo! sign-in process using OAuth, please use the following script:

/* yahoo OAuth enpoint */
$urlOAuth = "https://api.login.yahoo.com/oauth2/";

$strRequest = $urlOAuth . 'request_auth' .
  '?client_id=' . $Consumer_Key .
  '&redirect_uri=' . urlencode($your_APP_post_back_url) .
  '&response_type=code';

If the user authorizes the sign-in process, your app at "your_APP_post_back_url" will receive a request with the query parameter "code" which contains the key to be used to get Yahoo access token. The following script shows how to in PHP.

/* yahoo OAuth enpoint */
$urlOAuth = "https://api.login.yahoo.com/oauth2/";
$mailkey = $_GET["code"]; // the key to get access token
$strRequest =
 'redirect_uri=' . urlencode($your_APP_post_back_url) .
 '&code=' . $mailkey . 
 '&grant_type=authorization_code';
$strResult = httpRequest("POST", $urlOAuth . "get_token", $strRequest);
$o = json_decode($strResult,true);
// access token, type (Bearer) and refresh_key
$userGUID = $o['xoauth_yahoo_guid'];
$userACCESS_TOKEN = $o['access_token'];
$userREFRESH_TOKEN = $o['refresh_token']; // is used for renewal of access token

To collect user’s profile information, just use the GUID in a request to "social.yahooapis.com".

// get user profile
$strResult = httpRequest("GET", "https://social.yahooapis.com/v1/user/" . $userGUID . '/profile?format=json', 'Bearer ' . $userACCESS_TOKEN);
$o = json_decode($strResult, true);
$aaccount = $o['profile']['nickname'];

Yahoo OAuth2 using Asp.Net

/* method={'POST','GET'}
url=request-URL
httpParms=string-query-format request parameters */
String httpRequest(String method, String url, String httpParms)
{   String kq = null; // this is "RESULT" for short, in Vietnamese
    if (method.Equals("POST"))
    {
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
        request.Method = "POST";
        request.ContentType = "application/x-www-form-urlencoded";
        byte[] headerByte = System.Text.Encoding.UTF8.GetBytes(Consumer_Key + ":" + Consumer_Secret);
        string headerString = System.Convert.ToBase64String(headerByte);
        request.Headers["Authorization"] = "Basic " + headerString;
        byte[] byteData = UTF8Encoding.UTF8.GetBytes(httpParms);
        request.ContentLength = byteData.Length;
        // Write data
        using (Stream postStream = request.GetRequestStream())
        {
            postStream.Write(byteData, 0, byteData.Length);
        }
        // Get response  
        try
        {
            using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
            {
                // Get the response stream  
                StreamReader reader = new StreamReader(response.GetResponseStream());
                kq = reader.ReadToEnd();
            }
        }
        catch { kq = null; }
    }
    else
    {
        try
        {
            using (WebClient wc = new WebClient())
            {
                wc.Headers.Add("Authorization", httpParms);
                kq = wc.DownloadString(url);
            }
        }
        catch { kq = null; }
    }
    return kq;
}

To start a Yahoo! sign-in request using OAuth, please use the following script:

string ymailaut = "https://api.login.yahoo.com/oauth2/";
string yourPBurl = "your_APP_post_back_url";
strRequest = ymailaut + "request_auth" +
    "?client_id=" + APP_KEY +
    "&redirect_uri=" + Server.UrlEncode(yourPBurl) +
    "&response_type=code";
// Get User Auth code, yahoo will send back 'code' on user's acceptance
Response.Redirect(strRequest);

If the user authorizes the sign-in request, your app at "your_APP_post_back_url" will receive a request with the query parameter "code" which contains the key to be used to get Yahoo access token. The following script shows how to in C#.

string key_code = Request.QueryString["code"].ToString();
strRequest =
    "redirect_uri=" + Server.UrlEncode(yourPBurl ) +
    "&code=" + key_code + 
    "&grant_type=authorization_code";
// get access token
strResult = httpRequest("POST", ymailaut + "get_token", strRequest);
// the result is in JSON format, I used "Newtonsoft.Json" to parse the result
var o = JObject.Parse(strResult);
// access token, type (Bearer) and refresh_key
String GUID = (String)o["xoauth_yahoo_guid"];
String access_token =  (String)o["access_token"];
// the following value will be used when the token in "access_token" expires 
String refresh_token = (String)o["refresh_token"];

To collect user's profile information, just use the GUID in a request to "social.yahooapis.com".

// get user profile
strResult = httpRequest("GET", "https://social.yahooapis.com/v1/user/" + GUID + "/profile?format=json", "Bearer " + access_token);
o = JObject.Parse(strResult);
String nickname = (String)o["profile"]["nickname"];

Please note that all Yahoo OAuth http requests need the HTTP header field "Authorization" that is set to "Basic xxx" where xxx = base64_encode(API_Key + ":" + API_Secret). Please refer this article for how to Yahoo OAuth programming using C#. Thanks,

© 2024 blog.tinyray.com  by tinyray