<CharlieDigital/> Programming, Politics, and uhh…pineapples


Adding Support for Azure AD Login (O365) to MVC Apps

Posted by Charles Chen

I spent the day toying around with ASP.NET MVC 5 web applications and authentication.  I won't cover the step-by-step as there are plenty of blogs that have it covered.

It seems that online, most examples and tutorials show you either how to use your organizational Azure AD account or social identity providers but not both.

I wanted to be able to log in using Facebook, Google, and/or the organizational account I use to connect to Office 365.

This requires that you select Individual User Accounts when prompted to change the authentication mode (whereas most tutorials have you select "Organization Accounts"):


This will give you the baseline needed to add the social login providers (more on that later).

To enable Windows Azure AD, you will need to first login into Azure and add an application to your default AD domain.  In the management portal:

  1. Click on ACTIVE DIRECTORY in the left nav
  2. Click the directory
  3. Click the APPLICATIONS link at the top
  4. Now at the bottom, click ADD to add a new application
  5. Select Add an application my organization is developing
  6. Enter an arbitrary name and click next
  7. Now in the App properties screen, you will need to enter your login URL (e.g. https://localhost:4465/Account/Login) and for the APP ID URI, you cannot use "localhost".  You should use your Azure account info like: https://myazure.onmicrosoft.com/MyApp.  The "MyApp" part is arbitrary, but the bolded text must match your directory identifier.

Most importantly, once you've created it, you need to click on the CONFIGURE link at the top and turn on the setting APPLICATION IS MULTI-TENANT:


If you fail to turn this on, the logins are limited to the users that are in your Azure AD instance only; you will not be able to log on with accounts you use to connect to Office 365.  You'll get an error like this:

Error: AADSTS50020: User account ‘jdoe@myo365domain.com’ from external identity provider ‘https://sts.windows.net/1234567e-b123-4123-9112-912345678e51/’ is not supported for application ‘2123456f-b123-4123-9123-4123456789e5'. The account needs to be added as an external user in the tenant. Please sign out and sign in again with an Azure Active Directory user account.

An important note is that if you used "localhost" in step 7, the UI will not allow you to save the settings with an error "The App ID URI is not available. The App ID URI must be from a verified domain within your organization's directory."

Once you've enabled this, we're ready to make the code changes required.

First, you will need to install the OpenId package from nuget using the following command:

install-package microsoft.owin.security.openidconnect

Next, in the default Startup.Auth.cs file generated by the project template, you will need to add some additional code.

First, add this line:


Then, add this:

app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
    ClientId = "138C1130-4B29-4101-9C84-D8E0D34D222A",
    Authority = "https://login.windows.net/common",
    PostLogoutRedirectUri = "https://localhost:44301/",                
    Description = new AuthenticationDescription
        AuthenticationType = "OpenIdConnect",
        Caption = "Azure OpenId  Connect"
    TokenValidationParameters = new TokenValidationParameters
        // If you don't add this, you get IDX10205
        ValidateIssuer = false   

There are two very important notes.  The first is that the Authority must have the /common path and not your Azure AD *.onmicrosoft.com path.

The second note is that you must add the TokenValidationParameters and set ValidateIssuer to false.

If you don't set this to false, you'll get the following 500 error after you successfully authenticate against Azure AD with your organizational O365 account:

IDX10205: Issuer validation failed. Issuer: ‘https://sts.windows.net/F92E09B4-DDD1-40A1-AE24-D51528361FEC/’. Did not match: validationParameters.ValidIssuer: ‘null’ or validationParameters.ValidIssuers: ‘https://sts.windows.net/{tenantid}/’

I think that this is a hack and to be honest, I'm not quite certain of the consequences of not validating the issuer, but it seems that there aren't many answers on the web for this scenario yet.  Looking at the source code where the exception originates, you'll see the method that generates it:

public static string ValidateIssuer(string issuer, SecurityToken securityToken, TokenValidationParameters validationParameters)
    if (validationParameters == null)
        throw new ArgumentNullException("validationParameters");
    if (!validationParameters.ValidateIssuer)
        return issuer;
    if (string.IsNullOrWhiteSpace(issuer))
        throw new SecurityTokenInvalidIssuerException(string.Format(CultureInfo.InvariantCulture, ErrorMessages.IDX10211));
    // Throw if all possible places to validate against are null or empty
    if (string.IsNullOrWhiteSpace(validationParameters.ValidIssuer) && (validationParameters.ValidIssuers == null))
        throw new SecurityTokenInvalidIssuerException(string.Format(CultureInfo.InvariantCulture, ErrorMessages.IDX10204));
    if (string.Equals(validationParameters.ValidIssuer, issuer, StringComparison.Ordinal))
        return issuer;
    if (null != validationParameters.ValidIssuers)
        foreach (string str in validationParameters.ValidIssuers)
            if (string.Equals(str, issuer, StringComparison.Ordinal))
                return issuer;
    throw new SecurityTokenInvalidIssuerException(
        string.Format(CultureInfo.InvariantCulture, ErrorMessages.IDX10205, issuer, validationParameters.ValidIssuer ?? "null", Utility.SerializeAsSingleCommaDelimitedString(validationParameters.ValidIssuers)));

We're simply short circuiting the process.  It's clear that there is no matching issuer, but it's not quite clear to me yet where/how to configure that.

So what about the other social IdP's?  It's important to note that for Google, not only do you have to create a new client ID in the Google Developer Console, but you also need to enable the Google+ API:


You'll just get a bunch of useless error messages if you don't enable the API.

If you manage to get it all working, you should see the following options in the login screen:


And when you click it, you should be able to log in using the same organizational credentials that you use to connect to Office 365:


Filed under: .Net, MVC 1 Comment

Working with GUIDs in MongoDB and ASP.NET MVC3

Posted by Charles Chen

Just a small tip for those looking to use GUIDs as document IDs in MongoDB in conjunction with ASP.NET MVC3: it's a lot more straightforward than it may seem at the onset.

These examples are based off of the ASP.NET MVC3 tutorials...except with MongoDB instead of EF+SQL Server.

I've set up my model class like so:

public class Movie
    public Guid ID { get; set; }
    public string Title { get; set; }
    public DateTime ReleaseDate { get; set; }
    public string Genre { get; set; }
    public decimal Price { get; set; }

When the application creates an object and persists it to the database, you'll see that it shows up like this in the Mongo console (I've formatted the JSON for clarity):

