Monday, May 4, 2020

SharePoint with ADAL and the Microsoft Graph API

SharePoint with ADAL and the Microsoft Graph API

References: 
1. Register App in Azure Active Directory
2. Write code and deploy into Site Assets/Document library
3. Add Content Editor WebPart in Page and give script reference in edit WebPart mode. Check for result.

1. Register App in Azure Active Directory
go to https://portal.azure.com/

Click on new app registration

provide App name, App redirect URI.

go to overview -> Copy ClientID, TenantID.

go to 'API Permission' -> click on 'Grant admin consent for sreekanth09'

go to Manifest -> 
"oauth2AllowIdTokenImplicitFlow"true,
"oauth2AllowImplicitFlow"true,
"url""https://sreekanth09.sharepoint.com/*" (make sure add * after slash)

2. Write code and deploy into Site Assets/Document library

write below script in notepad and save as "MSGraph.html" and upload into site assets library in SharePoint.

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://secure.aadcdn.microsoftonline-p.com/lib/1.0.13/js/adal.min.js"></script>
<div>
    <div id="displayName"></div>
    <div id="mail"></div>
    <img id="img1">
</div>
<script type="text/javascript">
    "use strict";
    var tenant = 'cbb49af7-232c-4bb5-xxxx-xxxxxxxxxxxx';
    var clientId = '1e06ea44-7e76-459f-b21d-ca0781c6d608';
    var config = {
        tenant: tenant,
        clientId: clientId,
        endpoints: {
            graphUri: 'https://graph.microsoft.com'
        },
        cacheLocation: "localStorage"
    };
    var authContext = new AuthenticationContext(config);
    function getAuthToken(endpoint) {
        var d = jQuery.Deferred();
        var tokenCache = authContext.getCachedToken(endpoint);
        if (tokenCache == undefined) {
            authContext.acquireToken(endpointfunction (errortoken) {
                if (error || !token) {
                    d.reject(error);
                }
                else {
                    d.resolve(token);
                }
            });
        } else {
            d.resolve(tokenCache);
        }
        return d.promise();
    };

    function getGraphPhoto() {
        var tokenPromise = getAuthToken(config.endpoints.graphUri);
        tokenPromise.then(function (token) {
            if (token != undefined) {
                var meUri = "https://graph.microsoft.com/v1.0/me";
                $.ajax
                    ({
                        type: "GET",
                        url: meUri,
                        headers: {
                            "Authorization": "Bearer " + token
                        }
                    }).done(function (response) {
                        $("#displayName").text(response.displayName);
                        $("#mail").text(response.mail);
                    }).fail(function (response) {
                        $("#message").text("Failed to get the data. " + response);
                    });
                var meUri = "https://graph.microsoft.com/v1.0/me/photo/$value";
                var request = new XMLHttpRequest();
                request.open("GET"meUri);
                request.setRequestHeader("Authorization""Bearer " + token);
                request.responseType = "blob";
                request.onreadystatechange = function () {
                    if (request.readyState === 4 && request.status === 200) {
                        var url = window.URL || window.webkitURL;
                        var blobUrl = url.createObjectURL(request.response);
                        $('#img1').attr("src"blobUrl)
                    }
                };
                request.send();
            }
        }, function (error) {
            console.log(JSON.stringify(error));
        });
    };

    $(document).ready(function () {
        var isCallback = authContext.isCallback(window.location.hash);
        if (isCallback && !authContext.getLoginError()) {
            authContext.handleWindowCallback(window.location.hash);
        } else {
            var user = authContext.getCachedUser();
            if (!user) {
                authContext.login();
            } else {
                getGraphPhoto();
            }
        }
    });
</script>
<html>

<head>
    <title></title>
</head>


3. Add Content Editor WebPart in Page and give script reference in edit WebPart mode. Check for result.

let's check,

if are not given 'Grant admin consent for sreekanth09' then below popup window will come then click on 'Accept'.


5 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. From my experience, madalin stunt cars delivers endless fun through exciting races, thrilling stunts, and realistic driving mechanics. The colorful environments, responsive gameplay, and impressive vehicle selection make every session enjoyable from beginning to end.

    ReplyDelete
  3. Every single visit to small world cup brings exciting football action and entertaining gameplay. The polished interface, smooth mechanics, and creative match design make this website an excellent destination for casual sports gaming fans.

    ReplyDelete
  4. Surprisingly impressive is the little alchemy website because it delivers imaginative crafting challenges with engaging gameplay. The smooth mechanics, attractive graphics, and creative combinations provide endless entertainment for players seeking thoughtful puzzle adventures.

    ReplyDelete

Featured Post

test

  SET QRImagePath TO $'''C:\\Users\\usree\\Downloads\\patient_qr.png''' Scripting.RunPowershellScript.RunScript Scri...

Popular posts