protected override async Task InternalInterceptAsynchronous(IInvocation invocation)
        {
            var proceedInfo = invocation.CaptureProceedInfo();

            await _authorizationHelper.AuthorizeAsync(invocation.MethodInvocationTarget, invocation.TargetType);

            proceedInfo.Invoke();
            var task = (Task)invocation.ReturnValue;
            await task.ConfigureAwait(false);
        }
Exemple #2
0
        public virtual async Task <HttpResponseMessage> ExecuteAuthorizationFilterAsync(
            HttpActionContext actionContext,
            CancellationToken cancellationToken,
            Func <Task <HttpResponseMessage> > continuation)
        {
            var methodInfo = actionContext.ActionDescriptor.GetMethodInfoOrNull();

            if (methodInfo == null)
            {
                return(await continuation());
            }

            if (actionContext.ActionDescriptor.IsDynamicAbpAction())
            {
                return(await continuation());
            }

            try
            {
                await _authorizationHelper.AuthorizeAsync(methodInfo);

                return(await continuation());
            }
            catch (AbpAuthorizationException ex)
            {
                LogHelper.Logger.Warn(ex.ToString(), ex);
                _eventBus.Trigger(this, new AbpHandledExceptionData(ex));
                return(CreateUnAuthorizedResponse(actionContext));
            }
        }
Exemple #3
0
        public virtual async Task <HttpResponseMessage> ExecuteAuthorizationFilterAsync(
            HttpActionContext actionContext,
            CancellationToken cancellationToken,
            Func <Task <HttpResponseMessage> > continuation)
        {
            if (actionContext.ActionDescriptor.GetCustomAttributes <AllowAnonymousAttribute>().Any() ||
                actionContext.ActionDescriptor.ControllerDescriptor.GetCustomAttributes <AllowAnonymousAttribute>().Any())
            {
                return(await continuation());
            }
            var methodInfo = actionContext.ActionDescriptor.GetMethodInfoOrNull();

            if (methodInfo == null)
            {
                return(await continuation());
            }

            if (actionContext.ActionDescriptor.IsDynamicInfrastructureAction())
            {
                return(await continuation());
            }

            try
            {
                await _authorizationHelper.AuthorizeAsync(methodInfo);

                return(await continuation());
            }
            catch (AuthorizationException ex)
            {
                LogHelper.Logger.Warn(ex.ToString(), ex);
                _eventBus.Trigger(this, new HandledExceptionData(ex));
                return(CreateUnAuthorizedResponse(actionContext));
            }
        }
Exemple #4
0
        public async Task OnAuthorizationAsync(AuthorizationFilterContext context)
        {
            // Allow Anonymous skips all authorization
            if (context.Filters.Any(item => item is IAllowAnonymousFilter))
            {
                return;
            }

            //TODO: Avoid using try/catch, use conditional checking
            try
            {
                await _authorizationHelper.AuthorizeAsync(
                    context.ActionDescriptor.GetMethodInfo(),
                    context.ActionDescriptor.GetMethodInfo().DeclaringType
                    );
            }
            catch (AbpAuthorizationException ex)
            {
                Logger.Warn(ex.ToString(), ex);

                _eventBus.Trigger(this, new AbpHandledExceptionData(ex));

                if (ActionResultHelper.IsObjectResult(context.ActionDescriptor.GetMethodInfo().ReturnType))
                {
                    context.Result = new ObjectResult(new AjaxResponse(_errorInfoBuilder.BuildForException(ex), true))
                    {
                        StatusCode = context.HttpContext.User.Identity.IsAuthenticated
                            ? (int)System.Net.HttpStatusCode.Forbidden
                            : (int)System.Net.HttpStatusCode.Unauthorized
                    };
                }
                else
                {
                    context.Result = new ChallengeResult();
                }
            }
            catch (Exception ex)
            {
                Logger.Error(ex.ToString(), ex);

                _eventBus.Trigger(this, new AbpHandledExceptionData(ex));

                if (ActionResultHelper.IsObjectResult(context.ActionDescriptor.GetMethodInfo().ReturnType))
                {
                    context.Result = new ObjectResult(new AjaxResponse(_errorInfoBuilder.BuildForException(ex)))
                    {
                        StatusCode = (int)System.Net.HttpStatusCode.InternalServerError
                    };
                }
                else
                {
                    //TODO: How to return Error page?
                    context.Result = new StatusCodeResult((int)System.Net.HttpStatusCode.InternalServerError);
                }
            }
        }