> db.movies.find()
   "ReleaseDate":   ISODate("2011-05-11T04:00:00   Z"),

If you try to serialize this to JSON, instead of getting a GUID string, you'll get:

// Get a document
BsonDocument document = movies.FindOneAs<BsonDocument>();

// Direct to JSON
   "_id":new BinData(3,
   "n2FLBkAkhEOCkX42BGXRqg=="   ),
   "ReleaseDate":   ISODate("2011-05-11T04:00:00   Z"),

// With settings
JsonWriterSettings settings = new JsonWriterSettings{OutputMode = JsonOutputMode.JavaScript };

This is somewhat inconvenient if you want to work with it from a pure JavaScript perspective; I was hoping that it would have returned a GUID as a string instead.  I was also concerned that this meant that I'd have to manage this manually as well on the server side in my actions, but it turns out that it works better than expected.  The only caveat is that you have to use "_id" when creating queries; otherwise, you can use the GUID as-is and the Mongo APIs will convert it behind the scenes:

public ActionResult Details(Guid id)
    MongoCollection<Movie> movies = _database.GetCollection<Movie>("movies");

    // No need to mess with the GUID; use it as is.
    Movie movie = movies.FindOneAs<Movie>(Query.EQ("_id", id)); 

    return View(movie);

You can see the result below in the browser:

Note the properly formatted GUID in the URL

So far, so good with my little Mongo+MVC3 experiment 😀

Filed under: .Net, Mongo, MVC No Comments

Why ASP.NET (webforms) Sucks.

Posted by Charles Chen

Somehow, I got into a heated discussion at work today regarding the suckitude of ASP.NET web forms development model.  As a preface, I wrote Java for four years in a college, ASP in VBScript and JScript all throughout college, ASP after college, and then started working with ASP.NET when it released.

Undoubtedly, .NET and C# were a giant leap forward compared to ASP and JScript (my preferred scripting language for ASP).  But even from the start, I could never love ASP.NET.  Simple things that I used to do quite easily in ASP were now seemingly much more difficult and much more convoluted.  The HTML never quite came out the way I wanted it (remember the days when .NET wouldn't output cross browser compatible Javascript and markup?  And how that markup would always fail validation?  Yeah, I remember those days.) and it was a chore to get many development tasks done (had to overwrite this or implement that -- just to get a freaking icon in a table cell).  By the first year of use, I was already thinking that it was a terrible abomination of a framework; I never wanted to see a DataGrid ever again.

