/// <summary>
        /// Called when action starts executing.
        /// </summary>
        /// <param name="context">The action context.</param>
        public override void OnActionExecuting(HttpActionContext context)
        {
            string actionName = context.GetFullActionName();

            // Log the action entry
            var message = new StringBuilder();

            message.Append($"Entering action '{actionName}'.");
            if (context.ActionArguments.Count > 0)
            {
                message.AppendLine().Append("Action parameters:");
                foreach (KeyValuePair <string, object> parameter in context.ActionArguments)
                {
                    object valueToLog = parameter.Value;
                    var    login      = parameter.Value as LoginRequest;
                    if (login != null)
                    {
                        valueToLog = new LoginRequest
                        {
                            Username = login.Username,
                            Password = CommonHelper.PasswordMask
                        };
                    }

                    string argumentDesctiption = CommonHelper.GetObjectDescription(valueToLog);
                    message.AppendLine().Append($"\t {parameter.Key}: {argumentDesctiption}");
                }
            }

            Logger.Debug(message.ToString());
        }
예제 #2
0
        /// <summary>
        /// Validates user token and authorization.
        /// </summary>
        ///
        /// <remarks>
        /// All exceptions from back-end services will be propagated.
        /// </remarks>
        ///
        /// <param name="context">The action context.</param>
        public override void OnActionExecuting(HttpActionContext context)
        {
            string methodName = $"{nameof(AuthorizationFilter)}.{nameof(OnActionExecuting)}";

            Logger.DebugFormat("Entering '{0}' to validate the token.", methodName);

            // skip controllers or actions which allow anonymous access
            var actionDescriptor = context.ActionDescriptor;

            if (actionDescriptor.GetCustomAttributes <AllowAnonymousAttribute>(true).Any() ||
                actionDescriptor.ControllerDescriptor.GetCustomAttributes <AllowAnonymousAttribute>(true).Any())
            {
                Logger.DebugFormat("Token is not required for this action.");
                return;
            }

            string         errorMessage = null;
            HttpStatusCode code         = HttpStatusCode.OK;

            if (context.Request.Headers.Authorization != null &&
                context.Request.Headers.Authorization.Scheme == "Bearer")
            {
                // perform authentication
                User user = SecurityService.Authenticate(context.Request.Headers.Authorization.Parameter);
                if (user == null)
                {
                    code         = HttpStatusCode.Unauthorized;
                    errorMessage = "Token was not found or has been expired.";
                }
                else
                {
                    // check authorization
                    string actionName = context.GetFullActionName(false);
                    if (!SecurityService.IsAuthorized(actionName))
                    {
                        code         = HttpStatusCode.Forbidden;
                        errorMessage = "You are not authorized to perform this action.";
                    }
                    else
                    {
                        context.Request.Properties.Add(Helper.CurrentUserPropertyName, user);
                        Logger.Debug("Token is valid.");
                    }
                }
            }
            else
            {
                code         = HttpStatusCode.Unauthorized;
                errorMessage = "Bearer Token is missing.";
            }

            if (code != HttpStatusCode.OK)
            {
                context.Response         = new HttpResponseMessage(code);
                context.Response.Content = new StringContent(errorMessage);
                Logger.DebugFormat(errorMessage);
            }

            Logger.DebugFormat("Exiting '{0}'.", methodName);
        }
        /// <summary>
        /// Validates user token and authorization.
        /// </summary>
        ///
        /// <remarks>
        /// All exceptions from back-end services will be propagated.
        /// </remarks>
        ///
        /// <param name="context">The action context.</param>
        ///
        /// <exception cref="AuthenticationException">
        /// If Bearer token is not provided or token is invalid or expired.
        /// </exception>
        /// <exception cref="AuthorizationException">
        /// If user is not authorized to perform current action.
        /// </exception>
        public override void OnActionExecuting(HttpActionContext context)
        {
            string methodName = $"{nameof(AuthorizationFilter)}.{nameof(OnActionExecuting)}";

            Logger.DebugFormat("Entering '{0}' to validate the token.", methodName);

            // skip controllers or actions which allow anonymous access
            var actionDescriptor = context.ActionDescriptor;

            if (actionDescriptor.GetCustomAttributes <AllowAnonymousAttribute>(true).Any() ||
                actionDescriptor.ControllerDescriptor.GetCustomAttributes <AllowAnonymousAttribute>(true).Any())
            {
                Logger.Debug("Token is not required for the current action.");
                return;
            }

            // check whether Bearer token is provided
            if (context.Request.Headers.Authorization == null ||
                context.Request.Headers.Authorization.Scheme != "Bearer")
            {
                throw new AuthenticationException("Bearer Token is missing.");
            }

            // perform authentication
            User user = SecurityService.Authenticate(context.Request.Headers.Authorization.Parameter);

            if (user == null)
            {
                throw new AuthenticationException("Token was not found or has been expired.");
            }

            Logger.Debug("Token is valid.");

            // check authorization
            string actionName = context.GetFullActionName(false);
            bool   authorized = user.Role != null && SecurityService.IsAuthorized(user.Role.Value, actionName);

            if (!authorized)
            {
                authorized = user.KPIRole != null && SecurityService.IsAuthorized(user.KPIRole.Value, actionName);
            }

            if (!authorized)
            {
                throw new AuthorizationException("You are not authorized to perform this action.");
            }

            context.Request.Properties.Add(CommonHelper.CurrentUserPropertyName, user);
            Logger.DebugFormat("Exiting '{0}'.", methodName);
        }