예제 #1
0
        private async Task HandleOnRemoteFailure(RemoteFailureContext context)
        {
            context.Response.StatusCode  = 500;
            context.Response.ContentType = "text/html";
            await context.Response.WriteAsync("<html><body>");

            await context.Response.WriteAsync("A remote failure has occurred: <br>" +
                                              context.Failure.Message.Split(Environment.NewLine).Select(s => HtmlEncoder.Default.Encode(s) + "<br>").Aggregate((s1, s2) => s1 + s2));

            if (context.Properties != null)
            {
                await context.Response.WriteAsync("Properties:<br>");

                foreach (var pair in context.Properties.Items)
                {
                    await context.Response.WriteAsync($"-{ HtmlEncoder.Default.Encode(pair.Key)}={ HtmlEncoder.Default.Encode(pair.Value)}<br>");
                }
            }

            await context.Response.WriteAsync("<a href=\"/\">Home</a>");

            await context.Response.WriteAsync("</body></html>");

            // context.Response.Redirect("/error?FailureMessage=" + UrlEncoder.Default.Encode(context.Failure.Message));

            context.HandleResponse();
        }
예제 #2
0
 private static Task HandleRemoteLoginFailure(RemoteFailureContext ctx)
 {
     ctx.HttpContext.Items["ErrorMessage"] = ctx.Failure.Message;
     ctx.Response.Redirect("/Account/Login");
     ctx.HandleResponse();
     return(Task.CompletedTask);
 }
예제 #3
0
        public Task OnRemoteFailure(RemoteFailureContext context)
        {
            context.HandleResponse();
            // Handle the error code that Azure Active Directory B2C throws when trying to reset a password from the login page
            // because password reset is not supported by a "sign-up or sign-in policy".
            // Below is a sample error message:
            // 'access_denied', error_description: 'AADB2C90118: The user has forgotten their password.
            // Correlation ID: f99deff4-f43b-43cc-b4e7-36141dbaf0a0
            // Timestamp: 2018-03-05 02:49:35Z
            //', error_uri: 'error_uri is null'.
            if (context.Failure is OpenIdConnectProtocolException && context.Failure.Message.Contains("AADB2C90118"))
            {
                // If the user clicked the reset password link, redirect to the reset password route
                context.Response.Redirect($"{context.Request.PathBase}/AzureADB2C/Account/ResetPassword/{SchemeName}");
            }
            // Access denied errors happen when a user cancels an action on the Azure Active Directory B2C UI. We just redirect back to
            // the main page in that case.
            // Message contains error: 'access_denied', error_description: 'AADB2C90091: The user has cancelled entering self-asserted information.
            // Correlation ID: d01c8878-0732-4eb2-beb8-da82a57432e0
            // Timestamp: 2018-03-05 02:56:49Z
            // ', error_uri: 'error_uri is null'.
            else if (context.Failure is OpenIdConnectProtocolException && context.Failure.Message.Contains("access_denied"))
            {
                context.Response.Redirect($"{context.Request.PathBase}/");
            }
            else
            {
                context.Response.Redirect($"{context.Request.PathBase}/AzureADB2C/Account/Error");
            }

            return(Task.CompletedTask);
        }