Exemple #5
0
        public async Task OnAuthorizationAsync(AuthorizationFilterContext context)
        {
            // Allow Anonymous skips all authorization
            if (context.Filters.Any(item => item is IAllowAnonymousFilter))
            {
                return;
            }

            if (!context.ActionDescriptor.IsControllerAction())
            {
                return;
            }

            //TODO: Avoid using try/catch, use conditional checking
            try
            {
                await _authorizationHelper.AuthorizeAsync(
                    context.ActionDescriptor.GetMethodInfo(),
                    context.ActionDescriptor.GetMethodInfo().DeclaringType
                    );
            }
            catch (AuthorizationException ex)
            {
                LogUtil.Warn(ex);

                if (ActionResultHelper.IsObjectResult(context.ActionDescriptor.GetMethodInfo().ReturnType))
                {
                    var isLogin = await _authorizationHelper.CheckLoginAsync();

                    var errorInfo = ExceptionConvertUtil.Convert(ex);
                    context.Result = new ObjectResult(new AjaxResponse(errorInfo))
                    {
                        StatusCode = isLogin ? (int)System.Net.HttpStatusCode.Forbidden : (int)System.Net.HttpStatusCode.Unauthorized
                    };
                }
                else
                {
                    context.Result = new ChallengeResult();
                }
            }
            catch (Exception ex)
            {
                LogUtil.Error(ex);
                if (ActionResultHelper.IsObjectResult(context.ActionDescriptor.GetMethodInfo().ReturnType))
                {
                    context.Result = new ObjectResult(new OperateResult(ex))
                    {
                        StatusCode = (int)System.Net.HttpStatusCode.InternalServerError
                    };
                }
                else
                {
                    context.Result = new StatusCodeResult((int)System.Net.HttpStatusCode.InternalServerError);
                }
            }
        }
Exemple #6
0
        public async Task OnAuthorizationAsync(AuthorizationFilterContext context)
        {
            // Allow Anonymous skips all authorization
            if (context.Filters.Any(item => item is IAllowAnonymousFilter))
            {
                return;
            }

            try
            {
                //TODO: Avoid using try/catch, use conditional checking
                await _authorizationHelper.AuthorizeAsync(context.ActionDescriptor.GetMethodInfo());
            }
            catch (ValidationException ex)
            {
                Logger.LogWarning(ex.ToString(), ex);


                //if (ActionResultHelper.IsObjectResult(context.ActionDescriptor.GetMethodInfo().ReturnType))
                //{
                //    context.Result = new ObjectResult(new AjaxResponse(_errorInfoBuilder.BuildForException(ex), true))
                //    {
                //        StatusCode = context.HttpContext.User.Identity.IsAuthenticated
                //            ? (int)System.Net.HttpStatusCode.Forbidden
                //            : (int)System.Net.HttpStatusCode.Unauthorized
                //    };
                //}
                //else
                //{
                context.Result = new ChallengeResult();
                //}
            }
            catch (Exception ex)
            {
                Logger.LogError(ex.ToString(), ex);


                //if (ActionResultHelper.IsObjectResult(context.ActionDescriptor.GetMethodInfo().ReturnType))
                //{
                //    context.Result = new ObjectResult(new AjaxResponse(_errorInfoBuilder.BuildForException(ex)))
                //    {
                //        StatusCode = (int)System.Net.HttpStatusCode.InternalServerError
                //    };
                //}
                //else
                //{
                //TODO: How to return Error page?
                context.Result = new StatusCodeResult((int)System.Net.HttpStatusCode.InternalServerError);
                // }
            }
        }
