Radi Atanassov

SharePoint MCM, MVP, MCT and owner of OneBit Software

A sample ASP.NET Core starter solution with Identity, Entity Framework 6 and a Repository Pattern Implementation

This sample solution makes use of ASP.NET Core with ASP.NET Identity over Entity Framework Core running side-by-side with Entity Framework 6. Look at this if you don't want Entity Framework Core for your data layer, but still want to use ASP.NET Identity in ASP.NET Core and benefit from its out-of-the-box implementation (which is awesome!).

Goals and inspiration

I was inspired by Mosh Hamedani's work on "Repository Pattern with C# and Entity Framework, Done Right". I think the theory that Mosh has put forward on the difference between a repository pattern and EF's DbContext is well structured and well explained. The sample code is also worth checking out.

I wanted to take it one step forward and put the pattern into an ASP.NET Core starter solution. The key point I want to demonstrate is using critical components of an ASP.NET Core MVC web application with an implementation of the repository that works side-by-side with the ASP.NET Identity 3 implementation. I wanted to make the repository asynchronous as well, because there's not many good examples out there.

The catch: ASP.NET Identity 3 uses ASP.NET Core and Entity Framework Core. That's all great, but many are not ready for EFCore and want the battle-tested Entity Framework 6. EF6 is feature packed, while EFCore is still very feature-limited.

In summary, this sample answers these questions:

  • How do you inject an EF6 context with a connection string in the ASP.NET Core service collection?
  • How do you run ASP.NET Identity on EFCore and the rest of the application on EF6?
  • How do you properly implement the Repository pattern with EF6?
  • How do you make your Repository async?
  • How do you maintain one database for both your custom entities and ASP.NET Identity?
  • How and where do you implement a Services layer?
  • How do you make your Controller methods Async?
  • How do you use Services with Controllers?
  • How do you keep the connection string in one place.

GitHub Repository: https://github.com/OneBitSoftware/AspNetCore.Ef6.Identity3.StarterSolution

The Data class library

I've taken all data access classes in relation to EF6 and the Repository pattern in a separate class library. This library doesn't do anything else apart from the responsibility of data access. Technically you can split it into more assemblies if your case makes sense.

There's no need for me to describe the Repository implementation itself, because Mosh has done it very well. Follow his video or code sample for background knowlede. I am focusing on using it in an ASP.NET Core MVC application.

This is what my *.Data project looks like:

Asynchronous Repository

Many operations against Entity Framework 6 make sense to be asynchronous. You get the true benefit if the async chain goes all the way up to the controller. That is why my repository interface returns Task<T>.

public interface IRepository<TEntity> where TEntity: class

{

Task<TEntity> GetAsync(int id);

Task<IEnumerable<TEntity>> GetAllAsync();

Task<IEnumerable<TEntity>> FindAsync(Expression<Func<TEntity, bool>> match);

Task<TEntity> AddAsync(TEntity entity);

Task RemoveAsync(TEntity entity);

Task RemoveRangeAsync(IEnumerable<TEntity> entity);

}

The Web project

All of my other bits and pieces I have stuck in the MVC project. I have strictly kept to the empty ASP.NET Core MVP project structure - my Services and View models are here. I have not touched the ApplicationDbContext ASP.NET Identity DbContext class to allow for a quick start.

If you choose, you can break this project into more class libraries. In this sample I keep my MVC(S) Services where my ViewModels are, so Services return ViewModels, which also means that they encapsulate the Factory calls to map Models to ViewModels. If you wish, you can move that responsibility to the Controllers and have your Services return Models (and essentially move Services to their own library).

The Visual Studio tooling and specifically the MVC scaffolding is unfortunately designed (as of now) to have everything in one project, that is when you get good scaffolding possibilities.

Here is what my *.Web project looks like:

Common database for entities and ASP.NET Identity tables

Nobody wants to deal with more than one database unless it is really necessary. In our case we want a web application with objects and user accounts - not a hugely complex thing. A single database would be appropriate for many scenarios.

The sample does just that - both contexts (ApplicationDbContext and my custom entity context) access the same database. They use the same connection string during registration in the ConfigureServices startup method.

