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

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Building a Simple Todo App With Model Context Protocol (MCP)
  • Mastering React App Configuration With Webpack
  • Inheritance in PHP: A Simple Guide With Examples
  • How to Build a React Native Chat App for Android

Trending

  • How to Submit a Post to DZone
  • DZone's Article Submission Guidelines
  • How Large Tech Companies Architect Resilient Systems for Millions of Users
  • Medallion Architecture: Why You Need It and How To Implement It With ClickHouse
  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 (2)
Comment
Save
Tweet
Share
9.4K 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

  • Building a Simple Todo App With Model Context Protocol (MCP)
  • Mastering React App Configuration With Webpack
  • Inheritance in PHP: A Simple Guide With Examples
  • How to Build a React Native Chat App for Android

Partner Resources

×

Comments

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

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

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 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: