Search code examples
c#asp.net-mvcazure-active-directoryowin

How to get error reason from failed authentication using Microsoft.Owin?


I have the following code in Startup.Auth.cs :

app.UseOpenIdConnectAuthentication(

                        new OpenIdConnectAuthenticationOptions
                        {
                            ClientId = myclientId,
                            Authority = authority,
                            PostLogoutRedirectUri = mypostLogoutRedirectUri,
                           ,

                            

                            Notifications = new OpenIdConnectAuthenticationNotifications
                            {
                                AuthenticationFailed = (context) =>
                                {
                                    context.HandleResponse();
                                    string error = ""; //<-- what goes here?
                                    context.OwinContext.Response.Redirect("/Home/auth_error?error_msg=" + error);
                                    return Task.FromResult(0);
                                },
                                SecurityTokenValidated = (context) =>
                                {
                                    string name = context.AuthenticationTicket.Identity.Name;
                                    context.AuthenticationTicket.Identity.AddClaim(new Claim(ClaimTypes.Name, name, string.Empty));
                                    return System.Threading.Tasks.Task.FromResult(0);
                                }
                            }
                        });

What i want to do is display an error message with the reason why authentication failed. How can i get all the appropriate information in AuthenticationFailed segment as a string?


Solution

  • Your context should have your message in context.Exception.Message.

    See: https://learn.microsoft.com/en-us/previous-versions/aspnet/mt180967(v=vs.113)