Skip to content
This repository has been archived by the owner on Aug 24, 2021. It is now read-only.

Dev #1841

Closed
wants to merge 2 commits into from
Closed

Dev #1841

Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
69 changes: 69 additions & 0 deletions Samples/MicrosoftGraph.SPOConsumer/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
# Microsoft Graph - SharePoint Online Consumer #

### Summary ###
This is simplistic ASP.net MVC application to consume SharePoint Online using the Microsoft Graph.

### Applies to ###
- Office 365
- SharePoint Online

### Prerequisites ###
App configuration in the Azure AD

### Solution ###
Solution | Author(s)
---------|----------
SPOGraphConsumer | Paolo Pialorsi (PiaSys.com - @PaoloPia)

### Version history ###
Version | Date | Comments
---------| -----| --------
1.0 | March 2018 | Initial release

### Disclaimer ###
**THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.**

----------

# Introduction #
This sample is demonstrating simplistic solution to consume SharePoint Online sites and lists using the *sites* endpoint of Microsoft Graph.

![App UI](./assets/SPOGraphConsumerApp.png)

# Azure Active Directory Setup #
Before this sample can be executed, you will need to register application to Azure AD and provide needed permissions for the Graph queries to work. We will create an application entry in Azure Active Directory and configure the needed permissions.

- Open the [Azure Portal](https://portal.azure.com) and move to Azure Active Directory admin UI
- Move to **App Registrations** section
- Click **New application registration** to start the creation of a new app
- Configure a name for your app, select "Web app/API" for the *Application type*, and provide the URL of your app as it is declared in Visual Studio (for example: https://localhost:44346/)
- Click the *Create* button

![The app registration page in Azure AD](./assets/AppRegistration-01.png)

- Now click on *Settings*, select *Required Permissions*
- Click *Add* and select the *Microsoft Graph* API
- Choose the *Delegated* permission for *"Have full control of all site collections"*
- Click *Select* and *Done*

![The permissions configured for the app in Azure AD](./assets/AppRegistration-02.png)

- Now click on "Keys" and create a new key providing a unique name, a duration for the key (shorter duration is safer)
- Click on *Save* and copy the generated key in a safe place

![The keys configured for the app in Azure AD](./assets/AppRegistration-03.png)

You have now completed the the needed configuration at the Azure Active Directory part. Notice that you will need to still configure client id, client secret, and tenant settings in the web.config file of the project.

![Configuration of web.config](./assets/SPOGraphConsumerApp-Config.png)

# Run the solution #
Whenever you have configured the Azure AD side and updated the web.config based on your environmental values, you can run the sample properly.

- Press F5 in the Visual Studio
- Login with your Office 365 account
- Press *Manage Sites* to query a target site

You can find further details about this sample application in the following video: [SharePoint PnP Webcast – Consuming SharePoint Online via the Microsoft Graph](https://developer.microsoft.com/en-us/office/blogs/consuming-sharepoint-online-via-the-microsoft-graph/)

<img src="https://telemetry.sharepointpnp.com/pnp/samples/MicrosoftGraph.SPOConsumer" />
25 changes: 25 additions & 0 deletions Samples/MicrosoftGraph.SPOConsumer/SPOGraphConsumer.sln
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.27130.2020
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SPOGraphConsumer", "SPOGraphConsumer\SPOGraphConsumer.csproj", "{E07F59F6-EC3A-4E81-8692-985CB690CEC3}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{E07F59F6-EC3A-4E81-8692-985CB690CEC3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{E07F59F6-EC3A-4E81-8692-985CB690CEC3}.Debug|Any CPU.Build.0 = Debug|Any CPU
{E07F59F6-EC3A-4E81-8692-985CB690CEC3}.Release|Any CPU.ActiveCfg = Release|Any CPU
{E07F59F6-EC3A-4E81-8692-985CB690CEC3}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {96228666-23C2-482C-A445-3B361032A400}
EndGlobalSection
EndGlobal
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
using System.Web;
using System.Web.Optimization;

namespace SPOGraphConsumer
{
public class BundleConfig
{
// For more information on bundling, visit https://go.microsoft.com/fwlink/?LinkId=301862
public static void RegisterBundles(BundleCollection bundles)
{
bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
"~/Scripts/jquery-{version}.js"));

bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
"~/Scripts/jquery.validate*"));

// Use the development version of Modernizr to develop with and learn from. Then, when you're
// ready for production, use the build tool at https://modernizr.com to pick only the tests you need.
bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
"~/Scripts/modernizr-*"));

bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
"~/Scripts/bootstrap.js",
"~/Scripts/respond.js"));

