/// <inheritdoc />
        /// <summary>
        ///     Authorization as an asynchronous operation.
        /// </summary>
        /// <param name="context">The <see cref="T:Microsoft.AspNetCore.Mvc.Filters.AuthorizationFilterContext" />.</param>
        /// <returns>A <see cref="T:System.Threading.Tasks.Task" /> that on completion indicates the filter has executed.</returns>
        public async Task OnAuthorizationAsync(AuthorizationFilterContext context)
        {
            // Allow Anonymous skips all authorization
            if (context.Filters.Any(item => item is IAllowAnonymousFilter))
            {
                return;
            }

            var policyEvaluator    = context.HttpContext.RequestServices.GetRequiredService <IPolicyEvaluator>();
            var authenticateResult = await policyEvaluator.AuthenticateAsync(Policy, context.HttpContext);

            var authorizeResult = await policyEvaluator.AuthorizeAsync(Policy, authenticateResult, context.HttpContext, context);

            var errObject = new RequestErrorObject();

            if (authorizeResult.Challenged)
            {
                errObject.SetErrorTo401UnAuthorized();
            }
            else if (authorizeResult.Forbidden)
            {
                errObject.SetErrorTo403Forbidden(string.Join(", ", Policy.AuthenticationSchemes));
            }
            else
            {
                return;
            }

            context.Result = new ProblemResult(errObject);
        }
Exemplo n.º 2
0
 /// <summary>
 ///     Initializes a new instance of the <see cref="ProblemResult" /> class.  I will set the following:
 ///     <para>
 ///         <see cref="RequestErrorObject.Instance" /> value to the ActionContext.HttpContext.Request.Path
 ///     </para>
 ///     <para>
 ///         <see cref="ObjectResult.StatusCode" /> value to the <see cref="RequestErrorObject.Status" />
 ///     </para>
 ///     <para>
 ///         I will clear all content types and add "application/problem+json"
 ///     </para>
 /// </summary>
 /// <param name="error">The error.</param>
 public ProblemResult(RequestErrorObject error)
     : base(error)
 {
     _error     = error;
     StatusCode = _error.Status;
     ContentTypes.Clear();
     ContentTypes.Add(Constants.ResponseTypes.ErrorResponseContentType);
 }
Exemplo n.º 3
0
        public ActionResult GetProblemResultExample(CommonStatusCodes statusCode = CommonStatusCodes.Status403Forbidden, string description = null)
        {
            if (statusCode == CommonStatusCodes.Status200Ok || statusCode == CommonStatusCodes.Status204NoContent)
            {
                return(Ok("Try one that isn't a success code :)"));
            }

            var errObject = new RequestErrorObject();

            errObject.SetError(statusCode, description);

            return(new ProblemResult(errObject));
 private async Task <Exception> handleError(HttpResponseMessage response)
 {
     if (response.StatusCode == System.Net.HttpStatusCode.Forbidden)
     {
         return(new Exception("Quota exceeded"));
     }
     else if (response.StatusCode == System.Net.HttpStatusCode.Unauthorized)
     {
         return(new Exception("Invalid API Key"));
     }
     else
     {
         RequestErrorObject error = JsonConvert.DeserializeObject <RequestErrorObject>(await response.Content.ReadAsStringAsync());
         return(new Exception(error.Error));
     }
 }
Exemplo n.º 5
0
        /// <inheritdoc />
        /// <summary>
        ///     Called when just prior to
        ///     <see cref="M:APIBlox.AspNetCore.ActionResults.ProblemResult.OnFormatting(Microsoft.AspNetCore.Mvc.ActionContext)" />
        ///     completes.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="obj">The object.</param>
        protected override void OnBeforeFormattingComplete(ActionContext context, RequestErrorObject obj)
        {
            var ms = context.ModelState;

            if (ms.IsValid)
            {
                throw new ArgumentException(
                          "The validation state is VALID, the action result " +
                          $"{nameof(ValidationFailureResult)} is being inappropriately used."
                          );
            }

            var errors = context.ModelState.Keys
                         .Where(k => !k.IsEmptyNullOrWhiteSpace())
                         .SelectMany(key =>
                                     ms[key].Errors.Select(x =>
            {
                dynamic ret = new DynamicErrorObject
                {
                    Title  = "Invalid Property Value",
                    Detail = x.ErrorMessage
                };
                ret.Property = key;

                return(ret);
            }
                                                           )
                                     ).ToList();

            if (!errors.Any())
            {
                obj.Detail = "Errors have occured.";
            }

            foreach (var err in errors)
            {
                obj.Errors.Add(err);
            }
        }
Exemplo n.º 6
0
 /// <summary>
 ///     Called just prior to <see cref="OnFormatting(ActionContext)" /> completes.
 /// </summary>
 /// <param name="context">The context.</param>
 /// <param name="error">The <see cref="RequestErrorObject" />.</param>
 protected virtual void OnBeforeFormattingComplete(ActionContext context, RequestErrorObject error)
 {
 }
Exemplo n.º 7
0
 /// <inheritdoc />
 /// <summary>
 ///     Initializes a new instance of the <see cref="T:APIBlox.AspNetCore.Exceptions.HandledRequestException" /> class.
 /// </summary>
 /// <param name="requestErrorObject">The request error object.</param>
 public HandledRequestException(RequestErrorObject requestErrorObject)
 {
     RequestErrorObject = requestErrorObject;
 }