Ever since then, I've avoided writing applications in the traditional webforms model altogether.  First, I stumbled upon AJAX.NET, then I heard about this neat thing called "Atlas" (ASP.NET AJAX), then I picked up prototype, and finally, I have seen the light with jQuery (this is after writing my own Javascript for everything for the first several years of development).  I've never looked back; I've never once missed working with a web DataGrid.  I've never once missed working with most of the controls in ASP.NET web forms.  In fact, the only two four non-shitty controls worth using are the ScriptManager, Placeholder, LiteralControl, and Repeater.  That's it; that's where I draw the line.  UI controls?  They all suck.  Every.  Single.  One.  Why? 1) Because it mangles HTML output (ID's anyone?) which require ridiculous workarounds to do anything cool on the client side (i.e. writing the ClientID to the page?). 2) I hate viewstate...it's just extra...stuff (and yes, I'm intimately familiar with that "stuff" because I had to hack it to pieces at Factiva).

Don't get me wrong, I love .NET and C# to death; they're awesome (so awesome).  But ASP.NET webforms? I could smell coming from a mile away - like the stink of a dead skunk (or 20) in the middle of the road.  It's clever, I'll give you that, but it's been over-engineered to hell and back to account for the shittiness inherent in how it wants you to write web applications.

Finally, after what? 8, 9 years?  Microsoft has got it right with ASP.NET MVC.

What follows is the summary of my arguments as to why ASP.NET webforms suck (and it's only the tip of the iceberg!).

Undoubtedly, JSF and ASP.NET webforms suck giant elephant balls.  I mean giant balls of epic proportions of suck.  If this were the Richter scale, it would be a magnitude 10 level of suck (by the way, wiki describes that as "Epic.  Never recorded").

A simple google search for "JSF sucks" yields plenty of results.

Freddy D. has a nice summary list:

  • JSF + JSP = templates that are filled with way too much noise. f:verbatim? ack! Facelets helps here but it is still too hard to read.
  • The generated HTML is all kinds of black magic.
  • You can't have a simple link to a JSF bean with some parameters and invoking an action method, from outside the JSF context, without having to jump through all kinds of hoops.
  • Parameter binding and retrieval from a different page involves tricks and digging through the FacesContext.. yuk.
  • faces-config.xml. struts-config.xml all over again. Just too noisy and useless. What is the added value, really?
  • immediate="true"? are you kidding me?
  • the managed beans are supposed to be reusable POJOs. So why do you need to use SelectItem for select boxes? More useless code. This ties you to JSF for no good reason.
  • the data table is inept. Display Tag anyone?
  • writing your own component is way too much work.
  • want some AJAX? you'll need to add yet another framework to handle it, and if it doesn't work, you're SOL. if you want to write your own AJAX-enabled component.. read the item above and add a few more "way way WAY" in front of "too much work".
  • Even if you find ways to solve your problems, just knowing that it would be SO much easier with another framework, just adds to the frustration. Case in point, we switched to Stripes and our code is up to 30-50% more concise, clearer, easier to understand.. plus, as a small bonus, it actually works!
  • The principle of least surprise definitely does not apply when using JSF.

Well I'll be damned if those weren't some of the same reasons that ASP.NET webforms suck.

Since I'm not as familiar with JSF, I'll discuss this from the ASP.NET perspective.  First, why is ASP.NET the way it is?  Why did they design it like this?  Undoubtedly, one of the core reasons was because they thought VB6 developers were too damn stupid to know better.  To make these plebeian, lowest-of-the-low, bottom rung programmers "productive", they put together this abomination of an event model on top of a perfectly nice and awesome .NET and C#.  ASP.NET webforms are shitty beyond compare because of this.

To understand why this sucks, consider how you program for a client-server model when you are building a Windows forms application.  Your winform is responsible, clearly, for rendering data only.  It makes a service call that doesn't understand a damn thing about the winforms application, right?  The remote endpoint, the server side, cares about data and data only.  Once the service call completes, your client handles rendering of that data and putting it into grids and what not.  Your services called by the winforms client don't have silly "OnClick" handlers in the service implementation do they?  Can you imagine what that would be like if you had to write your WCF services or any sort of web service like that?  You'd have to do all this shitty state maintenance and pass around useless data (like what button was clicked); you would have to have UI logic in your service.  It sounds like it would suck to do that with your winforms to a WCF service.  This begs the question:  so why do you have them in your .aspx.cs?  .aspx.cs is an incredibly stupid model and absolutely forces you to mix your controller logic with your view logic, making it difficult to reuse, difficult to maintain, and difficult to understand.

Digest that for a moment.

(Granted, there are some differences in developing a winforms thin client and a web app and obviously some scenarios where it's advantageous to return generated/static markup.)

ASP.NET MVC is very, very far removed from JSP (I did a bit of JSP) since JSP was never an MVC design (and neither is ASP.NET webforms).  Out of the box JSP and ASP.NET webforms are both an almagam of the Page Controller and Template patterns with the shittiness of the faux event model layered on top.  ASP.NET MVC is a true MVC model (or at least it's pretty damn close) that uses a Front Controller pattern and truly separated concerns between the view, the model, and the controller.  Most of the shittiness and pain with ASP.NET stems from the fact that the page controller pattern violates all sorts of seperations of concern as it encourages mashing up code that should be isolated in a view with code that should be isolated in a controller.  The end result is a giant heaping pile of poo.  The control and event model only make the situation worse by requiring this ugly, terrible thing we've all come to hate known as viewstate.

I'm convinced that these frameworks were created for numbskull rent-a-coders because they're too lazy/stupid/incapable of grasping basic HTML, Javascript, CSS, and simple DOM.  Look, at the end of the day, if you're going to be a web developer and you're not going to put in the time to master HTML, CSS, and Javascript to some degree, you're not doing it right.  That would be like a baker that didn't want to learn the basic composition of breads and dough and the chemical reactions that make tasty baked goods out of simple ingredients like flour, yeast, eggs, water, salt, and sugar.  Web developers attached to ASP.NET web controls and fear Javascript (and I know some) are like "bakers" who open a "bakery" and buy their products from Costco and repackage them.  I guess it's efficient and productive, but at the end of the day, such a "baker" is constrained to a very small universe of possibilities...how boring.

I've come to beleive that ASP.NET webforms continue to perpetuate generations of developers who have no idea how all this "magic" works and when presented with a design scenario that calls for a truly innovative UI, they stumble because they can't figure out how to do it without a control to hold their hand...boo-hoo (I'm amazed when people are amazed by some stupid ASP.NET web control without realizing how easy it is to accomplish the same thing with some jQuery goodness (or conversely, how hard it was before we had nice things like prototype and jQuery)).  The list of companies that don't screw around with these stupid frameworks probably have some of the most brilliant developers working for them:  Yahoo!, Google, Facebook, Amazon, etc. -- these guys long ago learned the lesson that ASP.NET webforms/JSF is for simpletons (or masochists).

Okay, I concede that it's great for initial productivity.  Certainly, most developers can probably throw up a page with a grid with some databound recordset much faster than I could write a page with the same set of features.  But I wager that my implementation would be cleaner, easier to read, easier to understand, easier to maintain, easier to reuse, and easier to work with once the need arises to address a usage scenario not supported by the grid out of the box.  If first run development speed is your only concern, then I lose every time because I'm concerned about doing it right, making it maintainable, and making it easy to understand the programming model.  If you care about those things, then it's worth it to do it right.

ASP.NET MVC will be the litmus test that will differentiate the competent developers from the rent-a-coders and, hopefully, will come to replace webforms as the primary model of web application development on the .NET framework.  The "stateful web" was an experimental failure of epic proportions to satisfy the simple minds that couldn't wrap their heads around the fact that the web is inherently stateless.  Let's move on from that dark, dank, dreary past and bask in the light of ASP.NET MVC!

Filed under: .Net, MVC, Rants 10 Comments

I Like Jeffrey Palermo’s Prediction…

Posted by Charles Chen

I've been playing around with ASP.NET MVC for about a week now and it does everything right that ASP.NET web forms did so wrong.  I've hated ASP.NET web forms with a passion as soon as I realized that the model was terrible for the majority of development shops in terms of managing unmanageable code jumbles -- huge methods written on event handlers...

Don't get me wrong, ASP.NET 1.0 was a huge step up from classic ASP, but it has exploded into this huge culture of control based RAD developers.  Not that you couldn't roll your own MVC pattern for ASP.NET, but having it as an officially supported development model should help bring more web developers out from the grips of the dark side.

Most consultants (even "senior" ones) simply take the quick-and-dirty route when it comes to ASP.NET web forms development, dragging and dropping controls all day long.  Not that it's a bad thing...for prototyping, but it quickly devolves into hard to manage, hard to maintain, and difficult to test codebases with very low levels of reusability.  This is especially true once you roll on junior or mid level developers to a web project.

Earlier in the year, Jeffrey Palermo predicted that MVC would replace web forms as the dominant web application development model on the .NET platform.  With the recent news of MVC 2, Palermo reasserts his prediction with even greater conviction.  I was already long convinced that ASP.NET web forms was a craptastic model for web application development, but I had some skepticism about MVC (after my pretty awesome experience with Django).  This past week has convinced me that MVC kicks ass and I hope that Jeffrey's prediction is right.

I wholeheartedly agree; I simply can't wait to dump ASP.NET web forms.

Filed under: .Net, MVC No Comments