예제 #4
0
        private async Task HandleOnRemoteFailure(RemoteFailureContext context)
        {
            context.Response.StatusCode  = 500;
            context.Response.ContentType = "text/html";
            await context.Response.WriteAsync("<html><head><link rel='preconnect' href='https://fonts.gstatic.com'><link href='https://fonts.googleapis.com/css2?family=Roboto:ital,wght@0,100;0,300;0,400;0,500;0,700;0,900;1,100;1,300;1,400;1,500;1,700;1,900&display=swap' rel ='stylesheet'><link rel='stylesheet' href='css/bootstrap.min.css'/><link rel='stylesheet' href='css/style.css'/></head><body><div class='login-wrapper'><div class='container'><div class='logo-wrapper'><img class='logo-img' src='image/logo.png' alt='' /></div>");

            await context.Response.WriteAsync("<div><div class='login-form mb-4' style=height:50% !important;><h4>You have denied the application permissions.<br> Please try again.</h4><br>");

            //await context.Response.WriteAsync("A remote failure has occurred: <br>" +
            //    context.Failure.Message.Split(Environment.NewLine).Select(s => HtmlEncoder.Default.Encode(s) + "<br>").Aggregate((s1, s2) => s1 + s2));

            //if (context.Properties != null)
            //{
            //    await context.Response.WriteAsync("Properties:<br>");
            //    foreach (var pair in context.Properties.Items)
            //    {
            //        await context.Response.WriteAsync($"-{ HtmlEncoder.Default.Encode(pair.Key)}={ HtmlEncoder.Default.Encode(pair.Value)}<br>");
            //    }
            //}

            await context.Response.WriteAsync("<h5><a href=\"/\">Home</a></h5></div></div></div>");

            await context.Response.WriteAsync("</body></html>");

            // context.Response.Redirect("/error?FailureMessage=" + UrlEncoder.Default.Encode(context.Failure.Message));

            context.HandleResponse();
        }
예제 #5
0
        public Task OnRemoteFailure(RemoteFailureContext context)
        {
            context.HandleResponse();
            // Handle the error code that Azure AD B2C throws when trying to reset a password from the login page
            // because password reset is not supported by a "sign-up or sign-in policy"
            if (context.Failure is OpenIdConnectProtocolException && context.Failure.Message.Contains("AADB2C90118"))
            {
                context.Response.Redirect("/Session/ResetPassword");
            }
            else if (context.Failure is OpenIdConnectProtocolException &&
                     context.Failure.Message.Contains("access_denied"))
            {
                context.Response.Redirect("/");
            }
            else
            {
                // https://github.com/Azure-Samples/active-directory-b2c-dotnetcore-webapp/issues/29
                var message = Regex.Replace(context.Failure.Message, @"[^\u001F-\u007F]+", string.Empty);
                context.Response.Redirect("/Home/Error?message=" + message);
                // context.Response.Redirect("/Home/Error?message=" + context.Failure.Message);

                /* if you have this exception:
                 * Message contains error: 'invalid_request', error_description: 'AADB2C90205: This application does not have sufficient permissions against this web resource to perform the operation.
                 * Correlation ID: 073af821-4d5c-4db1-9d51-5f57d2c148e2Timestamp: 2018-04-09 09:37:13Z', error_uri: 'error_uri is null'.
                 *
                 * Please check this https://github.com/Azure-Samples/active-directory-b2c-javascript-msal-singlepageapp/issues/4
                 */
            }

            return(Task.FromResult(0));
        }
예제 #6
0
        public static async Task HandleOnRemoteFailure(RemoteFailureContext context)
        {
            context.Response.StatusCode  = 500;
            context.Response.ContentType = "text/html";
            await context.Response.WriteAsync("<html><body>");

            await context.Response.WriteAsync("A remote failure has occurred: " + UrlEncoder.Default.Encode(context.Failure.Message) + "<br>");

            /* unkown issue
             * if (context.Properties != null)
             * {
             *  await context.Response.WriteAsync("Properties:<br>");
             *  foreach (var pair in context.Properties.Items)
             *  {
             *      await context.Response.WriteAsync($"-{ UrlEncoder.Default.Encode(pair.Key)}={ UrlEncoder.Default.Encode(pair.Value)}<br>");
             *  }
             * }*/

            await context.Response.WriteAsync("<a href=\"/\">Home</a>");

            await context.Response.WriteAsync("</body></html>");

            // context.Response.Redirect("/error?FailureMessage=" + UrlEncoder.Default.Encode(context.Failure.Message));

            context.HandleResponse();
        }
        private static Task HandleOnRemoteFailure(RemoteFailureContext context)
        {
            context.Response.Redirect(context.Properties.RedirectUri);
            context.HandleResponse();

            return(Task.FromResult(0));
        }
            /// <summary>
            /// Method to handle the remote failures if any from authentication server
            /// </summary>
            /// <param name="context"> The RemoteFailureContext that contains the failure error message </param>
            /// <returns> Throw the exception with the received failure message from remote </returns>
            public Task OnRemoteFailure(RemoteFailureContext context)
            {
                context.HandleResponse();

                // Throw the exception to log the failure message in ApplicationInsights AND respond user with system failure message
                // This is further handled by ExceptionAttribute class
                throw (new Exception(context.Failure.Message));
            }
