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'.


No comments:

Post a Comment

Featured Post

Mention a Channel or Team – Power Automate

Mention a Channel or Team – Power Automate graph.microsoft.com/v1.0/teams/{teamId}/channels/{channelId}/messages Channel: ---------- {   ...

Popular posts