Protecting an MVC4 VS2012 Project with OpenId Connect and Azure AD
I have to say I am pretty surprised by the attention that last week’s OIDC OWIN+WebForms post has garnered. Had I known, I would have posted about it much earlier!
In the same spirit, here there’s another quick tutorial addressing a common FAQ: “My company is still on VS2012: can I use the OpenId Connect/WS-Fed middleware?”
The answer is “As long as you target .NET 4.5, totally!”
Just make things a tad more actionable, here there are some basic instructions on how to make a minimal MVC4 app work with AAD and OpenId Connect.
Create an empty project
Fire up the (even more) good ol’ VS2012, create a new project and navigate through the templates until you get to Visual C#/Web/ASP.NET MVC 4 Web Application. Choose a name and click OK.
Here you have a variety of choices. My personal preference is “intranet application”, mostly because it is the project type with the least amount of stuff I don’t need – hence I spend less tile deleting stuff after creation.
We’ll be doing things by the book, hence we’ll enable SSL. The flow was already pretty much the same one you find in VS2013:
- Select the project node in solution explorer. Hit F4.
- In the resulting property pages, flip SSL Enabled from false to true.
- Copy the newly populated SSL URL.
- Right click on the project node. Choose properties.
- Move to the Web tab. Paste the SSL Url in the Project Url field. Shift+CTR+S to save the new settings.
Here we do need to change a couple of things from the template, mostly to disable its Windows auth settings. Open the web config and:
- Change the <authentication> element by setting its mode attribute to “None”\
- Locate the <authorization> element and delete it.
That’s it! Next: configure your app in AAD.
Provision the app in Azure AD
This is exactly the same task for any platform, hence the indications I gave for VS2013 apply verbatim here as well.
Navigate to https://manage.windowsazure.com/, sign in as your tenant admin, scroll to the Active Directory tab, choose the tenant you want to use, select the Applications tab, and click the Add button on the appbar at the bottom of the screen.
Choose “Add an application my organization is developing”.
Give to the app any name you like. Keep the default “web application and/or web api”. Click the Next arrow.
In the Sign-On URL enter the HTTPS address you got when you enabled SSL on the project (mine is https://localhost:44307/). In the App ID URI enter any valid URI that will later remind you of what this app is. For my test app I chose http://OldFashionOWINisAwesomeS. Click the Done button.
Click on the Configure tab and leave the browser open there. We’re going to need some of the values here in just a moment.
Add references to the Cookie/OpenId Connect/SystemWeb NuGets
Once again, exactly the same deal as VS2013. Let’s go back to Visual Studio. Go to Tools->Library Package Manager->Package Manager Console. In the console, enter the following three magic commands:
Install-Package Microsoft.Owin.Security.OpenIdConnect -Pre
Install-Package Microsoft.Owin.Security.Cookies –Pre
Install-Package Microsoft.Owin.Host.SystemWeb –Pre
That will install the necessary OWIN packages.
Add the initialization logic
Here we really need to enable the OWIN pipeline forms cratch, given that the tempalte we used is 100% unaware of it. Luckily, it’s a trivial task.
In the root of the project, add a new class. Name the file Startup.cs.
Here there’s the code you want to have in there:
using Microsoft.Owin; using Owin; [assembly: OwinStartup(typeof(OldFashionOWIN.Startup))] namespace OldFashionOWIN { public partial class Startup { public void Configuration(IAppBuilder app) { ConfigureAuth(app); } } }
This class’ implementation of the Configuration method will be automatically called upon the first request comes in. All it does is invoking ConfigureAuth, the authentication initialization logic which we will add in another file. HEad to the App_startup folder, add a new class Startup.Auth.cs, and make its code look like the following:
using Microsoft.Owin.Security; using Microsoft.Owin.Security.Cookies; using Microsoft.Owin.Security.OpenIdConnect; using Owin; namespace OldFashionOWIN { public partial class Startup { public void ConfigureAuth(IAppBuilder app) { app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType); app.UseCookieAuthentication(new CookieAuthenticationOptions()); app.UseOpenIdConnectAuthentication( new OpenIdConnectAuthenticationOptions { ClientId = "475d1913-d6e7-422c-8dbc-3a94ed21cfaa", Authority = "https://login.windows.net/developertenant.onmicrosoft.com" }); } } }
The Authority part indicates the AAD tenant you want to use, while you can get the value of ClientId from the Configure tab of the application entry in the Azure portal, which should still be available in the browser from few steps earlier in the tutorial.
I already explained in various places what that middleware does, hence I won’t bore you again about it here.
Note: the namespace (VS will append a .App_start, delete it) and the fact that the class is partial.
Finally: head to the Controllers/HomeController.cs file and decorate the class with the following:
[Authorize] public class HomeController : Controller { //...
That will tell ASP.NET that all requestors of this controller’s actions must be authenticated, hence it will help to trigger the auth experience at start up time.
Give it a spin!
Hit F5. You’ll be bounced right away to AAD, Sign in with your user of choice.
Et voila! You are treated with the cerulean theme that was in fashion back in VS2012 times, and the upper right corner shows that you successfully signed in. Pretty easy!
As I hope the above has shown, the OWIN model is super flexible and can be applied pretty much anywhere there’s .NET 4.5 available. That means that if for one reason or another you didn’t upgrade to VS2013, you can still take full advantage of Azure AD, ADFS and the ease of use of the new OWIN based middlewares have fun!!!