예제 #9
0
파일: Startup.cs 프로젝트: detmach/Teknik
 private async Task HandleOnRemoteFailure(RemoteFailureContext context)
 {
     if (context.Failure.Message.Contains("access_denied"))
     {
         context.Response.StatusCode = 403;
     }
     context.HandleResponse();
 }
예제 #10
0
        public Task HandleRemoteFailure(RemoteFailureContext context)
        {
            this.logger.LogError(EventIDs.ExternalAuthNProviderError, context.Failure, LogMessages.AuthNProviderError);
            context.HandleResponse();
            context.Response.Redirect($"/Home/AuthNError?messageid={(int)AuthNFailureMessageID.ExternalAuthNProviderError}");

            return(Task.CompletedTask);
        }
예제 #11
0
        // Handle sign-in errors differently than generic errors.
        private Task OnAuthenticationFailed(RemoteFailureContext context)
        {
            context.HandleResponse();
            var message = Regex.Replace(context.Failure?.Message, @"[^\u001F-\u007F]+", string.Empty);

            context.Response.Redirect("/Home/Error?message=" + message);
            return(Task.FromResult(0));
        }
예제 #12
0
        public override Task RemoteFailure(RemoteFailureContext context)
        {
            _log.WriteErrorAsync("Authentication", "RemoteFailure", context.Failure.Message + context.Failure.InnerException, context.Failure).Wait();

            context.HandleResponse();
            context.Response.Redirect("/Home/AuthenticationFailed");

            return(Task.FromResult(0));
        }
예제 #13
0
        private async Task HandleOnRemoteFailure(RemoteFailureContext context)
        {
            var url = context.Request.Host.ToString();

            context.HandleResponse();
            await Task.Run(() =>
            {
                context.Response.Redirect("/Home", true);
            });
        }
예제 #14
0
        // TODO: Replace with better implementation, use built-in error handling.
        /// <summary>
        /// When an oath authorization or token request fails.
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public static async Task HandleOnRemoteFailure(RemoteFailureContext context)
        {
            var handler = context.HttpContext.RequestServices.GetRequiredService <JsonErrorHandler>();

            context.Response.StatusCode  = (int)HttpStatusCode.InternalServerError;
            context.Response.ContentType = "application/json";
            await context.Response.WriteAsync(handler.Serialize(new OauthException(context.Failure)));

            context.HandleResponse();
        }
        /// <summary>
        /// 远程服务器(如授权失败时)错误处理程序。
        /// </summary>
        /// <param name="remoteFailureContext"></param>
        /// <returns></returns>
        private Task OnRemoteFailureHandler(RemoteFailureContext remoteFailureContext)
        {
            remoteFailureContext.HandleResponse();

            if (!remoteFailureContext.HttpContext.Response.HasStarted)
            {
                //TODO 写入日志
                //TODO 向HttpContext.Response写入友好的错误提示信息展示给用户
            }
            return(Task.CompletedTask);
        }
        public static Task HandleRemoteFailure(this RemoteFailureContext context)
        {
            Log.Error(
                context.Failure,
                "External authentication remote failure. {Scheme}",
                context.Scheme.Name);

            context.Response.RedirectExternalError(context.Scheme.Name, context.Properties);
            context.HandleResponse();

            return(Task.CompletedTask);
        }
