DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • SelfService HR Dashboards with Workday Extend and APIs
  • How We Reduced LCP by 75% in a Production React App
  • Shipping GenAI Into an Existing App: How to Integrate AI Features Without Rewriting Your Stack
  • Modernizing Applications with the 7 Rs Strategy – A CTO's Guide

Trending

  • MuleSoft MCP and A2A in Production: What 17 Recipes Reveal
  • Using LLMs to Automate Data Cleaning and Transformation Pipelines
  • The Serverless Illusion: When “Pay for What You Use” Becomes Expensive
  • Monitoring Spring Boot Applications with Prometheus and Grafana
  1. DZone
  2. Coding
  3. Languages
  4. Creating a Microsoft Login Button Using PHP

Creating a Microsoft Login Button Using PHP

By 
Zachary Bedell user avatar
Zachary Bedell
·
Nov. 17, 14 · Interview
Likes (5)
Comment
Save
Tweet
Share
10.1K Views

Join the DZone community and get the full member experience.

Join For Free

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 echo file_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.

PHP app

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

Opinions expressed by DZone contributors are their own.

Related

  • SelfService HR Dashboards with Workday Extend and APIs
  • How We Reduced LCP by 75% in a Production React App
  • Shipping GenAI Into an Existing App: How to Integrate AI Features Without Rewriting Your Stack
  • Modernizing Applications with the 7 Rs Strategy – A CTO's Guide

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook