ASP.NET Core OAuth Facebook cancel causes 500 fix

If you’re using ASP.NET Core built-in authentication to allow your users to sign up / login to your web application using alternative providers, Microsoft provides various out of the box, such as Microsoft, Google, Twitter and Facebook.

Chances are you have something like the following in your startup.cs

services.AddFacebook(options=> ...)

This works pretty nicely. All you need are you keys and secrets (hello Urban Cookie Collective) and all should rock.

However, an issue arises if your user clicks ‘Sign in with <x>’, which (if they are not already signed-in) takes them to that app to sign in, but if they then cancel that (e.g., clicking the ‘Not Now’ link on the Facebook screen) can result in a ghastly 500 error.

System.Exception: An error was encountered while handling the remote login. —> System.Exception: Access was denied by the resource owner or by the remote server. — End of inner exception stack trace — at Microsoft.AspNetCore.Authentication.RemoteAuthenticationHandler`1.HandleRequestAsync() at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context) …

To work around this, you need to be able to handle the error, and fortunately this is fairly straight-forward by effectively catching the error and just redirecting to e.g., home.

services.AddFacebook(options =>
options.Events = new OAuthEvents
{
 OnRemoteFailure = context =>
 {
   context.Response.Redirect("/");
   context.HandleResponse();

   return Task.FromResult(0);
 }
};

Job done.

Be the first to comment

Leave a Reply

Your email address will not be published.


*