Пример #1
0
 // Handle sign-in errors differently than generic errors.
 private Task AuthenticationFailed(Microsoft.AspNetCore.Authentication.JwtBearer.AuthenticationFailedContext context)
 {
     //context.HandleResponse();
     //context.Response.Redirect("/Home/Error?message=" + context.Failure.Message);
     //context.Response.Redirect("/Home/Error?message=");
     return(Task.FromResult(0));
 }
Пример #2
0
        /// <summary>
        /// Handles Bearer Token authentication failures.
        /// </summary>
        /// <param name="context">The JWT authentication failed context.</param>
        /// <param name="auditLogger">The audit logger provider.</param>
        /// <returns>An async task.</returns>
        private Task OnAuthenticationFailed(Microsoft.AspNetCore.Authentication.JwtBearer.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(),
            })));
        }
Пример #3
0
            // Handle sign-in errors differently than generic errors.
            private Task AuthenticationFailed(Microsoft.AspNetCore.Authentication.JwtBearer.AuthenticationFailedContext context)
            {
                //context.HandleResponse();
                //context.Response.Redirect("/Home/Error?message=" + context.Failure.Message);
                //context.Response.Redirect("/Home/Error?message=");

                //_logger.LogError($"AuthenticationFailed token provided: {context.Request.Headers.TryGetValue("",)}");

                return(Task.FromResult(0));
            }
Пример #4
0
 private Task OnAuthenticationFailed(AuthenticationFailedContext notification)
 {
     notification.Response.Redirect("/Home/Error");
     return(Task.FromResult(0));
 }
Пример #5
0
        /// <summary>
        /// Searches the 'Authorization' header for a 'Bearer' token. If the 'Bearer' token is found, it is validated using <see cref="TokenValidationParameters"/> set in the options.
        /// </summary>
        /// <returns></returns>
        protected override async Task <AuthenticateResult> HandleAuthenticateAsync()
        {
            string token = null;

            try
            {
                // Give application opportunity to find from a different location, adjust, or reject token
                var messageReceivedContext = new MessageReceivedContext(Context, Scheme, Options);

                // event can set the token
                await Events.MessageReceived(messageReceivedContext);

                if (messageReceivedContext.Result != null)
                {
                    return(messageReceivedContext.Result);
                }

                // If application retrieved token from somewhere else, use that.
                token = messageReceivedContext.Token;

                if (string.IsNullOrEmpty(token))
                {
                    string authorization = Request.Headers["Authorization"];

                    // If no authorization header found, nothing to process further
                    if (string.IsNullOrEmpty(authorization))
                    {
                        return(AuthenticateResult.NoResult());
                    }

                    if (authorization.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase))
                    {
                        token = authorization.Substring("Bearer ".Length).Trim();
                    }

                    // If no token found, no further work possible
                    if (string.IsNullOrEmpty(token))
                    {
                        return(AuthenticateResult.NoResult());
                    }
                }

                if (_configuration == null && Options.ConfigurationManager != null)
                {
                    _configuration = await Options.ConfigurationManager.GetConfigurationAsync(Context.RequestAborted);
                }

                var validationParameters = Options.TokenValidationParameters.Clone();
                if (_configuration != null)
                {
                    var issuers = new[] { _configuration.Issuer };
                    validationParameters.ValidIssuers = validationParameters.ValidIssuers?.Concat(issuers) ?? issuers;

                    validationParameters.IssuerSigningKeys = validationParameters.IssuerSigningKeys?.Concat(_configuration.SigningKeys)
                                                             ?? _configuration.SigningKeys;
                }

                List <Exception> validationFailures = null;
                SecurityToken    validatedToken;
                foreach (var validator in Options.SecurityTokenValidators)
                {
                    if (validator.CanReadToken(token))
                    {
                        ClaimsPrincipal principal;
                        try
                        {
                            principal = validator.ValidateToken(token, validationParameters, out validatedToken);
                        }
                        catch (Exception ex)
                        {
                            Logger.TokenValidationFailed(token, ex);

                            // Refresh the configuration for exceptions that may be caused by key rollovers. The user can also request a refresh in the event.
                            if (Options.RefreshOnIssuerKeyNotFound && Options.ConfigurationManager != null &&
                                ex is SecurityTokenSignatureKeyNotFoundException)
                            {
                                Options.ConfigurationManager.RequestRefresh();
                            }

                            if (validationFailures == null)
                            {
                                validationFailures = new List <Exception>(1);
                            }
                            validationFailures.Add(ex);
                            continue;
                        }

                        Logger.TokenValidationSucceeded();

                        var tokenValidatedContext = new TokenValidatedContext(Context, Scheme, Options)
                        {
                            Principal     = principal,
                            SecurityToken = validatedToken
                        };

                        await Events.TokenValidated(tokenValidatedContext);

                        if (tokenValidatedContext.Result != null)
                        {
                            return(tokenValidatedContext.Result);
                        }

                        if (Options.SaveToken)
                        {
                            tokenValidatedContext.Properties.StoreTokens(new[]
                            {
                                new AuthenticationToken {
                                    Name = "access_token", Value = token
                                }
                            });
                        }

                        tokenValidatedContext.Success();
                        return(tokenValidatedContext.Result);
                    }
                }

                if (validationFailures != null)
                {
                    var authenticationFailedContext = new AuthenticationFailedContext(Context, Scheme, Options)
                    {
                        Exception = (validationFailures.Count == 1) ? validationFailures[0] : new AggregateException(validationFailures)
                    };

                    await Events.AuthenticationFailed(authenticationFailedContext);

                    if (authenticationFailedContext.Result != null)
                    {
                        return(authenticationFailedContext.Result);
                    }

                    return(AuthenticateResult.Fail(authenticationFailedContext.Exception));
                }

                return(AuthenticateResult.Fail("No SecurityTokenValidator available for token: " + token ?? "[null]"));
            }
            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;
            }
        }
 // Handle sign-in errors differently than generic errors.
 private Task AuthenticationFailedAsync(Microsoft.AspNetCore.Authentication.JwtBearer.AuthenticationFailedContext context)
 {
     context.Fail(context.Exception);
     return(Task.FromResult(0));
 }
