public override Task AuthenticationFailed(AuthenticationFailedContext context) { string errorMessage = ""; if (context.Exception is SecurityTokenException) { errorMessage = "Token expired"; } else if (context.Exception is SecurityTokenInvalidIssuerException) { errorMessage = "Invalid issuer"; } else { errorMessage = "Invalid token"; } context.Response.StatusCode = 401; context.Response.ContentType = "application/json"; var resp = new { ErrorCode = 401, message = errorMessage }; var options = new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() }; context.Response.WriteAsync(JsonConvert.SerializeObject(resp, options)).Wait(); return(Task.CompletedTask); }
// AuthenticationFailed, try again using the refreshToken public override async Task AuthenticationFailed(AuthenticationFailedContext context) { try { GetTokensFromRequestContext(context.HttpContext.Request, out string token, out string refreshToken); if (!string.IsNullOrEmpty(token) && !string.IsNullOrEmpty(refreshToken)) { JwtWithClaims newToken = await jwtManager.ExchangeRefreshToken(token, refreshToken); context.Principal = newToken.Claims; // if there was a cookie, then set again the cookie with the new value if (!string.IsNullOrEmpty(context.HttpContext.Request.Cookies[AppConstants.SessionCookie])) { context.HttpContext.SetCookie(AppConstants.SessionCookie, Newtonsoft.Json.JsonConvert.SerializeObject(new Dictionary <string, string> { [AppConstants.Token] = newToken.JsonWebToken.Token, [AppConstants.RefreshToken] = newToken.JsonWebToken.RefreshToken })); } // If everything goes ok set request principal (In this point authentication is done and ok) context.Success(); } } catch { return; } return; }
/// <summary> /// Wird ausgeführt, wenn die Verbindung zur API fehlgeschlagen ist. /// </summary> /// <param name="context">Ein <see cref="AuthenticationFailedContext"/> mit weiteren Informationen.</param> /// <returns></returns> private Task OnHubAuthorizationFailed(AuthenticationFailedContext context) { MessageBox.Show(context.Error.Message, "Connection Error", MessageBoxButton.OK, MessageBoxImage.Error); SetHubControls(false, false); context.Handled(); return(Task.CompletedTask); }
public override async Task AuthenticationFailed(AuthenticationFailedContext context) { await base.AuthenticationFailed(context); //context.Response.StatusCode = StatusCodes.Status401Unauthorized; //return Task.CompletedTask; }
/// <inheritdoc/> public override async Task AuthenticationFailed(AuthenticationFailedContext context) { if (!await ProcessAuthenticationFailedAsync(context)) { await base.AuthenticationFailed(context); } }
public async Task <AuthenticationFailedContext> HandleAuthenticationFailed(HttpContext context, AuthenticationScheme scheme, SpidOptions options, ResponseType message, Exception exception) { var authenticationFailedContext = new AuthenticationFailedContext(context, scheme, options, message, exception); await _events.AuthenticationFailed(authenticationFailedContext); return(authenticationFailedContext); }
private static async Task OnAuthenticationFailedAsync(AuthenticationFailedContext context) { Debug.WriteLine($"99. Begin {nameof(OnAuthenticationFailedAsync)}"); await s_onAuthenticationFailed(context).ConfigureAwait(false); Debug.WriteLine($"99. End - {nameof(OnAuthenticationFailedAsync)}"); }
private async Task OnAuthenticationFailedAsync(AuthenticationFailedContext context) { _logger.LogDebug($"99. Begin {nameof(OnAuthenticationFailedAsync)}"); await s_onAuthenticationFailed(context).ConfigureAwait(false); _logger.LogDebug($"99. End - {nameof(OnAuthenticationFailedAsync)}"); }
/// <summary> /// Wenn <see cref="AuthenticationEvents"/> angegeben sind, dann ausführen. /// </summary> /// <returns></returns> private async Task RunAuthenticationEventsAsync() { if (IsValidated) { await Options.DataStore.StoreAsync(Options.Credentials.GetCredentials().Key, Context.AccessToken); if (Options.AuthenticationEvents?.OnAuthorized != null) { await Options.AuthenticationEvents.OnAuthorized(Context); } } else { var context = new AuthenticationFailedContext(Options.ServerAddress, Error); if (Options.AuthenticationEvents?.OnAuthorizationFailed != null) { await Options.AuthenticationEvents.OnAuthorizationFailed(context); } if (!context.IsHandled) { throw Error; } } }
// Handle sign-in errors differently than generic errors. private Task AuthenticationFailed(AuthenticationFailedContext context) { context.HandleResponse(); context.Response.Redirect("/"); //context.Response.Redirect("/Home/Error?message=" + context.Response.ToString()); return Task.FromResult(0); }
/// <summary> /// Returns an error message if authentication failed. /// </summary> /// <param name="arg"></param> /// <returns></returns> public static async Task AuthenticationFailed(AuthenticationFailedContext arg) { // Check first if response was already handled if (!arg.Response.HasStarted) { // Track error in app insights var logger = arg.HttpContext.RequestServices.GetRequiredService <ILogger <JwtEventHelper> >(); logger.LogError(arg.Exception, "Authentication error."); var error = new MyProblemDetails(arg.HttpContext) { Title = "Authentication Error", Status = StatusCodes.Status401Unauthorized, Type = "https://www.my-error-portal.com/myproject/401", ErrorCode = "401" }; #if DEBUG error.Detail = arg.Exception.Message.Replace("\n", " "); #else error.Detail = "Authentication failed."; #endif // Add error message to response await WriteResponse(error, arg.Response, StatusCodes.Status401Unauthorized); } }
/// <summary> /// Handles authentication failures. /// </summary> /// <param name="context">The authentication failed context.</param> /// <param name="auditLogger">The audit logger provider.</param> /// <returns>An async task.</returns> private Task OnAuthenticationFailed(AuthenticationFailedContext context, IAuditLogger auditLogger) { this.Logger.LogDebug("OnAuthenticationFailed..."); AuditEvent auditEvent = new AuditEvent(); auditEvent.AuditEventDateTime = DateTime.UtcNow; auditEvent.TransactionDuration = 0; // There's not a way to calculate the duration here. auditLogger.PopulateWithHttpContext(context.HttpContext, auditEvent); auditEvent.TransactionResultCode = AuditTransactionResult.Unauthorized; auditEvent.CreatedBy = nameof(StartupConfiguration); auditEvent.CreatedDateTime = DateTime.UtcNow; auditLogger.WriteAuditEvent(auditEvent); context.Response.StatusCode = (int)HttpStatusCode.Unauthorized; context.Response.ContentType = "application/json"; return(context.Response.WriteAsync(JsonConvert.SerializeObject(new { State = "AuthenticationFailed", Message = context.Exception.ToString(), }))); }
public Task OnAuthenticationFailed(AuthenticationFailedContext context) { context.HandleResponse(); context.Response.Redirect("/Home/Error?message=" + context.Exception.Message); return(Task.FromResult(0)); }
public static void setCustomError(AuthenticationFailedContext context) { context.Response.StatusCode = 403; context.Response.ContentType = "application/json"; var err = ""; if (context.Exception.GetType() == typeof(SecurityTokenValidationException)) { err = "invalid token"; } else if (context.Exception.GetType() == typeof(SecurityTokenInvalidIssuerException)) { err = "invalid issuer"; } else if (context.Exception.GetType() == typeof(SecurityTokenExpiredException)) { err = "token expired"; } var resp = new { error = err, status = context.Response.StatusCode }; context.Response.WriteAsync(JsonConvert.SerializeObject(resp, Formatting.Indented)); }
private async Task OnAuthenticationFailedAsync(AuthenticationFailedContext context) { _logger.LogDebug(string.Format(CultureInfo.InvariantCulture, LogMessages.MethodBegin, nameof(OnAuthenticationFailedAsync))); await s_onAuthenticationFailed(context).ConfigureAwait(false); _logger.LogDebug(string.Format(CultureInfo.InvariantCulture, LogMessages.MethodEnd, nameof(OnAuthenticationFailedAsync))); }
static async Task OnAuthenticationFailed(AuthenticationFailedContext context) { Debug.WriteLine($"Begin {nameof(OnAuthenticationFailed)}"); await onAuthenticationFailed(context); Debug.WriteLine($"End - {nameof(OnAuthenticationFailed)}"); }
protected override async Task <AuthenticateResult> HandleAuthenticateAsync() { try { if (await Options.CredentialProvider.IsAuthenticationDisabledAsync()) { var anonymousPrincipal = new ClaimsPrincipal(new ClaimsIdentity(new Claim[] { new Claim(ClaimTypes.Role, "Bot") })); var anonynousContext = new TokenValidatedContext(Context, Scheme, Options) { Principal = anonymousPrincipal }; anonynousContext.Success(); return(anonynousContext.Result); } string authHeader = Request.Headers["Authorization"]; ClaimsIdentity claimsIdentity = await JwtTokenValidation.ValidateAuthHeader(authHeader, Options.CredentialProvider, _httpClient); Logger.TokenValidationSucceeded(); claimsIdentity.AddClaim(new Claim(ClaimTypes.Role, "Bot")); var principal = new ClaimsPrincipal(claimsIdentity); Context.User = principal; string jwtToken = JwtTokenExtractor.ExtractBearerTokenFromAuthHeader(authHeader); var tokenValidatedContext = new TokenValidatedContext(Context, Scheme, Options) { Principal = principal, SecurityToken = new JwtSecurityToken(jwtToken) }; await Events.TokenValidated(tokenValidatedContext); if (tokenValidatedContext.Result != null) { return(tokenValidatedContext.Result); } tokenValidatedContext.Success(); return(tokenValidatedContext.Result); } catch (Exception ex) { Logger.ErrorProcessingMessage(ex); var authenticationFailedContext = new AuthenticationFailedContext(Context, Scheme, Options) { Exception = ex }; await Events.AuthenticationFailed(authenticationFailedContext); if (authenticationFailedContext.Result != null) { return(authenticationFailedContext.Result); } throw; } }
private async Task AuthenticationFailed(AuthenticationFailedContext arg) { // For debugging purposes only! var s = $"AuthenticationFailed: {arg.Exception.Message}"; arg.Response.ContentLength = s.Length; await arg.Response.Body.WriteAsync(Encoding.UTF8.GetBytes(s), 0, s.Length); }
private static async Task OnAuthenticationFailedAsync(AuthenticationFailedContext context) { Debug.WriteLine($"99. Begin {nameof(OnAuthenticationFailedAsync)}"); // Place a breakpoint here and examine context.Exception await s_onAuthenticationFailed(context).ConfigureAwait(false); Debug.WriteLine($"99. End - {nameof(OnAuthenticationFailedAsync)}"); }
private static async Task AuthenticationFailed(AuthenticationFailedContext arg) { var message = $"AuthenticationFailed: {arg.Exception.Message}"; arg.Response.ContentLength = message.Length; arg.Response.StatusCode = (int)HttpStatusCode.Unauthorized; await arg.Response.Body.WriteAsync(Encoding.UTF8.GetBytes(message), 0, message.Length); }
private Task AuthenticationFailed(AuthenticationFailedContext context) { if (context.Exception.GetType() == typeof(SecurityTokenExpiredException)) { context.Response.Headers.Add("Token-Expired", "true"); } return(Task.CompletedTask); }
private Task AuthenticationFailed(AuthenticationFailedContext arg) { var s = $"AuthenticationFailed: {arg.Exception.Message}"; arg.Response.ContentLength = s.Length; arg.Response.Body.Write(Encoding.UTF8.GetBytes(s), 0, s.Length); return(Task.FromResult(0)); }
private Task AuthenticationFailed(AuthenticationFailedContext context) { var errorMessage = $"Authentication Failed : { context.Exception.Message}"; context.Response.ContentLength = errorMessage.Length; context.Response.Body.Write(System.Text.Encoding.UTF8.GetBytes(errorMessage), 0, errorMessage.Length); return(Task.FromResult(0)); }
public override Task AuthenticationFailed(AuthenticationFailedContext context) { var logger = context.HttpContext.RequestServices.GetService <ILogger>(); logger.Error(context.Exception, "Authentication Failed"); return(base.AuthenticationFailed(context)); }
static async Task OnAuthenticationFailed(AuthenticationFailedContext context) { Debug.WriteLine($"99. Begin {nameof(JwtBearerMiddlewareDiagnostics.OnAuthenticationFailed)}"); // Place a breakpoint here and examine context.Exception await JwtBearerMiddlewareDiagnostics.onAuthenticationFailed(context); Debug.WriteLine($"99. End - {nameof(JwtBearerMiddlewareDiagnostics.OnAuthenticationFailed)}"); }
static async Task OnAuthenticationFailed(AuthenticationFailedContext context) { Debug.WriteLine($"99. Begin {nameof(OnAuthenticationFailed)}"); // Place a breakpoint here and examine context.Exception await onAuthenticationFailed(context); Debug.WriteLine($"99. End - {nameof(OnAuthenticationFailed)}"); }
private async Task OnAuthenticationFailedAsync(AuthenticationFailedContext context) { _logger.LogDebug(string.Format(CultureInfo.InvariantCulture, LogMessages.MethodBegin, nameof(OnAuthenticationFailedAsync))); // Place a breakpoint here and examine context.Exception await _onAuthenticationFailed(context).ConfigureAwait(false); _logger.LogDebug(string.Format(CultureInfo.InvariantCulture, LogMessages.MethodEnd, nameof(OnAuthenticationFailedAsync))); }
/// <summary> /// Dont Leak Data When Jwt Authentication Fails Unless in Development Mode /// </summary> private static Task OnKeycloakAuthenticationFailed(this AuthenticationFailedContext context, IWebHostEnvironment env) { context.NoResult(); context.Response.StatusCode = 500; context.Response.ContentType = "text/plain"; return(context.Response.WriteAsync(env.IsDevelopment() ? context.Exception.ToString() : "An error occured processing your authentication.")); }
/// <summary> /// Authentications the failed. /// </summary> /// <param name="context">The context.</param> /// <returns>A task.</returns> public override Task AuthenticationFailed(AuthenticationFailedContext context) { this._logger .ForContext("JWTDebugEvent", "AuthenticationFailed") .ForContext("Context", context) .Debug("JWT AuthenticationFailed"); return(base.AuthenticationFailed(context)); }
public override Task AuthenticationFailed(AuthenticationFailedContext context) { if (context.Exception.GetType() == typeof(SecurityTokenExpiredException)) { context.Response.Headers.Add("x-service-token-expired", "true"); } return(Task.CompletedTask); }