Exemple #7
0
        public async Task <IActionResult> Put(int compid, int id, [FromBody] Crew crew)
        {
            Models.Competition competition = await _context.Competitions.Include("Administrators.CompetitionAdministrator").FirstAsync(x => x.CompetitionId == compid);

            var authorizationResult = await _authorizationHelper.AuthorizeAsync(User, competition, "CanAdminCompetition");

            if (!authorizationResult.Succeeded)
            {
                if (User.Identity.IsAuthenticated)
                {
                    return(new ForbidResult());
                }
                else
                {
                    return(new ChallengeResult());
                }
            }

            Models.Crew dbCrew = await _context.Crews.FirstOrDefaultAsync(x => x.BroeCrewId == id);

            if (dbCrew == null)
            {
                Models.Crew modelCrew = new Models.Crew {
                    Competition = competition
                };
                competition.Crews.Add(modelCrew);
                _mapper.Map(crew, modelCrew);
                await _context.SaveChangesAsync();

                return(CreatedAtRoute("GetById", new { id = modelCrew.BroeCrewId }));
            }
            else
            {
                _mapper.Map(crew, dbCrew);
                await _context.SaveChangesAsync();

                return(NoContent());
            }
        }
Exemple #8
0
 public static void Authorize(this IAuthorizationHelper authorizationHelper, MethodInfo methodInfo, Type type)
 {
     AsyncHelper.RunSync(() => authorizationHelper.AuthorizeAsync(methodInfo, type));
 }
Exemple #9
0
 public static void Authorize(this IAuthorizationHelper authorizationHelper,
                              IEnumerable <IStudioXAuthorizeAttribute> authorizeAttributes)
 {
     AsyncHelper.RunSync(() => authorizationHelper.AuthorizeAsync(authorizeAttributes));
 }
