No description, website, or topics provided.
Switch branches/tags
Nothing to show
Clone or download
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Failed to load latest commit information.
AzureAD.WebApi.SPOnline.ConsoleApp
AzureAD.WebApi.SPOnline.WebApi
.gitattributes
.gitignore
AzureAD.WebApi.SPOnline.sln
LICENSE
README.md

README.md

AzureAD-WebAPI-SPOnline

In this sample, a Windows console Application calls a Web API secured by Azure AD and the API calls SharePoint Online on behalf the logged in user. This scenario is useful for situations where you need a protected API proxy to interact with SharePoint Online using User's credentials. The application uses the Active Directory Authentication Library (ADAL) to get a token from Azure AD using the OAuth 2.0 client credential flow, where the client credential is a password.

For more information about how the protocols work in this scenario and other scenarios, see Authentication Scenarios for Azure AD.

If you just want to get an working demo, please go to this link.

Console Application

NuGet Packages

To create a solution from scratch, open Visual Studio and create a new Windows Console Application Solution.

Then click on Tools menu, NuGet Package Manager and in Package Manager Console item.

Install bellow packages:

  • Install-Package Microsoft.Net.Http
  • Install-Package Microsoft.IdentityModel.Clients.ActiveDirectory -Version 2.15.204151539

Install Nuget Packages

Web API

To create this project, Create a New ASP.NET Web Application and then choose Empty Template. We're going to create everything from the ground.

New Project

Choose Template

NuGet Packages

To create a solution from scratch, open Visual Studio and create a new Windows Console Application Solution.

Then click on Tools menu, NuGet Package Manager and in Package Manager Console item.

Install bellow packages:

  • Install-Package Microsoft.AspNet.WebApi
  • Install-Package Microsoft.AspNet.WebApi.Owin
  • Install-Package Microsoft.Owin.Host.SystemWeb
  • Install-Package Microsoft.Owin.Security.ActiveDirectory
  • Install-Package Microsoft.IdentityModel.Clients.ActiveDirectory -Version 2.15.204151539

Install Nuget Packages

Add Owin Startup Class

The first thing we need to do is to tell Owin Framework what class is responsible for the Owin initialization.

Add Owin Startup Class

Add the below annotation right before the class namespace.

[assembly: OwinStartup(typeof(AzureAD.WebApi.SPOnline.WebApi.Startup))]

Replace AzureAD.WebApi.SPOnline.WebApi for your own Startup namespace of the class

Owin Startup Class Code

Add this code:

using AzureAD.WebApi.SPOnline.WebApi.App_Start;
using Microsoft.Owin;
using Microsoft.Owin.Security.ActiveDirectory;
using Owin;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Http;

[assembly: OwinStartup(typeof(AzureAD.WebApi.SPOnline.WebApi.Startup))]
namespace AzureAD.WebApi.SPOnline.WebApi
{
    public partial class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            HttpConfiguration config = new HttpConfiguration();
            ConfigureAuth(app);
            WebApiConfig.Register(config);
            app.UseWebApi(config);
        }

        private void ConfigureAuth(IAppBuilder app)
        {
            app.UseWindowsAzureActiveDirectoryBearerAuthentication(
                new WindowsAzureActiveDirectoryBearerAuthenticationOptions
                {
                    Audience = ConfigurationManager.AppSettings["Audience"],
                    Tenant = ConfigurationManager.AppSettings["Tenant"]
                });
        }
    }
}

Add WebApiConfig Class

Create a new folder named App_Start and add a new class. The class name will be WebApiConfig.

Create class

Add the code below:

WebApiConfig code

using Newtonsoft.Json.Serialization;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http.Formatting;
using System.Web;
using System.Web.Http;

namespace AzureAD.WebApi.SPOnline.WebApi.App_Start
{
    public class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services
			 config.Routes.MapHttpRoute(
             name: "DefaultApi",
             routeTemplate: "api/{controller}/{id}",
             defaults: new { id = RouteParameter.Optional });

