.Net Core Identity 2 Provider login Cancel leads to unhandled exception

倾然丶 夕夏残阳落幕 提交于 2019-12-05 11:40:44

There's a Github issue that explains what's happening here in more detail, with a bit of information as to why it's happening and even an indication that this won't be "fixed":

Handling the RemoteFailure event is the right thing to do. We should update our docs/samples to show how to handle that event and at least show a more appropriate message to the user. The error page sample could include a link to enabled the user to try logging in again.

Unfortunately it's difficult to implement this event in a very generic way that's also super useful because each remote auth provider has its own behavior for different types of failures.

The workaround for this (as quoted above) is to handle the RemoteFailure event:

services.AddAuthentication().AddOAuth("LinkedIn", "LinkedIn", c => {
    // ...
    c.Events.OnRemoteFailure = ctx =>
    {
        // React to the error here. See the notes below.
        return Task.CompletedTask;
    }
    // ...
});

ctx is an instance of RemoteFailureContext, which includes an Exception property describing what went wrong. ctx also contains a HttpContext property, allowing you to perform redirects, etc, in response to such exceptions.

I've found the following to work well for me, based on this and similar to Kirk Larkin's answer. The part that took a little figuring out was where to redirect to, without causing problems for subsequent login attempts.

services.AddAuthentication().AddOAuth("LinkedIn", "LinkedIn", c =>
{
    ...
    c.Events = new OAuthEvents()
    {
        OnRemoteFailure = (context) =>
        {
            context.Response.Redirect(context.Properties.GetString("returnUrl"));
            context.HandleResponse();
            return Task.CompletedTask;
        }
    };
};
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!