예제 #17
0
 private Task HandleRemoteFailure(RemoteFailureContext context)
 {
     if (context.Failure.Message.ToLower().Contains("correlation"))
     {
         context.HandleResponse();
         context.Response.Redirect("/Home/CorrelationError");
         return(Task.FromResult(0));
     }
     else
     {
         throw context.Failure;
     }
 }
예제 #18
0
#pragma warning disable CS1998 
        private async Task HandleOnRemoteFailure(RemoteFailureContext context)
        {
            var msg = context.Failure.Message.Split(Environment.NewLine).Select(s => s + Environment.NewLine).Aggregate((s1, s2) => s1 + s2);

            if (context.Properties != null)
                foreach (var pair in context.Properties.Items)
                    msg = $"{msg}{Environment.NewLine}-{pair.Key}={pair.Value}";

            Log.Logger.Error($"External authentication error: {msg}");

            context.Response.Redirect($"/externalauth/error/{ErrorEnum.ExternalAuthError}");

            context.HandleResponse();
        }
예제 #19
0
 public Task OnRemoteFailure(RemoteFailureContext context)
 {
     context.HandleResponse();
     if (context.Failure is OpenIdConnectProtocolException && context.Failure.Message.Contains("AADB2C90118"))
     {
         context.Response.Redirect("/Session/ResetPassword"); //todo: add this
     }
     else if (context.Failure is OpenIdConnectProtocolException && context.Failure.Message.Contains("access_denied"))
     {
         context.Response.Redirect("/");
     }
     else
     {
         context.Response.Redirect("/Home/Error?message=" + Uri.EscapeDataString(context.Failure.Message));
     }
     return(Task.FromResult(0));
 }
        /// <summary>
        /// Handles a remote failure.
        /// </summary>
        /// <typeparam name="T">The type of the secure data.</typeparam>
        /// <param name="context">The failure context.</param>
        /// <param name="provider">The authentication provider.</param>
        /// <param name="secureDataFormat">The secure data format.</param>
        /// <param name="logger">The <see cref="ILogger"/> to use.</param>
        /// <param name="propertiesProvider">A delegate to a method to retrieve authentication properties from the secure data.</param>
        /// <returns>
        /// A <see cref="Task"/> representing the completion of the operation.
        /// </returns>
        public static Task HandleRemoteFailure <T>(
            RemoteFailureContext context,
            string provider,
            ISecureDataFormat <T> secureDataFormat,
            ILogger logger,
            Func <T, IDictionary <string, string>?> propertiesProvider)
        {
            string?path = GetSiteErrorRedirect(context, secureDataFormat, propertiesProvider);

            if (string.IsNullOrEmpty(path) ||
                !Uri.TryCreate(path, UriKind.Relative, out Uri? notUsed))
            {
                path = "/";
            }

            SiteMessage message;

            if (WasPermissionDenied(context))
            {
                message = SiteMessage.LinkDenied;
                logger.LogTrace("User denied permission.");
            }
            else
            {
                message = SiteMessage.LinkFailed;

                var    eventId    = default(EventId);
                string errors     = string.Join(";", context.Request.Query.Select((p) => $"'{p.Key}' = '{p.Value}'"));
                string logMessage = $"Failed to sign-in using '{provider}': '{context.Failure.Message}'. Errors: {errors}.";

                if (IsCorrelationFailure(context))
                {
                    // Not a server-side problem, so do not create log noise
                    logger.LogTrace(eventId, context.Failure, logMessage);
                }
                else
                {
                    logger.LogError(eventId, context.Failure, logMessage);
                }
            }

            context.Response.Redirect($"{path}?Message={message}");
            context.HandleResponse();

            return(Task.CompletedTask);
        }
        public async Task OnRemoteFailure(RemoteFailureContext context)
        {
            var requestId = Activity.Current?.Id ?? context.HttpContext.TraceIdentifier;

            _logger.LogError(context.Failure, "[Request: {requestId}] Authentication Failure", requestId);
            if (_hostingEnvironment.IsDevelopment())
            {
                // Handle in-place and report the error
                context.Response.StatusCode = StatusCodes.Status500InternalServerError;
                await context.Response.WriteAsync(context.Failure.ToString());
            }
            else
            {
                var url = $"/Error?failedRequestId={requestId}";
                context.Response.Redirect(url);
                context.HandleResponse();
            }
        }
        public override Task RemoteFailure(RemoteFailureContext context)
        {
            context.HandleResponse();
            if (context.Failure is ResponseSuccessException)
            {
                context.Response.Redirect("/Responses/Success?message=El Token se guardo de manera exitosa!!");
            }
            else if (context.Failure is ResponseFailedException)
            {
                ResponseFailedException responseFailedException = context.Failure as ResponseFailedException;
                context.Response.Redirect($"/Responses/Error?message={responseFailedException.Message}");
            }
            else
            {
                context.Response.Redirect($"/Responses/Error?message=Hubo un error interno: {context.Failure.Message}");
            }

            return(Task.FromResult(0));
        }
 public Task OnRemoteFailure(RemoteFailureContext context)
 {
     context.HandleResponse();
     // Handle the error code that Azure AD B2C throws when trying to reset a password from the login page
     // because password reset is not supported by a "sign-up or sign-in policy"
     if (context.Failure is OpenIdConnectProtocolException && context.Failure.Message.Contains("AADB2C90118"))
     {
         // If the user clicked the reset password link, redirect to the reset password route
         context.Response.Redirect("/Session/ResetPassword");
     }
     else if (context.Failure is OpenIdConnectProtocolException && context.Failure.Message.Contains("access_denied"))
     {
         context.Response.Redirect("/");
     }
     else
     {
         context.Response.Redirect("/Home/Error?message=" + Uri.EscapeDataString(context.Failure.Message));
     }
     return(Task.FromResult(0));
 }
        private static async Task HandleOnRemoteFailure(RemoteFailureContext context)
        {
            var response = context.Response;

            response.StatusCode  = 500;
            response.ContentType = "text/html; charset=utf-8";
            await response.WriteAsync("<html><body>");

            await response.WriteAsync("<h1>A remote failure has occurred</h1>");

            await response.WriteAsync(HtmlEncoder.Default.Encode(context.Failure.Source ?? "Unknown") + ": " + HtmlEncoder.Default.Encode(context.Failure.Message) + "<br>");

            await response.WriteAsync("<a href=\"/\">Home</a>");

            await response.WriteAsync("</body></html>");

            //response.Redirect("/error?FailureMessage=" + UrlEncoder.Default.Encode(context.Failure.Message));

            context.HandleResponse();
        }