            // Web API routes
            config.MapHttpAttributeRoutes();

            var jsonFormatter = config.Formatters.OfType<JsonMediaTypeFormatter>().First();
            jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
        }
    }
}

Add SharePoint Client References

Right-click in References and select Add Reference...

Choose:

  • Microsoft.SharePoint.Client
  • Microsoft.SharePoint.Client.Runtime

References

Add a Controller to Handle Requests

Create a new folder named Controllers. Add a new Web API 2 Controller. Give it a name.

Create new Controller

The Test method goes on SharePoint Online using a new User's AccessToken and returns the site title.

The important thing here is to annotate your class with [Authorize]. With that annotation, your api will only accept authenticated request. Easy, isn't it?

using Microsoft.IdentityModel.Clients.ActiveDirectory;
using Microsoft.SharePoint.Client;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace AzureAD.WebApi.SPOnline.WebApi.Controllers
{
    [Authorize]
    public class TestController : ApiController
    {
        [HttpGet]
        public string Test()
        {
            string sharePointUrl = ConfigurationManager.AppSettings["SharePointURL"];
            string newToken = GetSharePointAccessToken(sharePointUrl, this.Request.Headers.Authorization.Parameter);

            using (ClientContext cli = new ClientContext(sharePointUrl))
            {

                /// Adding authorization header 
                cli.ExecutingWebRequest += (s, e) => e.WebRequestExecutor.WebRequest.Headers.Add("Authorization", "Bearer " + newToken);
            
                var web = cli.Web;
                cli.Load(web);
                cli.ExecuteQuery();
                return web.Title;
            }
        }

        internal static string GetSharePointAccessToken(string url, string accessToken)
        {
            string clientID = ConfigurationManager.AppSettings["ClientID"];
            string clientSecret = ConfigurationManager.AppSettings["ClientSecret"];

            var appCred = new ClientCredential(clientID, clientSecret);
            var authContext = new Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext("https://login.windows.net/common");

            AuthenticationResult authResult = authContext.AcquireToken(new Uri(url).GetLeftPart(UriPartial.Authority), appCred, new UserAssertion(accessToken));
            return authResult.AccessToken;
        }

     
    }
}

How to run this sample

To run this sample you will need:

  • Visual Studio 2013
  • An Internet connection
  • An Azure subscription (a free trial is sufficient)

Every Azure subscription has an associated Azure Active Directory tenant. If you don't already have an Azure subscription, you can get a free subscription by signing up at http://wwww.windowsazure.com. All of the Azure AD features used by this sample are available free of charge.

Step 1: Clone or download this repository

From your shell or command line:

git clone https://github.com/RARomano/AzureAD-WebAPI-SPOnline.git

Step 2: Register the Web API in Azure Active Directory

To create your applications in Azure, please follow instructions provided in this link: Create Azure AD Application.

There are a lot of links that explains the same steps. If you will use the link I've provided, follow the steps: 3, 4, 7, 8 and 9.

In addition to that, open your WebAPI project in Azure management portal and click on Configure link.

Click on Add Application and Choose Office 365 SharePoint Online and grant Have Full control of all site collections permission.

Step 3: Update references in the Windows Console Application and WEB API project

In the ConsoleApp project, update values in Program.cs file.

/// Azure AD WebApi's APP ID URL
string resource = "";

/// Azure AD WebApi's Client ID 
string clientId = "";

/// Azure AD User's credentials
string userName = "";
string userPassword = "";

/// Web API's URL
string apiUrl = "http://localhost:3672/api/Test";

In the WebApi Project, update the Web.Config file.

 <appSettings>
    <add key="Audience" value="APPURI" />
    <add key="Tenant" value="TenantGUID" />
    <add key="ClientID" value="ClientID" />
    <add key="ClientSecret" value="ClientSecret" />
    <add key="SharePointURL" value="https://[yourtenant].SharePoint.com" />
  </appSettings>