services.AddDbContext<ApplicationDbContext>(options =>

options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

services.AddScoped<CarApplicationDbContext>(_ =>

new CarApplicationDbContext(Configuration.GetConnectionString("DefaultConnection")));

Here is what the database looks like. EF5 uses the migration history tables to deal with migrations as it should, the ContextKey column here is key.

Target Framework

Entity Framework 6 is dependent on the full .NET Framework. This is why the solution targets .NET Framework (4.5.2) but uses the ASP.NET Core framework and libraries to run the application.

Code on GitHub

Feel free to use as you please. I'd be glad to get your feedback and comments.

GitHub Repository: https://github.com/OneBitSoftware/AspNetCore.Ef6.Identity3.StarterSolution

A Rational Guide to Dealing with Azure's "MySQL in App" App Service Capability and PHP Web Applications - Part 2

This is a multi-part series with tips and solutions to roadblocks that I faced in dealing with the "MySQL in App" service.

Part 2 - Migrating a really large MySQL database to Azure's "MySQL in App"

You can use the phpMyAdmin interface to do most operations on your database, but it has never been good with importing/exporting databases over 8MB, and these days 8MB is not that big. 

I had to operate on a 3GB database and using phpMyAdmin to restore it was no option at all.

Export your database from your source with the "mysqldump.exe" command:

mysqldump -u [user_name]-pdbpassword [database_name] --routines > 20170416_dbbackup_full.sql

(notice the -pPASSWORD syntax, a bit weird but there is no space there).

NOTE: if your .sql file is "huge" see spliting a .sql file on Windows below. "Huge" means the import times out given the size of the App Service resources that you have provided.

Soon we will use the Kudu console, but first access the FTP service that is enabled on your Azure App Service. Get the FTP hostname and credentials from the Overview screen, and upload your large database.

FTP your large database to the D:\home folder:

Once your file is there, you can manipulate it with mysql.exe.

The key thing to gather is the path and port of your MySQL instance (phpMyAdmin could tell you both. The username and passwords you need to know are the "root" and "azure" accounts, both with passwords "password". You also need to specify the --bind-address parameter to localhost.

Pretty much your command looks like this:

D:\home\sql_restore>"D:\Program Files (x86)\mysql\5.7.9.0\bin\mysql.exe" --user=root --password=password --port=56172 --bind-address=127.0.0.1 mydbname-test-01 < 20170401_dbbackup_mini.sql

This is enough for you to restore a large database, but there is one big problem with this approach. The Kudu console will timeout (I think after 30 or 60 minutes) and kill the process that is hosting it. BAD. Basically it looks like this:

Eventually you might get a timeout of the console before the operation completes, terminating it half-way.

See my next post for a solution to the above problem: Part 3 - Splitting a really large MySQL database dump/export file into smaller pieces

A Rational Guide to Dealing with Azure's "MySQL in App" App Service Capability and PHP Web Applications - Part 1

If you haven't heard, Azure's App Service PaaS offering comes with a build in MySQL instance. See these blog posts for welcoming info:

This is great because you can move any PHP solution (like Wordpress) that uses MySQL to an Azure App Service instance. You could even use the free tier and host your blog or anything else at your likings.

Working with PHP and MySQL in Azure has its intricacies and definitely doesn't have a lot of information.

This is a multi-part series with tips and solutions to roadblocks that I faced in dealing with the "MySQL in App" service.

I was tasked with moving a pretty big PHP solution with a big database to Azure.

Here are some key bits of information that I were either not documented or I had a hard time figuring out.

Part 1 - Overview and different interfaces to manage PHP

Azure's portal doesn't have much, but it has a few crucial buttons worth knowing about. I will first explain the Kudu console, because it is a predecessor to tweaking PHP settings.

Kudu Console, aka Advanced Tools

You might be familiar with the Kudu project, a cool set of tools to manage your Azure App Instance. This is key to working with PHP and MySQL.

Access it through the App Service interface in portal.azure.com.

The Kudu UI is simple enough and has tons of useful information:

To access the console, go to the Debug console menu and click CMD or PowerShell, depending on what you need.

This gives you a neat console into the VM behind the App Service (yes, they are VM's!).

Everything under C:\ is blocked, but you can do all you wish under D:\

PHP Settings

An Azure App Service has PHP installed by default, and it has various versions available too. These are changeable in the Application Settings screen on the App Service:

The actual php.ini file is located in "D:\local\Config\PHP-5.5.38\php.ini" (or as per the version you are using). You can edit that, however it is a much better recommendation to do it the "right way" and create a ".user.ini" file. To do this, add a custom php.ini override file with the configurations you need, place it in your application root and deploy your application. Restart it so you force PHP to re-read its configuration.

Alternatively, you can place a ".ini" file on the D: drive, such as d:\home\site\ini, then add the 'PHP_INI_SCAN_DIR' configuration settings key in "App settings":

Both will work. This is documented much better here: Configure PHP in Azure App Service Web Apps

Managing the MySQL service

You can manage the MySQL service through the Azure portal UI (very limited) or through the well-known phpMyAdmin interface. The Azure App Service comes with phpMyAdmin installed. Reach it through the difficult to see "MySQL in App" option and the "Manage" portal button/link, or through the following URL: https://[appserviceaddress].scm.azurewebsites.net/phpMyAdmin/ mine was https://blog-prod-01.scm.azurewebsites.net/phpMyAdmin/

You will be automatically logged in with an "azure" account.

And the not-so-visible Manage button:

You will reach the phpMyAdmin interface:

This is enough to get you going with basic PHP and MySQL management. My next post describes how to import large MySQL databases: Part 2 - Migrating a really large MySQL database to Azure's "MySQL in App"

Jerky mouse movement with a laser Logitech mouse

This is one of those off-topic blog posts that I eventually write, but I spent significant time trying to figure out why my Logitech G700s mouse doesn't move in a straight line and I think it would be worth it.

I couldn't find solutions for this on the web. My problem is simple - I move the mouse and it doesn't go smooth in a straight line. It jumps sporadically across the movement vector at about 0.5-1cm off its course, making it impossible to use for games or anything for that matter. I can't really demonstrate it easily, but it was bad.

I got initially put off in the wrong direction - drivers. I did all kinds of installs and uninstalls, both native windows and Logitec. I played with the pointer speed settings both in Windows devices and in the Logitech mouse drive software. None solved my problem.

I even tried different mouse pads.

The issue at hand is that it is just dirty - the laser heads have very tiny dust particles that are very difficult to see. I tried blowing them off, but I'm not a good blower.

My fix is easy - I stuck an almost dried out wet wipe tissue into the laser hole and rotated it a few times. The laser heads we're visibly cleaner.

Now it works like brand new. This is one of the most smoothest mice I have owned and it is fantastic.

Happy cleaning!

The Mystery of Microsoft.IdentityModel.Extensions

When doing development with SharePoint Server and SharePoint Online, we have to do API calls that are authenticated and authorized. Authentication and authorization over HTTP in regards to SharePoint API's, for the better part of it, nowadays is based on principles and techniques predominantly stepping on the OAuth protocol, which deals with authorization by its definition. We have to do handshaking with token providers and resource owners, and include HTTP headers with our calls. From a development perspective, as long as you have an HTTP request/response interceptor and code that can generate/manipulate/transform HTTP packets and tokens – you pretty much have whatever you need to call an OAuth secured endpoint, such as SharePoint API's.

Every modern web development platform has these capabilities. You can build SharePoint provider-hosted add-ins and console applications on whatever platform you want and use whatever HTTP mangling language you want (See the Python example here for proof https://github.com/SharePoint/PnP/tree/master/Samples/Python.Office365.AppAuthentication). The only thing you really need to do is deal with the authentication and authorization side of things, then just call the API's.

When it comes to the Microsoft promoted development set of tools, we use Visual Studio, ASP.NET and Office Developer Tools to build provider-hosted apps for SharePoint. Our development model steps on ASP.NET, which steps on Windows Identity Foundation and ASP.NET (System.Web and supporting libraries). Visual Studio knows nothing about SharePoint add-ins unless you install Office Developer Tools.

If you've been around for a while, you will recall Windows Identity Foundation and how it got integrated into the .NET Framework (4.5) (see this Namespace Mapping between WIF 3.5 and WIF 4.5 and Guidelines for Migrating an Application Built Using WIF 3.5 to WIF 4.5). "Beginning with .NET 4.5, Windows Identity Foundation (WIF) has been fully integrated into the .NET Framework". *Almost* everything under the namespaces Microsoft.IdentityModel have been moved to System.Security.Claims, System.ServiceModel.Security, and the System.IdentityModel namespace.

One odd fella, Microsoft.IdentityModel.Extensions, has been left aside. This is the namespace in the Microsoft.IdentityModel.Extensions.dll file and is where the code for SharePoint provider-hosted apps mangling of OAuth and S2S tokens is located. During that era SharePoint development had a decline in general, mostly due to the growth of Office 365 and Azure AD, so the libraries got left aside (btw, they are all owned by the almighty and unhuman idol of mine Vittorio Bertocci). Microsoft.IdentityModel.Extensions is not maintained by anyone, yet SharePoint add-ins depend on it. The future of SharePoint server-side development depends on it. Development of SharePoint add-ins on the Microsoft development platform depends on it. SharePoint PnP depends on it, so we need to show that library some deep love.

Enough history, let's look at where we use it and where it comes from.

 

Understanding the dependency chain

I'm going to focus on SharePoint provider-hosted add-ins and applications that use App-only calls, because that's where this stuff gets used for the most of it.

You create a SharePoint Add-in project in Visual Studio and you get a bunch of stuff in the project. Some are .cs/.vb files, others are assembly refences and a few nuget packages.

If you look at the AppForSharePointOnlineWebToolkit nuget package, it contains Framework assembly references. Notice the Microsoft.IdentityModel.Extensions assembly and the fact that it doesn't exist in the nuget package itself. AppForSharePointOnlineWebToolkit brings in SharePointContext and TokenHelper classes to your project (together with the ASP.NET MVC SharePointContextFilter attribute). Before the AppForSharePointOnlineWebToolkit package was available, we used to copy those classes to get a console application to authenticate with SharePoint. Here is a view of the package in NuGet Package Explorer. You might recognize SharePointContext.cs/.vb and TokenHelper.cs/.vb.

So, where does Microsoft.IdentityModel.Extensions.dll come from? This is the mysterious question that we have to answer, so we can reliably build PnP tooling that helps developers.

Let's look at the Microsoft.SharePoint.CSOM NuGet package:

No dependencies. No Microsoft.IdentityModel.Extensions.dll to be found.

This is quite a bad design decision – both Microsoft.SharePointOnline.CSOM and AppForSharePointOnlineWebToolkit require Microsoft.IdentityModel.Extensions.dll to be present, TokenHelper has direct managed code calls to classes in it. Inherently, our OfficeDevPnP.Core library depends on Microsoft.IdentityModel.Extensions.dll, and this is where it affects PnP.

The answer to the question: the actual assembly gets delivered with Office Developer Tools for Visual Studio 2015: https://www.visualstudio.com/vs/office-tools/ through one of its packaged MSI's, which steps on Web Platform Installer. This means that the entire development toolchain depends on the abovementioned dependencies.

The problem doesn't exist only here either. There's quite a few nuget packages that depend on Framework assemblies. That is OK. Our problem is that it is delivered with a Visual Studio extension.

NOTE: At one point of our careers me and a colleague of mine did a silly thing and packaged the DLL as an NuGet package and published it on nuget.org. We delisted it, but can never remove it from the feed (that's how nuget.org rolls): https://www.nuget.org/packages/Microsoft.IdentityModel.Extensions/1.0.0

 

You can actually download the MSI

Funny enough, you can directly download the MSI packages that copy over the DLL to your machine:

If you open the MSI with 7-ZIP (yes, you can do that), or any other MSI explorer, you can see that it only contains that DLL.

This is the only way I know, that you can get the assembly without VS Office Developer Tools… until…

SharePointPnP.IdentityModel

As part of PnP, we want to help developers build stuff. We pay a lot of attention towards what you need to get going and how easy it is to get it. We currently have a new agenda, too – getting PnP to run on .NET Core. This is possible, see my previous blog posts on Developing the ASP.NET Core Authentication/Authorization Middleware for SharePoint Provider-Hosted Apps (Add-ins), and the OfficeDevPnP.Core.Framework.Authentication library. Keep an eye for developments here, because we're investing time into it.

The OfficeDevPnP.Core.Framework.Authentication library achieves one awesome goal – it lets you build an ASP.NET Core web application that authenticate with SharePoint, just like every other SharePoint provider-hosted add-in, but you can make use of the ASP.NET Core stack, which is tons better than System.Web.Mvc etc. You can use CSOM with it to manipulate SharePoint. Awesome, but it doesn't solve one next challenge – to use OfficeDevPnP.Core to help you manipulate SharePoint better.

OfficeDevPnP.Core naturally depends on Microsoft.IdentityModel.Extensions.dll, which depends on System.IdentityModel.dll, and that causes hell when you want to run in .NET Core.

Our solution is simple – port Microsoft.IdentityModel.Extensions.dll to a .NET Core project in Visual Studio. The hard work of this is done here: https://github.com/SharePoint/PnP/tree/dev/Solutions/AspNetCore.Authentication/src/SharePointPnP.IdentityModel

For the time being, you can build a custom OfficeDevPnP.Core assembly with reference to SharePointPnP.IdentityModel instead of Microsoft.IdentityModel.Extensions and happily continue referncing it in .NET Core.

We are working with the PnP team to do this once for good in January (2017). Stay tuned…

Azure App Service CORS versus Web API CORS

I'm blogging this as it wasted about 3 hours of my time. I ended up debugging the Microsoft.AspNetCore.Cors library, and that takes time.

I was having issues with cross-domain AJAX requests (with AngularJS). Firefox was pretty shit at telling me the problem. The developer tools just show the failed request. IE was pretty verbal:

SEC7122: Credentials flag was set to true, but Access-Control-Allow-Credentials was not present or was not set to "true".

Right on the spot. So using Fiddler, I spent some time reviewing HTTP packets (of course it is difficult with HTTPS and debugging) and IE was pretty much right. The response did not include Access-Control-Allow-Credentials: true

I tested it locally and it works fine. Debugging runtime in Azure is difficult (I would've lost another 3 hours probably) so I ended up guessing. It turns out that configuring CORS on the Azure Web Site overrides stuff in the underlying layers. Even though that ASP.NET Core is doing the right thing, somewhere (most likely on packet exit) Azure CORS takes control. So, if you want to use CORS in ASP.NET, avoid this:

Solution: remove all of them, including a "*" if you have one.

Unfortunately (for me), this is also documented (I went to document it myself, but it was already there!). All I had to do was find it :)

https://azure.microsoft.com/en-gb/documentation/articles/app-service-api-cors-consume-javascript/#app-service-cors-versus-web-api-cors clearly states:

"Don't try to use both Web API CORS and App Service CORS in one API app. App Service CORS will take precedence and Web API CORS will have no effect. For example, if you enable one origin domain in App Service, and enable all origin domains in your Web API code, your Azure API app will only accept calls from the domain you specified in Azure."

And even further, there is something on StackOverflow:

http://stackoverflow.com/questions/36860423/enable-access-control-allow-credentials-header-in-azure-website-azure-app-servi

Ouch, painful, lesson learnt. Hope this helps you and saves you time.

For the record, Microsoft.AspNetCore.Cors ignores everything if the Origin header is not present:

Microsoft.AspNetCore.Authentication.ActiveDirectory updated to ASP.NET Core RTM

Since the ASP.NET Core RTM bits came out it's time to update all RC1/RC2 solutions and NuGet packages to run under RTM.

Find it here:

The steps to update are not that difficult, but here they are in general:

  1. Global.json should be updated, and the version here is important. Notice the bits are in preview (we still don't have VS2015 tooling that is RTM at the time of writing this):
{
"projects": [ "src" ],
"sdk": { "version": "1.0.0-preview2-003121" }
}
  1. Change all dependencies from Microsoft.AspNet.Something to Microsoft.AspNetCore.Something. Some libraries have been totally rearranged.
  2. Update the project.json file. There are quite a few things to be done and intellisense is good at pointing them out. The most important:
"frameworks": {
"netcoreapp1.0": {},
"net451": { }
}

This essentially means the library can run in both frameworks, cool.

The code has also significantly changed/improved – lots of work around redirects and working with the ASP.NET Cookie Middleware.

Feel free to ping me if you have issues.

Getting Started with ASP.NET Core Add-ins for SharePoint Online

Overview

With the introduction and growth of ASP.NET Core, we SharePoint/Office 365 developers need a story that allows us to build Add-ins on top of provider-hosted ASP.NET Core deployments. What we have now works with old school ASP.NET and MVC 5 (yes, that is now old J).

As I explained in my previous post, Developing the ASP.NET Core Authentication/Authorization Middleware for SharePoint Provider-Hosted Apps (Add-ins), I've explained why this might be appealing and the technical challenges we are faced with. I have put together a library that allows us to develop SharePoint Add-ins that run on ASP.NET Core and in this blog post I explain how you can get started with including it in your own ASP.NET Core projects.

We have now updated the library to .NET Core and ASP.NET Core RTM. Previously it was running on RC1 only.

If you just want to have a look, just get the sample project and run it. Please share your experiences and feedback, they are an important reminder to where we need to put effort in with the PnP team.

Before you start

  • You don't have to complete these steps manually; the PnP repository has a sample project located here: https://github.com/OfficeDev/PnP/tree/master/Solutions/AspNetCore.Authentication
  • Make sure you are using Visual Studio 2015 Update 3. This is not required, but some new features in the tooling make things easier.
  • You need to register your app and get a ClientId and ClientSecret. This is not detailed here as it is nothing new. By default, ASP.NET Core web applications run on https://localhost:5000

Things you need to know before you start (all are explained why here):

  • At the time of writing (09.09.2016) there is no support for High-Trust Add-ins, yet. This is on our roadmap.
  • Our PnP library still targets .NET Framework 4.5.1.

Adding SharePoint Authentication to ASP.NET Core

Step 1: Create a new ASP.NET Core project based on the Web Application template

Step 2: Change the target framework of the web application project

This might change in future. Currently, our PnP library only runs on .NET 4.5.1. See why in this post: Developing the ASP.NET Core Authentication/Authorization Middleware for SharePoint Provider-Hosted Apps (Add-ins)

Change this:

"frameworks": {
"netcoreapp1.0": {
"imports": [
"dotnet5.6",
"portable-net45+win8"
]
}
},

To this (you can, of course, keep the imports that you need):

"frameworks": {
"net451": {}
},

Then, remove the dependency to Microsoft.NETCore.App (it is only for netcoreapp1.0 and above):

"dependencies": {
"Microsoft.NETCore.App": {
"version": "1.0.0",
"type": "platform"
},

If you need the NETStandard library , just add it under dependencies:

"dependencies": {
"NETStandard.Library": {
"version": "1.6.0",
"type": "platform"
},

Step 3: Add the Microsoft.SharePointOnline.CSOM NuGet package

You need this to write SP CSOM code that works with SharePoint J Get it here: https://www.nuget.org/packages/Microsoft.SharePointOnline.CSOM/

PS Command: Install-Package Microsoft.SharePointOnline.CSOM

 

Step 4: Add the OfficeDevPnP.Core.Framework.Authentication NuGet package

With the current release of VS Tooling and .NET Core projects (Preview 2 at the time of writing) you can't add a reference to a DLL, you need to add it through a NuGet package.

As pointed out, also at the time of writing the PnP Core Authentication code is not part of the Core library (see roadmap later in this post, we are working on that). This means that you need to bundle the OfficeDevPnP.Core.Framework.Authentication DLL into a NuGet package.

You can do this following the steps outlined on the NuGet site (https://docs.nuget.org/create/creating-and-publishing-a-package ) or just using Nuget Package Explorer (click here).

 UPDATE (18.09.2016):

I have added a ready NuGet package to the project. You can find it here:

 

Step 5: Add other necessary NuGet packages to your project.json

You will need these:

"Microsoft.AspNetCore.Authentication": "1.0.0",
"Microsoft.AspNetCore.Session": "1.0.0",
"Microsoft.AspNetCore.Server.Kestrel.Https": "1.0.0",

 

Step 6: Configure your Service Collection and pipeline in Startup.cs

Now it is time to add code. I hope you are impressed with the minimal footprint.

Add using OfficeDevPnP.Core.Framework.Authentication; and using OfficeDevPnP.Core.Framework.Authentication.Events;.

Include AddSession() and AddAuthentication() to your service collection.

public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddMvc();
 
//Add Session to the service collection
services.AddSession();
 
//add the authentication middleware and point SP as the default authentication sign-in scheme
services.AddAuthentication(sharedOptions =>
sharedOptions.SignInScheme = SharePointAuthenticationDefaults.AuthenticationScheme);
}

Then, go ahead and configure your pipeline to include the middleware:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
//required to store SP Cache Key session data
//must also call AddSession in the IServiceCollection
app.UseSession();
 
//Add SharePoint authentication capabilities
app.UseSharePointAuthentication(
new SharePointAuthenticationOptions()
{
ClientId = Configuration["SharePointAuthentication:ClientId"],
ClientSecret = Configuration["SharePointAuthentication:ClientSecret"],
 
AutomaticAuthenticate = true, //set to false if you prefer to manually call Authenticate on the handler.
//OPTIONAL: CookieAuthenticationScheme = "AspNet.ApplicationCookie",
 
//Handle events thrown by the auth handler
SharePointAuthenticationEvents = new SharePointAuthenticationEvents()
{
OnAuthenticationSucceeded = succeededContext => {
return Task.FromResult<object>(null);
},
OnAuthenticationFailed = failedContext => {
return Task.FromResult<object>(null);
}
}
}
);

NOTE: Some web applications/add-ins will require multiple authentication mechanisms. The library is built to allow this and co-exist with other Authentication middleware.

NOTE 2: Keep in mind that this is a pipeline, so order matters. The right place will depend on your app.

 

Step 7: Add your ClientId and ClientSecret

Configurations in ASP.NET Core happen in the appsettings.json file. Add the following under the root object:

"SharePointAuthentication": {
"ClientId": "Add id here",
"ClientSecret": "Add secret here"
}

Step 8: Modify your Kestrel Web Server to run on HTTPS

Since we're doing Add-in authentication based on the OAuth protocol, we need to run over SSL. ASP.NET Core can run both on IIS and on Kestrel, I prefer Kestrel. This is what you need to do:

In Program.cs, change this:

public static void Main(string[] args)
{
var host = new WebHostBuilder()
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseStartup<Startup>()
.Build();
 
host.Run();
}

To this:

public static void Main(string[] args)
{
var host = new WebHostBuilder()
.UseKestrel(options =>
    {
    options.UseHttps(@"..\..\certificates\localhost_ssl.pfx", "pass@word1");
options.NoDelay = true;
    }
)
.UseUrls("https://localhost:5000")
.UseContentRoot(Directory.GetCurrentDirectory())
.UseStartup<Startup>()
.Build();
 
host.Run();
}

You can stick it in a try/catch if you wish. I have also added a IgnoreSslErrorsConnectionFilter class in the PnP sample to get rid of SSL handshaking errors with untrusted certificates. This is optional.

The SSL certificate is committed to the certificates folder. Note the https://localhost:5000 URL. Make sure everything runs at this point.

Make sure your project is firing up HTTPS://localhost:5000 and your F5 is not kicking off IIS Express, but rather the actual web application (which runs it as a console application now). This will start Kestrel.

Step 9: Add some CSOM code

You are all set. Write some CSOM Code to test:

var spContext = SharePointContextProvider.Current.GetSharePointContext(HttpContext);
var spLists = new List<SharePointListViewModel>();
 
if (spContext == null) return View();
 
//build a client context to work with data
using (var clientContext = spContext.CreateUserClientContextForSPHost())
{
if (clientContext != null)
{
var lists = clientContext.Web.Lists;
clientContext.Load(lists);
clientContext.ExecuteQuery();
 
foreach (var list in lists)
{
spLists.Add(new SharePointListViewModel() { ListTitle = list.Title });
}
}
}

Step 10: Test it!

Now that everything is set, go to the SharePoint Online site where your app is configured, then click it's link. It will go through AppRedirect.aspx and then lead your browser to https://localhost:5000 if everything is configured right. The ASP.NET Code PnP middleware will intercept (based on the SPHostUrl query string) and get the context token, work through it and eventually allow you to instantiate the SPContext object needed to work with CSOM data. Pretty cool, hey?

Summary

Overall, it takes 10 steps to heaven J We are working hard to improve everything we can in regards to the developer experience, that is the fun parth in building tooling and API's.

Please take the time to give feedback, share your issues or even high five. Microsoft and the PnP team need to see activity and the need for this library, so we have justification to increase its priority.

 

Roadmap for the ASP.NET Core Authentication library

As mentioned, things are still evolving. We have tons of issues to solve in terms of dependencies and figure out how to make it easier to plug-and-play all of this. It might seem hard at first, but so where Apps when they first came out. The PnP team is working hard to make it easier for developers and this is all done in our free time. Please help us out with constructive feedback and contributions https://github.com/OfficeDev/PnP .

Here is a list of targets that we have:

  • Enhance the sample to demonstrate the usage of App-Only access tokens.
  • Enhance the sample to demonstrate on-the-fly authentication through the Authentication Code flow.
  • Remove dependencies from Microsoft.IdentityModel.Extensions and framework assemblies
  • Implement High-Trust authentication capabilities
  • Add to the current OfficeDev PnP Core library
  • Build a true .NET Core App compatible library

 

Team Leadership in а Software Development World

Being a good team leader is hard. At least for me. For some it may come natural, for others - we have to put in a reasonable amount of effort to get it right. I spend a lot of energy thinking about what good leaders do, especially in the software development field, so I'm putting forward some thought and principles that I follow. Read further for my ideas to grow software development team leadership into a workable model.

Team leadership is different from management. It's less bullshit, more personal and very tactical, operational and actually things get delivered. That's why it's important. I'm going to start writing a series of posts about it and this is the first one. I'm sharing my key principles, which are written from a software development perspective, but most apply to any industry. Principles are essential towards establishing the grounds of an initiative. They are personal, but everyone can interpret them from their point of view (see measurement below, there is no black and white here.). You'd be surprised at how many teams don't even have principles.

The actual real-life problem

No one teaches us to be team leaders. We either get promoted to the position at one point in our careers, or we do the job because we stood out. Every available courseware on team leadership is part of some greater initiative, so learning is not really focused. You can even argue that there isn't really any good courseware on team leadership, especially in the software development space, yet there are millions of team leaders around the world. There's books, but that's different, you need practical workshops that take days, but we rarely do those. Very little companies offer soft-skills and management training, and usually the "team leader" is in that middle ground between management and developer, so they don't really get the training attention. The second part to the problem is that team leaders are naturally busy and many companies don't invest in that training level.

Creating a methodology

I believe the entire practice of team leadership could be put to a model. This is not a software delivery model or a project life-cycle methodology, but rather a framework for learning about and growing team leadership skills. I don't have the experience to do it in the context of other disciplines, but hopefully I have the experience to base it on software development. Maybe I suck at it, but at least I'm doing something about it. Do you want to help me write/author this model? I am gathering a team to work on this side project, so let me know if you are interested to help out and be part of it. I'm even keen to hear if you are just interested in this model and you think it is a good idea.

Here are things I try to be best at.

Knowing your team

I try to get to know everyone as much as I can, but not crossing the line where you become too close (dangerous). Go to lunch together, socialise and listen. Observe. There is huge value in listening alone. Spending out-of-office time with the team allows people to open up. Understanding the true character of your team members by talking to them is very important. Stories and experiences are usually shared outside of the work environment, so whatever you could fit in is worthwhile. I use this time to get a feel of people's behaviors, preferences, their most productive time of the day, whether they are introverts or extraverts, whether they have problems that I could be aware of (and maybe help), how they communicate, sometimes you might even pick up on how they solve problems or resolve conflicts. All this information is extremely valuable to me - I can arrange people with similar productivity patterns, I can reduce the stress if there are issues on the side, I can learn about things in our work environment, I can show personal interest and that really matters, it is well respected. It might not always be lunch - drinks after work or anything else you could think of will do. This point proves that work and life are actually things that go together, and they need to be balanced.

Key point: Get them to know you too. Tell your stories. You are their leader, so opening up could really go a far way.

Understand the "TEAM" part in "team leader"

No one gets big results done when working alone, and we usually want big results out of our jobs, lives and ideas. A team leader who does all the true work is pretty much a failed team leader. Results (and innovation) get delivered and nurtured when many people work together for the common goal. This is why we have teams in the first place. I do the best I can to fairly share the work and make sure everyone is putting in their part. This doesn't always work, sometimes the key foundations of what the team is doing misaligns with members of the team. But at the end of the day results happen when everyone contributes.

Agree on principles

Yes, that's one of my principles J This is actually applicable for all situations when you do something with someone else - love life, project work, company management, many others but also working in a team. You define and agree on the team's key principles so everyone knows which direction to follow, how to go by it, and most importantly, how to resolve a conflict when you need to. You base decisions and resolutions on your principles - that is a good and easy way to solve issues related to personal preferences.

Lead.

Quite a no brainer, but you have to lead people. Many misinterpret what leading actually is. To me it is not about giving tasks or solving their technical challenges, it is about empowering people to figure out and perform their own tasks in the best direction for the situation. Instead of solving the most technical challenges, give directions and guidance so the team members solve their technical challenges, offer support and re-evaluation when needed. This principle touches on the management side of things, but reading between the lines it is different. You will find many "Leader vs. Manager" comparisons to include this.

Give feedback often

I suck at this and I am working on improving it, and adopting it as a principle is the first step in improving it. Giving positive feedback is much easier, giving negative feedback in a timely manner is critical, but for some it is really difficult. If you don't do it your team members will think that what they are doing is right and exactly what you expected, yet you don't get the results in. Giving positive feedback is equally important, but much easier to learn and get into a habit. Negative feedback I always in private, positive feedback – always public.

Respect what you do

Show that you care, both about the people and the actual work that you do. Promote the idea of mutual respect as well as respect for the work that you do, highlight it as a principle. You can show respect in many ways, here's a few tips: Listen to personal issues and give advice on how to minimize their impact on the whole team. Motivate team members to respect the team as a whole, in general, and believe in the work that you do. That is very important. I sometimes have projects that I don't really believe in - they either don't bring value or the requirements are just silly. It is extremely evident when people have to do things they don't believe in. When a team leader doesn't care - things go downhill. I have seen this with some of our work and it's not good. A good team leader will find a way to make everything appealing to the team so the work is done with quality in mind. Quality leads to happy team members, happy clients and long-term success. We often have to do work that we don't like or don't want to do. Those emotions are best kept aside and often they are for a greater cause, so do your best to respect that work too.

Minimize process and paperwork

Being lean is good and I have had really good results here. Other companies and team leaders praise OneBit for being so lean and fast. A true leader removes obstacles from interfering with the true work that delivers value. Team members appreciate when you make their job easier. Do whatever you can to simplify what they do and how they need to do it. This is important for the people that actually get things done. Get rid of process. Don't give me the "we're a large organization with slow processes and lots of approvals" bullshit, I've heard it way too many times. You're a team leader, you're there to make things happen, so change your business and stop saying "that's how our slow company does things". People will leave you if they have far too much stuff that impedes their work, and if they leave - you have no team and you're not leading anyone. Developers are smart - they want to code at least 40 hours a week, not 20 and spend the rest in processes and impediments. Being lean should be a principle.

Be a good human

A colleague of mine praised me with a few simple words - he used that term - "good human". It stuck with me, but I could actually relate to it significantly. I'm taking it in as a principle. I don't know how to define what it is to be a good human, but I'm doing my best to be one in my own perception and character. You can take it under your own understanding and mark it down based on what you feel is good, I focus on fairness, being nice, supportive, having values and avoiding anything that makes me look like an asshole. I've got lots of those.

Be up to date with your stuff

You might not be in the software development field, but I'm sure this relates to you. IT is an industry and ecosystem that changes constantly. I've adopted the concept of working 24/7 and I am perfectly fine with that. If I'm not in front of a device, I observe and learn about human behavior, social patterns, how to be a good human and sink in any information I find relevant from everywhere (that is what I mean when I say 24/7). On the technical side, you should really be well up to date and actually top notch with what you do. Adopt it as a principle to know as much as you can. Some team leaders fall behind with the latest trends and innovations, but other jobs just demand you to be the best. Mine does so I do everything I can here.

Measurement

I try to measure everything I do. Everything from where my time is wastes to how much water and electricity I use. Measuring the performance of a "team leader" is hard and subjective. It's also quite difficult to define what "getting it right" actually means. There is no black and white, it is all about you and your team, and how you do what you do together. Most books specify that KPI's should be related to staff retention, growth, numbers, and many other measurable indicators. While all that is true, I try to never underestimate or forget about the bond with your team. The level of mutual respect, loyalty, trust and support. You can't really measure that. Managers measure KPI's, team leaders focus on the unmeasurable relationships between people. It takes time, sometime years, to build this and you never know if you're there or not

That's all for now.

 

Last words

I'm working on ways to enable better learning of team leadership. For now – all I have to offer is learning through experience. My amateur way to recruit a good team leader: join me J Let me know you want to be a good team leader and let's both learn how to be good team leaders together. That's probably the best opportunity you have in front of you and these last sentences are the best I could do at subliminal advertising. Thanks for reading :)

Developing the ASP.NET Core Authentication/Authorization Middleware for SharePoint Provider-Hosted Apps (Add-ins)

Getting SharePoint apps to work with ASP.NET Core was a bit of an interesting challenge, which I will share with you in this post. A nice new addition to the Office Dev PnP repository surfaced up from getting this working – a library/implementation for you to reuse in your day-to-day ASP.NET Core apps/add-ins development (see https://github.com/OfficeDev/PnP/tree/master/Solutions/AspNetCore.Authentication). You add this to your ASP.NET Core projects and you can authenticate as a SharePoint provider-hosted app. Hopefully, we will integrate this into the PnP Core namespace & package as the time comes.

The Problem

In order to build ASP.NET MVC 5 apps (not ASP.NET Core) we have the option to use the Office Developer Tools for Visual Studio 201X, which gives us developers an "App for SharePoint" project template (notice the App terminology never changed to Add-ins!). We create one of these and get an ASP.NET MVC 5 web application project together with an App project with the manifest and packaging capabilities. We get files such as TokenHelper.cs, SharePointContext.cs and SharePointContextFilterAttribute.cs with all the plumbing for token requesting, storage, cookie generation and authorization. Good stuff, but now old.

We currently don't have an equivalent for ASP.NET Core. There is no toolset in Visual Studio to develop apps/add-ins that run on ASP.NET Core, no project template. I have asked Microsoft around and as far as I got responses there is no team assigned to develop anything. The guy who developed the toolset moved on to another team. What's even more complicated is the fact that ASP.NET Core is drastically different, so we can't just do a copy/paste port and recompile it for the DNX runtime. We have to rewrite the whole implementation.

This blog post is my story on the rewriting of it and bringing the SharePoint developer community a way to do SharePoint apps with ASP.NET Core.

Business Justification

Why would you use ASP.NET Core for SharePoint Apps?

  • You may want to migrate existing ASP.NET MVC 5 Provider-Hosted Add-ins to ASP.NET Core to make use of the benefits that the new platform offers
  • Introduce an ASP.NET Core / SharePoint Add-in story, because currently there is none. PnP to the rescue!
  • You might not be ready for Azure AD authentication and the Active Directory Authentication Library (or you just don't want to use it for whatever reason, such as the new MSAL package)
  • You want your provider-hosted Office Marketplace app to use ASP.NET Core.

The Solution – PnP to the Rescue!

The actual solution to the above problem is quite simple:

  • create a library that performs the necessary authentication handshaking and authorization to be able to run SharePoint apps/add-ins on ASP.NET Core.
  • Bundle it as part of PnP so it gets adoption, attention, contribution and support
  • Publish it as a NuGet package so everyone could add it and use it in their ASP.NET Core web applications.

Some terminology to clarify things:

  • AspNetCore.Authentication – this is the name of the Office PnP Solution in the repository. It contains a sample web application, a SharePoint app project and the library below
  • OfficeDevPnP.Core.Framework.Authentication – the name of the library (and namespace) with all of the authentication logic & plumbing. This is what will be pushed out as a NuGet package so it can easily be added to any ASP.NET Core project.

Design Goals

I've used the following principles and goals in the design of this solution:

  • It must be very easy to "Add" and "Use", based on the plug 'n' play model of ASP.NET Core (Add and Use are special Core terms)
  • Enforce the least amount of change to the developer experience, SharePoint developers should know how to use this straight away
  • Base it on the ASP.NET Core middleware design
  • Figure out how to compile to DNX Core. This is currently not achieved. We must compile to .NET Framework rather than Core due to a dependency on Microsoft.IdentityModel.Extensions.dll
  • Implement with ASP.NET Core configuration and logging patterns/classes
  • Base it on the ASP.NET Authorization & Authentication model so the request is truly authenticated and authorized from the System.Security.Claims.IIdentity perspective.
  • Be able to use the [Authorize] attribute to lock down controller methods
  • Figure out how to include it as part of the OfficeDevPnP.Core library. This is currently not achieved. We cannot add it to the true Core assembly due to the old project format and the fact that we're using the/ DNX assembly format.
  • Release it through NuGet so anyone could add it to their ASP.NET Core web application.

How does SharePoint Authentication/Authorization work in the ASP.NET MVC 5 implementation?

When we are tackling a port/upgrade/rewrite of something we must really understand how it works to build on it, improve it and get results. This is a quick refresher of how SharePoint provider-hosted authentication is implemented in ASP.NET MVC 5.

  • We had tooling, the Office Developer Tools for VS, which gave us a starter template project with several class files that made authentication work with SharePoint.

  • From that point onwards we literally press F5 and VS does what it needs to do to get a "Hello World" solution running. It worked.
  • The TokenHelper.cs & SharePointContext.cs set of classes handled the required plumbing & business logic.

  • These classes had a dependency on Microsoft.IdentityModel.Extensions.dll for S2S and OAuth2 token/claims manipulation.
  • The class design and implementation followed the MVC 5 patterns and development model
  • We had a publish & deploy experience, quite satisfactory for most.
  • A SharePointContextFilter attribute handles redirects and retrieves a SharePointContext object in session.
  • The SPCacheKey is stored in a cookie to identify users between their redirects and web requests
  • TokenHelper deals with authorization codes and access tokens, together with Microsoft.IdentityModel.Extensions.dll
  • The SharePointContext.cs file contains a total of 7 classes, some of them abstract. SharePointAcsContext/Provider and SharePointHighTrustContext/Provider are important as they hold the specific implementations of authentication through ACS and through the High-Trust model (using symmetric keys from certificates).
  • When the user clicks on an installed app url, or the app icon on the site contents page in SharePoint, the user is taken to AppRedirect.aspx. This page generates an HTML form element posting to the URL of the app, providing it with a context token and other useful information so the provider-hosted app can authenticate the request. I will not go into greater detail of this process, but it is crucial to understand it. It is well documented by fellow bloggers.
  • There is no true implementation of ASP.NET authorization (the [Authorize] attribute) at the MVC controller level. Poo.

NOTE: The above are key points that describe how the AuthZ mechanism works when we talk about SharePoint Provider-hosted apps. Note that it is truly authorization, not authentication. SharePoint handles authentication through its identity provider, then OAuth is used to share resources between SharePoint and the application you are building. OAuth 2 is an authorization protocol (see https://tools.ietf.org/html/rfc6749). On this point, read further down for some wording misnomers…

ASP.NET Core Implementation Deep Dive

OK so here we go. So far it is called AspNetCore.Authentication, which is probably the name that will last for a while until Vesa makes me change it. In the following section I list the key implementation decisions made so far. Here is a quick screenshot of the classes created to meet our needs:

Middleware

It is based on the ASP.NET middleware concepts, registered through extension methods on the IApplicationBuilder object during the Configure method in Startup.cs

//Add SharePoint authentication capabilities

app.UseSharePointAuthentication(

new SharePointAuthenticationOptions()

{

CookieAuthenticationScheme = "AspNet.ApplicationCookie",

//I really don't like how config settings are retrieved, but that is how the ASP.NET guys do it in their samples

ClientId = Configuration["SharePointAuthentication:ClientId"],

ClientSecret = Configuration["SharePointAuthentication:ClientSecret"],

//Handle events thrown by the auth handler

Events = new SharePointAuthenticationEvents()

{

OnAuthenticationSucceeded = succeededContext =>

{

return Task.FromResult<object>(null);

},

OnAuthenticationFailed = failedContext =>

{

return Task.FromResult<object>(null);

}

}

}

);

 

Authentication & Authorization

The AspNetCore.Authentication library is based on the Authentication & Authorization libraries part of ASP.NET Core (see https://github.com/aspnet/Security/tree/dev/src/Microsoft.AspNetCore.Authentication and https://github.com/aspnet/Security/tree/dev/src/Microsoft.AspNetCore.Authorization ). This is important to achieve one of the design goals – consider the web request authenticated and be able to use the [Authorize] attribute and relevant AuthZ capabilities.

The provided SharePointAuthenticationMiddleware class inherits the framework's AuthenticationMiddleware class

public class SharePointAuthenticationMiddleware : AuthenticationMiddleware<SharePointAuthenticationOptions> { …removed… }

The CreateHandler method returns an instance of the SharePointAuthenticationHandler, holding all of the logic for authentication handler:

protected override AuthenticationHandler<SharePointAuthenticationOptions> CreateHandler()

{

return new SharePointAuthenticationHandler();

}

NOTE: Back to the point on AuthZ vs AuthN, the ASP.NET classes use the Authentication term, even though there is a case where a remote party does the authentication. This might be a topic for argument for the purists and scientists out there.

Cookies and Session

The cookie handling implementation has been entirely rewritten in ASP.NET Core, so naturally that had a knock-on effect on the SharePointContext classes in AspNetCore.Authentication that manage the cookie to track the user's requests.

//The following code generates a cookie in the response with the SPCacheKey as a value

var options = new CookieOptions() { HttpOnly = true, Secure = true };

httpContext.Response.Cookies.Append(SPCacheKeyKey, spAcsContext.CacheKey, options);

//read the cookie value

HttpCookie spCacheKeyCookie = new HttpCookie(SPCacheKeyKey, httpContext.Request.Cookies[SPCacheKeyKey]);

string spCacheKey = spCacheKeyCookie != null ? spCacheKeyCookie.Value : null;

Luckily, the code is pretty simple J

Handling Events

In a typical use-case scenario, you would reference the compiled library and retrieve it through the NuGet package manager. That means that you can't really plug in your own code, so I've implemented an events model. The idea is that you as a developer will subscribe to the events and deal with custom logic in the handlers. The following are the currently implemented events:

/// <summary>

/// Invoked when the SharePoint authentication process has succeeded and authenticated the user.

/// </summary>

public Func<AuthenticationFailedContext, Task> OnAuthenticationFailed { get; set; } = context => Task.FromResult(0);

 

/// <summary>

/// Invoked when the authentication handshaking failed and the user is not authenticated.

/// </summary>

public Func<AuthenticationSucceededContext, Task> OnAuthenticationSucceeded { get; set; } = context => Task.FromResult(0);

See the Events = new SharePointAuthenticationEvents() { } line in the UseSharePointAuthentication extension method.

 

Let me know if you need any other events handled.

Getting Started

So, to get this up and running, do the following:

  1. Clone and build the OfficeDevPnP.Core.Framework.Authentication project and add a reference to the output NuGet package to your ASP.NET Core application.
  2. Add the following to the Startup.cs Configure method in your ASP.NET Core web application:

app.UseSharePointAuthentication(

new SharePointAuthenticationOptions()

{

CookieAuthenticationScheme = "AspNet.ApplicationCookie",

ClientId = Configuration["SharePointAuthentication:ClientId"],

ClientSecret = Configuration["SharePointAuthentication:ClientSecret"],

}

);

 

  1. The library needs Session and Cookies in order to keep track of the client requests during redirects. Add the following to the Configure method:

app.UseSession();

 

app.UseCookieAuthentication(new CookieAuthenticationOptions()

{

AutomaticAuthenticate = true,

CookieHttpOnly = false,

AutomaticChallenge = false,

AuthenticationScheme = "AspNet.ApplicationCookie",

ExpireTimeSpan = System.TimeSpan.FromDays(14),

LoginPath = "/account/login"

}

);

Note that the AuthenticationScheme must be the same in both Use instructions. This is so the SharePointAuthenticationHandler also signs in the cookie authentication middleware to issue the needed cookie.

  1. For the Session & Cookie pipeline additions to work, the following needs to be added to the ConfigureServices method of Startup.cs:

services.AddCaching();

services.AddSession(o => { o.IdleTimeout = TimeSpan.FromSeconds(3600); });

 

  1. There's a few other intricacies in the whole setup:
    1. HTTPS – the web server must be serving over HTTPS. See the sample project for an example of setting up Kestrel with SSL
    2. Bower and NPM – if you are looking at the AspNetCore.Mvc.StarterWeb project you might need to restore all packages to get it running.

That should do it!

Frequently Asked Questions

What about UseRemoteAuthentication?

The ASP.NET Core authentication library/package (Microsoft.AspNetCore.Authentication) has a sample implementation of "Remote" or "External" authentication, packaged in a RemoteAuthenticationHandler class. I spent a good amount of time researching those at the time of writing this library, however I came to the conclusion that it is way too soon to use those classes. It was heavily changed/updated and not stable/ready enough to use when I needed it.

While it sounds like the perfect way to achieve what we want, for the time being I've kept away from it. I will keep a very close eye and rewrite the implementation if required, when we have something stable to work with.

What about Microsoft.IdentityModel.Extensions.dll?

This one's a bit of a bitch. I've posted a question to the relevant Microsoft team to understand what the next plans for this library are and got this for an answer:

"We have moved forward on S2S specific libraries, but it is too early to share publically" (see https://github.com/AzureAD/azure-activedirectory-identitymodel-extensions-for-dotnet/issues/343 )

Not really satisfactory,but at least it is something, so I made the decision to just reference it for the time being until there's new things coming.

The negative effect on the OfficeDevPnP.Core.Framework.Authentication library is that we must compile to the .NET Framework rather than .NET Core since it is compiled for .NET 4.5.2, but that is not such a huge issue because the CSOM library is in the same boat. Until both implementations are ready for .NET Core we will have to live with the fact that we're compiling for the full framework. I'll be working on communicating with the right people on the needs and challenges here.

I'm also looking at the option to completely rewrite the GetAccessToken() methods in TokenHelper.cs, replacing all instances of OAuth2S2SClient and similar classes with custom ones, or reuse some if Microsoft do something in this space. This will allow us to ditch this damn library.

What about compiling for .NET Core?

We're gonna have to recompile the Microsoft.SharePoint.CSOM.dll library for this. It's too big of a task for me (having to run OneBit Software in my work time), but maybe with the PnP folks we can lobby Microsoft to do it, or just recruit more lads and las to help us out. Currently, it is not on the immediate priority list, but I would love to do this one day.

Will this have Visual Studio tooling?

At this stage there are no plans for this, given that the actual app manifest project is still completely operable and you can use it as you always have. If you check out the ASP.NET Core model, things are a bit different now. You add your minimum amount of NuGet packages that you need through the dependency section in the project configuration file and the package manager interfaces, and you only get what you need. ASP.NET Core is minimalist and cool.

In that sense, my goal is to host OfficeDevPnP.Core.Framework.Authentication as a public NuGet package and allow you to directly add it as a package, when you need it. Just like the ASP.NET Core model.

What about a pure client-side implementation?

No. Not here. The SharePoint provider-hosted AppRedirect.aspx mechanism is based on the OAuth 2 Authorization Code flow, which is not safe if the required tokens are transferred to the client. (For more details see my slides from the Azure AD workshop that I delivered in Lisbon).

A client-side authentication implementation must use the OAuth2 Implicit Grant flow, with is specifically designed for those use-cases. It is only as secure as the browser's capability to secure Local Storage and cookie jars.

If you are looking for a pure JavaScript client-side implementation, see the ADAL.JS library and its implementation for AngularJS, but make sure you are aware of its flaws with IE and trusted zones.

Why do you have Gulp, Bower and NPM in the sample StarterWeb project?

The design goal of the sample web application was to use the ASP.NET Core Web Application project template and only add what is needed to demonstrate SharePoint provider-hosted authentication. It comes with all those goodies, so I prefer people to see the difference between a new project and the AspNetCore.Mvc.StarterWeb sample project, and decided not to remove them. People should get to know that stuff.

Future Plans and Upcoming Tasks

Here is a quick summary of what changes are being planned and worked on:

  • Get it working with RTM, I'm waiting for updates on the ASP.NET authZ/authN libraries to figure out if any real architectural changes are required
  • Decide on the High Trust story – we (PnP) still don't know if it is important, so bug us if it is!
  • Decide on the overall PnP strategy for ASP.NET Core, because this is the first solution/sample/component that is built on ASP.NET Core
  • Decide if we need to get some VS tooling to work with this library

Thank you for reading this far (if you actually did!) and thanks to all of my Stockholm SharePoint friends for giving me the motivation to write this blog post on my flight back from SPS Stockholm. Tell Vesa that this stuff is important so we lift it up in the priority list J

A HUGE thanks to Velin Georgiev from OneBit Software for helping me code this up.