How to Authorize users to access GRAPH APIs with OAuth 2.0

In this tutorial, we will discuss, how to authorize users to access GRAPH APIs with OAuth 2.0. We will see the basic usage of the ADAL library and required user inputs, with a JavaScript example.

Authentication and Authorization steps

The basic steps required to use the OAuth 2.0 authorization code grant flow to get an access token from the Microsoft identity platform endpoint are:

  1. Register your app with Azure AD.
  2. Get authorization.
  3. Get an access token.
  4. Call Microsoft Graph with the access token.

1. Register your app

To use graph API in your application, you must register your application in the Azure app registration portal. You can use your work account to register but make sure you have admin permission to access the site.

Authorize user to access to GRAPH APIs with OAuth 2.0
  • Click Register.
  • Go to App registrations > View all applications and select the app. Copy the Application (client) ID.
How to Authorize user to access to GRAPH APIs with OAuth 2.0
  • Add AzureDatabricks to the Required permissions of the registered application. You must be an admin user to perform this step. If you encounter a “permission” problem performing this step, contact your administrator for help.
Authorize users to access GRAPH API with OAuth 2.0

2. Get authorization

The first step to getting an access token for many OpenID Connect (OIDC) and OAuth 2.0 flows is to redirect the user to the Microsoft identity platform/authorize endpoint.

Azure AD will sign the user in and ensure their consent for the permissions your app requests. In the authorization code grant flow, after consent is obtained, Azure AD will return an authorization_code to your app that it can redeem at the Microsoft identity platform /token endpoint for an access token.

3. Get an Access Token

We can follow the below code to generate the access token. Here I have simply used the Javascript library for all operations.

Step 1: Add the below reference in your code

<script type="text/javascript" src="https://alcdn.msauth.net/lib/1.4.14/js/msal.min.js"></script>

Step 2: Next use the below code and copy the client id which you have created in the Azure app. In loginHints section, you can use your email id or you can pass it as a parameter.

How to Authorize users to access GRAPH API with OAuth 2.0

In the next step, you have to generate the token based on the above configuration data.

Authorize users to access GRAPH API

The next step is to call the Graph API to get the data.

How to Authorize users to access GRAPH API

Please find the full code here.

var config = {
                auth: {
                    clientId: "60192db7-e8a4-4ca7-9e76-7aaa81d805cb
",
                    authority: "https://login.microsoftonline.com/common"
                },
                cache: {
                    cacheLocation: "sessionStorage"

                }
            };
            var graphConfig = {
                graphEndPoint: "https://graph.microsoft.com/v1.0/me"
            };
            var requestPermissionScope = {
                scopes: ["user.read"],
                loginHint: email // enter your email id here
            };
            var myMSALObj = new Msal.UserAgentApplication(config);
            myMSALObj.acquireTokenPopup(requestPermissionScope).then(function (result) {
                if (result != undefined) {
                    var headers = new Headers();
                    accessToken = "Bearer " + result.accessToken;
                    headers.append("Authorization", accessToken);
                    var options = {
                        method: "GET",
                        headers: headers
                    };

                    fetch(graphConfig.graphEndPoint, options)
                        .then(function (response) {
                            if (response.status == 200) {
                                var data = response.json();
                                data.then(function (userinfo) {
                                    var printResponse = JSON.stringify(userinfo)
                                    $.cookie("Name", userinfo.displayName);
                                    $.cookie("token", accessToken);
                                    window.location = "index.html";
                                })
                            }
                        });
                }
            })
            return false;
        }

Let me login to my account and we can see how the access token gets created by using the above code. When I click on the Login button, it will verify the details and it will create an access token.

Authorize users to access GRAPH APIs with OAuth 2.0

Once I click on the Login button, it’s redirecting to the office login page where you have to provide your password details.

How to Authorize users to access GRAPH APIs with OAuth 2.0

If you check the session storage, you can see the newly created token has been generated and stored in the browser.

Authorize users to access GRAPH APIs with OAuth 2.0

And I have also received my all user profile information through graph api.

Authorize users to access GRAPH APIs with OAuth 2.0

Note:

This feature is available in the PremiumStandardBasic, and Developer tiers of API Management.

For more information about using OAuth 2.0 and API Management, you can post your comment here.

In this tutorial, we learned, how to Authorize users to access GRAPH APIs with OAuth 2.0.

Related Posts:

>