예제 #25
0
 public Task OnRemoteFailure(RemoteFailureContext context)
 {
     context.HandleResponse();
     // Handle the error code that Azure AD B2C throws when trying to reset a password from the login page
     // because password reset is not supported by a "sign-up or sign-in policy"
     if (context.Failure is OpenIdConnectProtocolException && context.Failure.Message.Contains("AADB2C90118"))
     {
         // If the user clicked the reset password link, redirect to the reset password route.
         context.Response.Redirect("/account/resetpassword");
     }
     else if (context.Failure is OpenIdConnectProtocolException && context.Failure.Message.Contains("access_denied"))
     {
         context.Response.Redirect("/");
     }
     else
     {
         context.Response.Redirect("/home/error?message=" + WebUtility.UrlEncode(context.Failure.Message));
     }
     return(Task.CompletedTask);
 }
예제 #26
0
        public async Task ProcessFail(RemoteFailureContext ctx)
        {
            await Task.Factory.StartNew(() => {
                ctx.HandleResponse();
                var url = AuthenticationConfig.UriError + UrlEncoder.Default.Encode(ctx.Failure.Message);

                if (ctx.Failure.Message.StartsWith(RedirectKey) && AuthenticationConfig.AuthenticationType == AuthenticationType.Cookie)
                {
                    url = AuthenticationConfig.UriCookieSucess;
                }

                if (ctx.Failure.Message.StartsWith(RedirectKey) && AuthenticationConfig.AuthenticationType == AuthenticationType.Token)
                {
                    var split = ctx.Failure.Message.Split('|');
                    url       = AuthenticationConfig.UriTokenSucess + split.Last();
                }

                ctx.Response.Redirect(url);
            });
        }
        private static Task HandleRemoteFailure(RemoteFailureContext context)
        {
            var logger        = context.HttpContext.RequestServices.GetRequiredService <ILogger <Startup> >();
            var contextAsJson = string.Empty;

            try
            {
                contextAsJson = JsonConvert.SerializeObject(context);
            }
            catch (Exception)
            {
            }

            logger.LogError(context.Failure,
                            $"An error has occurred while authenticating user against identity server. JSON: {contextAsJson}.");

            context.HandleResponse();
            context.Response.Redirect("/error/authfailure");

            return(Task.CompletedTask);
        }