bundles.Add(new StyleBundle("~/Content/css").Include(
"~/Content/bootstrap.css",
"~/Content/site.css"));
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
using System.Web;
using System.Web.Mvc;

namespace SPOGraphConsumer
{
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

namespace SPOGraphConsumer
{
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Globalization;
using System.Linq;
using System.Web;
using Owin;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.Cookies;
using Microsoft.Owin.Security.OpenIdConnect;
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using System.IdentityModel.Claims;
using SPOGraphConsumer.Components;
using System.Threading.Tasks;

namespace SPOGraphConsumer
{
public partial class Startup
{
public void ConfigureAuth(IAppBuilder app)
{
app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

app.UseCookieAuthentication(new CookieAuthenticationOptions());

app.UseOpenIdConnectAuthentication(
new OpenIdConnectAuthenticationOptions
{
ClientId = GraphSettings.ClientId,
Authority = GraphSettings.Authority,
TokenValidationParameters = new System.IdentityModel.Tokens.TokenValidationParameters
{
// instead of using the default validation (validating against a single issuer value, as we do in line of business apps),
// we inject our own multitenant validation logic
ValidateIssuer = false,
},
Notifications = new OpenIdConnectAuthenticationNotifications()
{
SecurityTokenValidated = (context) =>
{
return Task.FromResult(0);
},
AuthorizationCodeReceived = (context) =>
{
var code = context.Code;

ClientCredential credential = new ClientCredential(
GraphSettings.ClientId,
GraphSettings.ClientSecret);
string signedInUserID = context.AuthenticationTicket.Identity.FindFirst(
ClaimTypes.NameIdentifier).Value;
string tenantId = context.AuthenticationTicket.Identity.FindFirst(
"http://schemas.microsoft.com/identity/claims/tenantid").Value;

AuthenticationContext authContext = new AuthenticationContext(
GraphSettings.AadInstance + GraphSettings.TenantId,
new MemoryADALCache(signedInUserID));
AuthenticationResult result = authContext.AcquireTokenByAuthorizationCode(
code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)),
credential, GraphSettings.GraphResourceId);

return Task.FromResult(0);
},
AuthenticationFailed = (context) =>
{
context.OwinContext.Response.Redirect("/Home/Error?message=" + context.Exception.Message);
context.HandleResponse(); // Suppress the exception
return Task.FromResult(0);
}
},
PostLogoutRedirectUri = GraphSettings.PostLogoutRedirectUri
});
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
<?xml version="1.0" encoding="utf-8"?>
<ApplicationInsights xmlns="http://schemas.microsoft.com/ApplicationInsights/2013/Settings">
</ApplicationInsights>
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;

namespace SPOGraphConsumer.Components
{
public static class GraphSettings
{
private static string clientId = ConfigurationManager.AppSettings["ida:ClientId"];
private static string clientSecret = ConfigurationManager.AppSettings["ida:ClientSecret"];
private static string aadInstance = ConfigurationManager.AppSettings["ida:AADInstance"];
private static string tenantId = ConfigurationManager.AppSettings["ida:TenantId"];
private static string postLogoutRedirectUri = ConfigurationManager.AppSettings["ida:PostLogoutRedirectUri"];
private static string spoTenant = ConfigurationManager.AppSettings["ida:SpoTenant"];
private static string authority = aadInstance + tenantId;

public static String GraphResourceId = "https://graph.microsoft.com/";
public static String MicrosoftGraphV1BaseUri = "https://graph.microsoft.com/v1.0/";
public static String MicrosoftGraphBetaBaseUri = "https://graph.microsoft.com/beta/";

public static String ClientId
{
get
{
return (clientId);
}
}

public static String ClientSecret
{
get
{
return (clientSecret);
}
}

public static String AadInstance
{
get
{
return (aadInstance);
}
}

public static String TenantId
{
get
{
return (tenantId);
}
}

public static String SpoTenant
{
get
{
return (spoTenant);
}
}

public static String PostLogoutRedirectUri
{
get
{
return (postLogoutRedirectUri);
}
}

public static String Authority
{
get
{
return (authority);
}
}
}
}
Loading