Пример #7
0
 /// <summary>
 /// Invoked if exceptions are thrown during request processing. The exceptions will be re-thrown after this event unless suppressed.
 /// </summary>
 public virtual Task AuthenticationFailed(AuthenticationFailedContext context) => OnAuthenticationFailed(context);
Пример #8
0
 public virtual Task AuthenticationFailed(AuthenticationFailedContext context) => OnAuthenticationFailed(context);
Пример #9
0
        // private OpenIdConnectConfiguration _configuration;

        /// <summary>
        /// Searches the 'Authorization' header for a 'Bearer' token. If the 'Bearer' token is found, it is validated using <see cref="TokenValidationParameters"/> set in the options.
        /// </summary>
        /// <returns></returns>
        protected override async Task <AuthenticateResult> HandleAuthenticateAsync()
        {
            string url = Microsoft.AspNetCore.Http.Extensions.UriHelper.GetDisplayUrl(Context.Request);

            System.Console.WriteLine(url);


            string             token  = null;
            AuthenticateResult result = null;

            try
            {
                // Give application opportunity to find from a different location, adjust, or reject token
                var messageReceivedContext = new MessageReceivedContext(Context, Options);

                // event can set the token
                // await Options.Events.MessageReceived(messageReceivedContext);
                if (messageReceivedContext.CheckEventResult(out result))
                {
                    return(result);
                }

                // If application retrieved token from somewhere else, use that.
                token = messageReceivedContext.Token;

                if (string.IsNullOrEmpty(token))
                {
                    string authorization = Request.Headers["Authorization"];

                    // If no authorization header found, nothing to process further
                    if (string.IsNullOrEmpty(authorization))
                    {
                        return(AuthenticateResult.Skip());
                    }

                    if (authorization.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase))
                    {
                        token = authorization.Substring("Bearer ".Length).Trim();
                    }

                    // If no token found, no further work possible
                    if (string.IsNullOrEmpty(token))
                    {
                        return(AuthenticateResult.Skip());
                    }
                }

                /*
                 * if (_configuration == null && Options.ConfigurationManager != null)
                 * {
                 *  _configuration = await Options.ConfigurationManager.GetConfigurationAsync(Context.RequestAborted);
                 * }
                 *
                 * var validationParameters = Options.TokenValidationParameters.Clone();
                 * if (_configuration != null)
                 * {
                 *  if (validationParameters.ValidIssuer == null && !string.IsNullOrEmpty(_configuration.Issuer))
                 *  {
                 *      validationParameters.ValidIssuer = _configuration.Issuer;
                 *  }
                 *  else
                 *  {
                 *      var issuers = new[] { _configuration.Issuer };
                 *      validationParameters.ValidIssuers = (validationParameters.ValidIssuers == null ? issuers : validationParameters.ValidIssuers.Concat(issuers));
                 *  }
                 *
                 *  validationParameters.IssuerSigningKeys = (validationParameters.IssuerSigningKeys == null ? _configuration.SigningKeys : validationParameters.IssuerSigningKeys.Concat(_configuration.SigningKeys));
                 * }
                 */


                /*
                 * List<Exception> validationFailures = null;
                 * SecurityToken validatedToken;
                 * foreach (var validator in Options.SecurityTokenValidators)
                 * {
                 *  if (validator.CanReadToken(token))
                 *  {
                 *      ClaimsPrincipal principal;
                 *      try
                 *      {
                 *          principal = validator.ValidateToken(token, validationParameters, out validatedToken);
                 *      }
                 *      catch (Exception ex)
                 *      {
                 *          Logger.TokenValidationFailed(token, ex);
                 *
                 *          // Refresh the configuration for exceptions that may be caused by key rollovers. The user can also request a refresh in the event.
                 *          if (Options.RefreshOnIssuerKeyNotFound && Options.ConfigurationManager != null
                 *              && ex is SecurityTokenSignatureKeyNotFoundException)
                 *          {
                 *              Options.ConfigurationManager.RequestRefresh();
                 *          }
                 *
                 *          if (validationFailures == null)
                 *          {
                 *              validationFailures = new List<Exception>(1);
                 *          }
                 *          validationFailures.Add(ex);
                 *          continue;
                 *      }
                 *
                 *      Logger.TokenValidationSucceeded();
                 *
                 *      var ticket = new AuthenticationTicket(principal, new AuthenticationProperties(), Options.AuthenticationScheme);
                 *      var tokenValidatedContext = new TokenValidatedContext(Context, Options)
                 *      {
                 *          Ticket = ticket,
                 *          SecurityToken = validatedToken,
                 *      };
                 *
                 *      await Options.Events.TokenValidated(tokenValidatedContext);
                 *      if (tokenValidatedContext.CheckEventResult(out result))
                 *      {
                 *          return result;
                 *      }
                 *      ticket = tokenValidatedContext.Ticket;
                 *
                 *      if (Options.SaveToken)
                 *      {
                 *          ticket.Properties.StoreTokens(new[]
                 *          {
                 *              new AuthenticationToken { Name = "access_token", Value = token }
                 *          });
                 *      }
                 *
                 *      return AuthenticateResult.Success(ticket);
                 *  }
                 * }
                 */

                /*
                 * if (validationFailures != null)
                 * {
                 *  var authenticationFailedContext = new AuthenticationFailedContext(Context, Options)
                 *  {
                 *      Exception = (validationFailures.Count == 1) ? validationFailures[0] : new AggregateException(validationFailures)
                 *  };
                 *
                 *  await Options.Events.AuthenticationFailed(authenticationFailedContext);
                 *  if (authenticationFailedContext.CheckEventResult(out result))
                 *  {
                 *      return result;
                 *  }
                 *
                 *  return AuthenticateResult.Fail(authenticationFailedContext.Exception);
                 * }
                 */
                return(AuthenticateResult.Fail("No SecurityTokenValidator available for token: " + token ?? "[null]"));
            }
            catch (Exception ex)
            {
                // Logger.ErrorProcessingMessage(ex);

                var authenticationFailedContext = new AuthenticationFailedContext(Context, Options)
                {
                    Exception = ex
                };

                // await Options.Events.AuthenticationFailed(authenticationFailedContext);
                if (authenticationFailedContext.CheckEventResult(out result))
                {
                    return(result);
                }

                throw;
            }
        }
 public override Task AuthenticationFailed(AuthenticationFailedContext context)
 {
     _logger.AuthenticationFailed(context.Exception);
     return base.AuthenticationFailed(context);
 }
Пример #11
0
 private Task JwtBearerAuthenticationFailed(Microsoft.AspNetCore.Authentication.JwtBearer.AuthenticationFailedContext arg)
 {
     _logger.LogDebug("JwtBearerAuthenticationFailed!");
     return(Task.FromResult(0));
 }
 // Handle sign-in errors differently than generic errors.
 private Task AuthenticationFailed(Microsoft.AspNetCore.Authentication.JwtBearer.AuthenticationFailedContext context)
 {
     return(Task.FromResult(0));
 }
Пример #13
0
 private static Task OnAuthenticationFailed(AuthenticationFailedContext arg)
 {
     Console.WriteLine(arg);
     return(Task.FromResult(0));
 }