예제 #28
0
        public Task OnRemoteFailure(RemoteFailureContext context)
        {
            context.HandleResponse();

            bool isOidcProtocolException = context.Failure is OpenIdConnectProtocolException;

            // Handle the error code that Azure Active Directory B2C throws when trying to reset a password from the login page
            // because password reset is not supported by a "sign-up or sign-in user flow".
            // Below is a sample error message:
            // 'access_denied', error_description: 'AADB2C90118: The user has forgotten their password.
            // Correlation ID: f99deff4-f43b-43cc-b4e7-36141dbaf0a0
            // Timestamp: 2018-03-05 02:49:35Z
            // ', error_uri: 'error_uri is null'.
            string message = context.Failure?.Message ?? string.Empty;

            if (isOidcProtocolException && message.Contains(ErrorCodes.B2CForgottenPassword, StringComparison.OrdinalIgnoreCase))
            {
                // If the user clicked the reset password link, redirect to the reset password route
                context.Response.Redirect($"{context.Request.PathBase}{Options.ResetPasswordPath}/{SchemeName}");
            }

            // Access denied errors happen when a user cancels an action on the Azure Active Directory B2C UI. We just redirect back to
            // the main page in that case.
            // Message contains error: 'access_denied', error_description: 'AADB2C90091: The user has canceled entering self-asserted information.
            // Correlation ID: d01c8878-0732-4eb2-beb8-da82a57432e0
            // Timestamp: 2018-03-05 02:56:49Z
            // ', error_uri: 'error_uri is null'.
            else if (isOidcProtocolException && message.Contains(ErrorCodes.AccessDenied, StringComparison.OrdinalIgnoreCase))
            {
                context.Response.Redirect($"{context.Request.PathBase}/");
            }
            else
            {
                _errorAccessor.SetMessage(context.HttpContext, message);

                context.Response.Redirect($"{context.Request.PathBase}{Options.ErrorPath}");
            }

            return(Task.CompletedTask);
        }
예제 #29
0
        private async Task HandleOnRemoteFailure(RemoteFailureContext context)
        {
            context.Response.StatusCode  = 500;
            context.Response.ContentType = "text/html";
            await context.Response.WriteAsync("<html><body>");

            await context.Response.WriteAsync("A remote failure has occurred: " + UrlEncoder.Default.Encode(context.Failure.Message) + "<br>");

            if (context.Properties != null)
            {
                await context.Response.WriteAsync("Properties:<br>");

                foreach (KeyValuePair <string, string> pair in context.Properties.Items)
                {
                    await context.Response.WriteAsync($"-{ UrlEncoder.Default.Encode(pair.Key)}={ UrlEncoder.Default.Encode(pair.Value)}<br>");
                }
            }

            await context.Response.WriteAsync("<a href=\"/\">Home</a>");

            await context.Response.WriteAsync("</body></html>");

            context.HandleResponse();
        }
예제 #30
0
 private static Task HandleRemoteLoginFailure(RemoteFailureContext ctx)
 {
     ctx.Response.Redirect("/Login");
     ctx.HandleResponse();
     return(Task.CompletedTask);
 }