Exemple #10
0
 public static async Task AuthorizeAsync(this IAuthorizationHelper authorizationHelper,
                                         IStudioXAuthorizeAttribute authorizeAttribute)
 {
     await authorizationHelper.AuthorizeAsync(new[] { authorizeAttribute });
 }
        public virtual async Task OnAuthorizationAsync(AuthorizationFilterContext context)
        {
            var endpoint = context?.HttpContext?.GetEndpoint();

            // 如果注入了 IAllowAnonymous 接口则允许所有匿名用户的请求
            // Allow Anonymous skips all authorization
            if (endpoint?.Metadata.GetMetadata <IAllowAnonymous>() != null)
            {
                return;
            }

            // 如果不是一个控制器方法则直接返回
            if (!context.ActionDescriptor.IsControllerAction())
            {
                return;
            }

            //TODO: Avoid using try/catch, use conditional checking
            // 开始使用 IAuthorizationHelper 对象来进行权限校验
            try
            {
                await _authorizationHelper.AuthorizeAsync(
                    context.ActionDescriptor.GetMethodInfo(),
                    context.ActionDescriptor.GetMethodInfo().DeclaringType
                    );
            }
            // 如果是未授权异常的处理逻辑
            catch (AbpAuthorizationException ex)
            {
                // 记录日志
                Logger.Warn(ex.ToString(), ex);

                // 触发异常事件
                await _eventBus.TriggerAsync(this, new AbpHandledExceptionData(ex));

                // 如果接口的返回类型为 ObjectResult,则采用 AjaxResponse 对象进行封装信息
                if (ActionResultHelper.IsObjectResult(context.ActionDescriptor.GetMethodInfo().ReturnType))
                {
                    //context.Result = new ObjectResult(new AjaxResponse(_errorInfoBuilder.BuildForException(ex), true))
                    //{
                    //    StatusCode = context.HttpContext.User.Identity.IsAuthenticated
                    //        ? (int)System.Net.HttpStatusCode.Forbidden
                    //        : (int)System.Net.HttpStatusCode.Unauthorized
                    //};
                    //获取错误信息
                    var errorInfo = _errorInfoBuilder.BuildForException(ex);
                    //code设置状态码数据
                    errorInfo.Code = (context.HttpContext.User.Identity.IsAuthenticated ? (int)System.Net.HttpStatusCode.Forbidden : (int)System.Net.HttpStatusCode.Unauthorized);
                    //返回结果
                    context.Result = new ObjectResult(new AjaxResponse(errorInfo, unAuthorizedRequest: true))
                    {
                        //默认状态
                        StatusCode = (int)System.Net.HttpStatusCode.OK
                    };
                }
                else
                {
                    context.Result = new ChallengeResult();
                }
            }
            // 其他异常则显示为服务器内部异常
            catch (Exception ex)
            {
                Logger.Error(ex.ToString(), ex);

                await _eventBus.TriggerAsync(this, new AbpHandledExceptionData(ex));

                if (ActionResultHelper.IsObjectResult(context.ActionDescriptor.GetMethodInfo().ReturnType))
                {
                    //context.Result = new ObjectResult(new AjaxResponse(_errorInfoBuilder.BuildForException(ex)))
                    //{
                    //    StatusCode = (int)System.Net.HttpStatusCode.InternalServerError
                    //};
                    //获取错误信息
                    var errorInfo = _errorInfoBuilder.BuildForException(ex);
                    errorInfo.Details = ex.Message;
                    errorInfo.Code    = (int)System.Net.HttpStatusCode.InternalServerError;
                    context.Result    = new ObjectResult(new AjaxResponse(errorInfo))
                    {
                        StatusCode = (int)System.Net.HttpStatusCode.OK
                    };
                }
                else
                {
                    //TODO: How to return Error page?
                    context.Result = new StatusCodeResult((int)System.Net.HttpStatusCode.InternalServerError);
                }
            }
        }
 public static async Task AuthorizeAsync(this IAuthorizationHelper authorizationHelper, IInfrastructureAuthorizeAttribute authorizeAttribute)
 {
     await authorizationHelper.AuthorizeAsync(new[] { authorizeAttribute });
 }
        public async Task OnAuthorizationAsync(AuthorizationFilterContext context)
        {
            // Allow Anonymous skips all authorization
            if (context.Filters.Any(item => item is IAllowAnonymousFilter))
            {
                return;
            }

            if (!context.ActionDescriptor.IsControllerAction())
            {
                return;
            }

            var isWebserviceWay = false;

            if (context.HttpContext.Request.Headers.ContainsKey("requestWay") || context.HttpContext.Request.Headers["requestWay"].ToString() != "webapi")
            {
                isWebserviceWay = true;
            }

            //TODO: Avoid using try/catch, use conditional checking
            try
            {
                await _authorizationHelper.AuthorizeAsync(
                    context.ActionDescriptor.GetMethodInfo(),
                    context.ActionDescriptor.GetMethodInfo().DeclaringType
                    );
            }
            catch (AbpAuthorizationException ex)
            {
                Logger.Warn(ex.ToString(), ex);

                _eventBus.Trigger(this, new AbpHandledExceptionData(ex));

                if (ActionResultHelper.IsObjectResult(context.ActionDescriptor.GetMethodInfo().ReturnType))
                {
                    if (isWebserviceWay)
                    {
                        context.Result = new ObjectResult(new ResultMessage <object>(ResultCode.Auth_Error, "authorization failure"));
                    }
                    else
                    {
                        context.Result = new ObjectResult(new AjaxResponse(_errorInfoBuilder.BuildForException(ex), true))
                        {
                            StatusCode = context.HttpContext.User.Identity.IsAuthenticated? (int)System.Net.HttpStatusCode.Forbidden:(int)System.Net.HttpStatusCode.Unauthorized
                        };
                    }
                }
                else
                {
                    if (isWebserviceWay)
                    {
                        context.Result = new ObjectResult(new ResultMessage <object>(ResultCode.Auth_Error, "authorization failure"));
                    }
                    else
                    {
                        context.Result = new ChallengeResult();
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.Error(ex.ToString(), ex);

                _eventBus.Trigger(this, new AbpHandledExceptionData(ex));

                if (ActionResultHelper.IsObjectResult(context.ActionDescriptor.GetMethodInfo().ReturnType))
                {
                    if (isWebserviceWay)
                    {
                        context.Result = new ObjectResult(new ResultMessage <object>(ResultCode.SytemError, "Unknown exception"));
                    }
                    else
                    {
                        context.Result = new ObjectResult(new AjaxResponse(_errorInfoBuilder.BuildForException(ex)))
                        {
                            StatusCode = (int)System.Net.HttpStatusCode.InternalServerError
                        };
                    }
                }
                else
                {
                    if (isWebserviceWay)
                    {
                        context.Result = new ObjectResult(new ResultMessage <object>(ResultCode.SytemError, "Unknown exception"));
                    }
                    else
                    {
                        //TODO: How to return Error page?
                        context.Result = new StatusCodeResult((int)System.Net.HttpStatusCode.InternalServerError);
                    }
                }
            }
        }