Okay, so the title may not be the clearest thing ever here today, but it’s tough to do in just a few words, so let me explain the scenario a little more fully. Suppose you create an ASP.NET application and you configure it to be secured by Azure Active Directory. When you do that you have to configure your right to request Azure AD permissions to sign-on and read the user’s profile. This is the minimum right needed to have someone use Azure AD to login to your application, so naturally everyone will agree to this, right?? 🙂
Well, as you can probably guess from this post, not always. So what happens when a user sees that consent page from Azure AD at login time and then decides no, I don’t want to let you sign me in, so they hit cancel? Well the out of the box behavior is that you get an unhandled exception in your ASP.NET application. This of course brings up the awesome yellow screen of indecipherable death. If you’re running it locally you can at least see the error message, which looks something like this:
So, how to fix right? Well try as I might, the Bing Gods were not with me this day when I decided to try and figure this out. In fact for future search engine happiness, the error is access_denied and comes from Microsoft.IdentityModel.Protocols.OpenIdConnectProtocolException. With a little trial and error I was able to figure out the way to fix this issue so wanted to document here for those of you stuck in a similar boat.
What you need to do is go back to your Startup.Auth.cs file. You should have something configured in there for OpenIdConnect that starts out something like this:
What you want to do is configure one of the NotificationOptions, which you configure inside the OpenIdConnectAuthenticationOptions like this:
Notifications = new OpenIdConnectAuthenticationNotifications()
To deal with the scenario of someone canceling out of granting permissions during login you need to add a handler for the AuthenticationFailed notification. Here’s what mine looks like:
AuthenticationFailed = (context) =>
//this section added to handle scenario where user logs in, but cancels consenting to rights to read directory profile
string appBaseUrl = context.Request.Scheme + “://” + context.Request.Host + context.Request.PathBase;
context.ProtocolMessage.RedirectUri = appBaseUrl + “/”;
//this is where the magic happens
Essentially what’s happening there is if someone cancels it hits this notification handler. I just figure out what the root Url of my application is, which I’ve pushed into the context.ProtocolMessage.RedirectUri property (which I actually liberally stole from my handler for RedirectToIdentityProvider). Then I redirect somewhere else in my site that doesn’t require authentication, which in this case is my home page.
That’s it. I don’t really see this covered in any of the sample code locations I usually hit up for Azure AD code so thought you might find it useful.