Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Creating a Microsoft Login Button Using PHP

DZone's Guide to

Creating a Microsoft Login Button Using PHP

· Web Dev Zone
Free Resource

Tips, tricks and tools for creating your own data-driven app, brought to you in partnership with Qlik.

In this tutorial I will show you how to create a Microsoft login button for your website using PHP. To start with, let’s answer the question: What is OAuth? OAuth is a protocol used to allow secure authorization to websites and applications to access user information on other websites. There are two versions of OAuth, 1.0 and 2.0. In this post we will use OAuth 2.0 to build a Microsoft login system.


What is Microsoft Log-In?

Microsoft Log-in means asking user to grant access to his/her Microsoft live information like email id, username etc. Once your website has been granted access and has all these information about the user it can allow the users to access protected pages on your website.


Setting up Directory and Files

Before we get started you need to create a PHP file named redirect.php. Place this file anywhere in your webspace.


Creating a Microsoft App

If your website is allowing login using Microsoft then your website is considered as an Microsoft app. So you have your website ready now its time to register you website as a Microsoft app. Follow this steps to create a Microsoft app:

  1. Visit Microsoft apps page.
  2. Now create a Microsoft app
  3. Select API Settings and for redirect URL pass URL pointing to the redirect.php file.
  4. You can find the Client ID and Client Secret under App Settings

Creating Login with Microsoft Button

When user clicks on Login button you need to run this code to redirect user to Microsoft Live website so that user can grant permission to your app to access their information

$client_id = "";
2	$redirect_uri = "";
3	$scopes = "wl.basic,wl.offline_access,wl.signin,wl.emails";
4	 
5	header("Location: " . "https://login.live.com/oauth20_authorize.srf?client_id=" . $client_id . "&scope=" . $scopes . "&response_type=token&redirect_uri=" . $redirect_uri);

Scopes represent the list of permissions for the app. You need to pass a comma separated list of permissions. List of all scopes.

Populate the $client_id and $redirect_uri variables.


Redirecting back to the App

Once user has given access to the app, Microsoft will redirect user back to the redirect URI. Now you need to retrieve an access token which acts like a permission to get user information.

In the redirect.php file you can retrieve access token by running this code

<?php

  $client_id = "";
  $client_secret = "";
  $redirect_uri = "";

  //$_GET["code"] is the authorization code
  if(isset($_GET["code"]))
  {
    //user granted permission

    //get access token using the authorization code

    $url = "https://login.live.com/oauth20_token.srf";
        $fields = array("client_id" => $client_id, "redirect_uri" => $redirect_uri, "client_secret" => $client_secret, "code" => $_GET["code"], "grant_type" => "authorization_code");

        foreach($fields as $key=>$value) { $fields_string .= $key."=".$value."&"; }
        rtrim($fields_string, "&");

        $ch = curl_init();

        curl_setopt($ch,CURLOPT_URL, $url);
        curl_setopt($ch,CURLOPT_HTTPHEADER, array("Content-Type: application/x-www-form-urlencoded"));
        curl_setopt($ch,CURLOPT_POST, count($fields));
        curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);

        $result = curl_exec($ch);
        $result = json_decode($result);

        curl_close($ch);

    //this is the refresh token used to access Microsoft Live REST APIs
        $access_token = $result->access_token;
        $refresh_token = $result->refresh_token;
  }
  else
  {
    echo "An error occured";
  }

?>

Populate variable $client_id,$client_secret and $redirect_uri.

Finally we got $access_token and $refresh_token. $access_token usually expires in 1 hour therefore $refresh_token is used to get a new access token after every 1 hour.

If access token is expired then you are likely to get an error in HTTP response content while making requests to REST APIs.

You can retrieve new access token using this function

function new_access_token($refresh_token)
{
    $url = "https://login.live.com/oauth20_token.srf";
    $fields = array("client_id" => $client_id, "redirect_uri" => $redirect_uri, "client_secret" => $client_secret, "grant_type" => "refresh_token", "refresh_token" => $refresh_token);

    foreach($fields as $key=>$value) { $fields_string .= $key."=".$value."&"; }
    rtrim($fields_string, "&");

    $ch = curl_init();

    curl_setopt($ch,CURLOPT_URL, $url);
    curl_setopt($ch,CURLOPT_HTTPHEADER, array("Content-Type: application/x-www-form-urlencoded"));
    curl_setopt($ch,CURLOPT_POST, count($fields));
    curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);
    curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);

    $result = curl_exec($ch);
    $result = json_decode($result);

    curl_close($ch);

    $access_token = $result->access_token;

    return $access_token;
}

Making calls to REST API

You can find list of all REST APIs at Microsoft REST API reference. All the requests to these APIs must be made using the access token.

To retrieve user profile information you need to make a GET request of such kind

1 echofile_get_contents("https://apis.live.net/v5.0/me?access_token=". $access_token);

Integrating Microsoft Login in WordPress

WordPress is made on PHP therefore all code will be same for authorizing user and getting profile information. To create a redirect URL in WordPress use WordPress AJAX API.


Final Thoughts

If you want to more than just Login then increase the permissions in permission list and store the access token and refresh token in database for further use. Make sure you update the access token when its refreshed. Don’t share the client secret with anyone.

Explore data-driven apps with less coding and query writing, brought to you in partnership with Qlik.

Topics:

Published at DZone with permission of Zachary Bedell. See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}