public override void OnActionExecuting(HttpActionContext actionContext)
        {
            HttpRequestMessage request = actionContext.Request;
            string query = request.RequestUri.Query.Substring(1);
            var parts = query.Split('&').ToList();
            bool foundExpand = false;
            for (int i = 0; i < parts.Count; i++)
            {
                string segment = parts[i];
                if (segment.StartsWith(ODataExpandOption, StringComparison.Ordinal))
                {
                    foundExpand = true;
                    parts[i] += "," + this.AlwaysExpand;
                    break;
                }
            }

            if (!foundExpand)
            {
                parts.Add(ODataExpandOption + this.AlwaysExpand);
            }

            UriBuilder modifiedRequestUri = new UriBuilder(request.RequestUri);
            modifiedRequestUri.Query = string.Join("&",
                                        parts.Where(p => p.Length > 0));
            request.RequestUri = modifiedRequestUri.Uri;
            base.OnActionExecuting(actionContext);
        }
Example #2
1
    public override async Task OnAuthorizationAsync( HttpActionContext actionContext, CancellationToken cancellationToken )
    {

      if ( actionContext.ControllerContext.ControllerDescriptor.ControllerType == typeof( UserController ) || string.Equals( actionContext.ActionDescriptor.ActionName, "Test", StringComparison.OrdinalIgnoreCase ) )
        return;

      var request = actionContext.Request;

      string loginToken = null;

      if ( loginToken == null )
      {
        var authorization = request.Headers.Authorization;

        if ( authorization != null && authorization.Scheme == "Hello" )
          loginToken = authorization.Parameter;
      }

      if ( loginToken == null )
      {
        var cookie = request.Headers.GetCookies( "loginToken" ).SelectMany( c => c.Cookies );
        if ( cookie.Any() )
          loginToken = cookie.First().Value;

      }


      var userId = Host.UserService.GetUserID( loginToken );
      if ( userId == null )
        actionContext.Response = request.CreateErrorResponse( HttpStatusCode.Unauthorized, "Unauthorized" );

      else
        actionContext.Request.Properties["UserID"] = userId;
    }
Example #3
0
        protected override bool IsAuthorized(System.Web.Http.Controllers.HttpActionContext actionContext)
        {
            bool result = base.IsAuthorized(actionContext);

            Console.WriteLine(result);
            return(true);
        }
 public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext actionContext)
 {
     if (actionContext.ModelState.IsValid == false)
     {
         actionContext.Response = actionContext.Request.CreateErrorResponse(HttpStatusCode.BadRequest, actionContext.ModelState);
     }
 }
Example #5
0
        //重写基类的验证方式,加入我们自定义的Ticket验证
        public override void OnAuthorization(System.Web.Http.Controllers.HttpActionContext actionContext)
        {
            //url获取token
            var content = actionContext.Request.Properties["MS_HttpContext"] as HttpContextBase;
            var token   = content.Request.Headers["sessionID"];

            if (!string.IsNullOrEmpty(token) && token != "undefined")
            {
                //解密用户ticket,并校验用户名密码是否匹配
                if (ValidateTicket(token))
                {
                    base.IsAuthorized(actionContext);
                }
                else
                {
                    HandleUnauthorizedRequest(actionContext);
                }
            }
            //如果取不到身份验证信息,并且不允许匿名访问,则返回未验证401
            else
            {
                var  attributes  = actionContext.ActionDescriptor.GetCustomAttributes <AllowAnonymousAttribute>().OfType <AllowAnonymousAttribute>();
                bool isAnonymous = attributes.Any(a => a is AllowAnonymousAttribute);
                if (isAnonymous)
                {
                    base.OnAuthorization(actionContext);
                }
                else
                {
                    HandleUnauthorizedRequest(actionContext);
                }
            }
        }
Example #6
0
 public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext actionContext)
 {
     if (actionContext.Request.Headers.Authorization == null)
     {
         actionContext.Response = new System.Net.Http.HttpResponseMessage(System.Net.HttpStatusCode.Unauthorized);
     }
     else
     {
         string authToken    = actionContext.Request.Headers.Authorization.Parameter;
         string decodedToken = Encoding.UTF8.GetString(Convert.FromBase64String(authToken));
         if (!string.IsNullOrEmpty(decodedToken))
         {
             string[] paramters = decodedToken.Split(':');
             if (paramters.Length == 2)
             {
                 ErpUser obj = new ErpUser()
                 {
                     Username = paramters[0],
                     Token    = Guid.Parse(paramters[1])
                 };
                 if (ErpUserRepo.IsValidToken(obj))
                 {
                     return;
                 }
             }
         }
         actionContext.Response = new System.Net.Http.HttpResponseMessage(System.Net.HttpStatusCode.Unauthorized);
     }
 }
        //public override void OnAuthorization(HttpActionContext actionContext)
        //{
        //	var authHeader = actionContext.Request.Headers.Authorization;

        //	if (authHeader != null)
        //	{
        //		var authenticationToken = actionContext.Request.Headers.Authorization.Parameter;
        //		var decodedAuthenticationToken = Encoding.UTF8.GetString(Convert.FromBase64String(authenticationToken));
        //		var usernamePasswordArray = decodedAuthenticationToken.Split(':');
        //		var userName = usernamePasswordArray[0];
        //		var password = usernamePasswordArray[1];
        //		var api_key = ConfigurationManager.AppSettings["basic_api_key"];
        //		var api_secret = ConfigurationManager.AppSettings["basic_api_secret"];

        //		// validacion de credenciales
        //		var isValid = userName == api_key && password == api_secret;

        //		if (isValid)
        //		{
        //			var principal = new GenericPrincipal(new GenericIdentity(userName), null);
        //			Thread.CurrentPrincipal = principal;

        //			return;
        //		}
        //	}

        //	HandleUnathorized(actionContext);
        //}

        public override void OnAuthorization(System.Web.Http.Controllers.HttpActionContext actionContext)
        {
            if (actionContext.Request.Headers.Authorization == null)
            {
                HandleUnathorized(actionContext);
            }
            else
            {
                var basic_api_key    = ConfigurationManager.AppSettings["basic_api_key"];
                var basic_api_secret = ConfigurationManager.AppSettings["basic_api_secret"];

                // Gets header parameters
                string authenticationString = actionContext.Request.Headers.Authorization.Parameter;
                string originalString       = Encoding.UTF8.GetString(Convert.FromBase64String(authenticationString));

                // Gets credenciales
                string api_key    = originalString.Split(':')[0];
                string api_secret = originalString.Split(':')[1];

                // validacion de credenciales
                var isValid = api_key == basic_api_key && api_secret == basic_api_secret;
                if (!isValid)
                {
                    // returns unauthorized error
                    HandleUnathorized(actionContext);
                }
            }

            base.OnAuthorization(actionContext);
        }
Example #8
0
        /// <summary>
        /// Authorizes a given request based on the existence of the API key.
        /// </summary>
        /// <param name="actionContext">The current <see cref="HttpActionContext"/> to inspect.</param>
        private bool AuthorizeRequest(System.Web.Http.Controllers.HttpActionContext actionContext)
        {
            if (Debugger.IsAttached)
            {
                return(true);
            }

            List <string> values = new List <string>();

            try
            {
                values = actionContext.Request.Headers.GetValues("APIKey").ToList();
            }
            catch (Exception)
            { }

            if (values.Count == 0)
            {
                return(false);
            }
            else if (values[0] != ConfigurationManager.AppSettings["APIKey"])
            {
                return(false);
            }

            return(true);
        }
Example #9
0
        public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext actionContext)
        {
            var request = actionContext.Request;
            var headers = request.Headers;

            if (!headers.Contains("X-Requested-With") || headers.GetValues("X-Requested-With").FirstOrDefault() != "XMLHttpRequest")
            {
                TransactionalInformation transactionInformation = new TransactionalInformation();
                transactionInformation.ReturnMessage.Add("Access has been denied.");
                transactionInformation.ReturnStatus = false;
                actionContext.Response = request.CreateResponse <TransactionalInformation>(HttpStatusCode.BadRequest, transactionInformation);
            }
            else
            {
                HttpContext ctx = default(HttpContext);
                ctx = HttpContext.Current;
                if (ctx.User.Identity.IsAuthenticated == false)
                {
                    TransactionalInformation transactionInformation = new TransactionalInformation();
                    transactionInformation.ReturnMessage.Add("Your session has expired.");
                    transactionInformation.ReturnStatus = false;
                    actionContext.Response = request.CreateResponse <TransactionalInformation>(HttpStatusCode.BadRequest, transactionInformation);
                }
            }
        }
Example #10
0
        public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext actionContext)
        {
            string secret  = "myJwtAuthDemo";//加解密的key,如果不一樣會無法成功解密
            var    request = actionContext.Request;

            if (!WithoutVerifyToken(request.RequestUri.ToString()))
            {
                if (request.Headers.Authorization == null || request.Headers.Authorization.Scheme != "Bearer")
                {
                    setErrorResponse(actionContext, "Lost Token");
                }
                else
                {
                    var jwtObject = Jose.JWT.Decode <Dictionary <string, Object> >(
                        request.Headers.Authorization.Parameter,
                        Encoding.UTF8.GetBytes(secret),
                        JwsAlgorithm.HS256);

                    if (IsTokenExpired(jwtObject["Exp"].ToString()))
                    {
                        setErrorResponse(actionContext, "Token Expired");
                    }
                }
            }

            base.OnActionExecuting(actionContext);
        }
        protected override bool IsAuthorized(System.Web.Http.Controllers.HttpActionContext actionContext)
        {
            object        tempRoles = null;
            List <string> lstRoles  = new List <string>();
            var           identity  = ParseAuthorizationHeader(actionContext);

            if (identity == null)
            {
                return(false);
            }

            if (!OnAuthorizeUser(identity.Name, actionContext))
            {
                return(false);
            }

            List <Claim> lstClaims = new List <Claim>();

            if (actionContext.Request.Properties.TryGetValue("Token", out tempRoles))
            {
                EmployeeToken employeeTokenInfo = tempRoles as EmployeeToken;
                lstClaims.Add(new Claim(ClaimTypes.Name, employeeTokenInfo.UserName));
                lstClaims.Add(new Claim(ClaimTypes.UserData, identity.Name));
                lstClaims.Add(new Claim(ClaimTypes.Role, employeeTokenInfo.Type.ToString()));
            }

            ClaimsIdentity  claimsIdentity = new ClaimsIdentity(lstClaims, "MicroBot");
            ClaimsPrincipal principal      = new ClaimsPrincipal(claimsIdentity);

            Thread.CurrentPrincipal = HttpContext.Current.User = principal;
            return(base.IsAuthorized(actionContext));
        }
Example #12
0
        protected override bool IsAuthorized(System.Web.Http.Controllers.HttpActionContext actionContext)
        {
            var headers = actionContext.Request.Headers.Authorization;

            if (headers != null)
            {
                try
                {
                    if (string.IsNullOrWhiteSpace(SessionHelper.SessionId))
                    {
                        return(false);
                    }
                    CacheManagement _cache      = new CacheManagement();
                    var             sessionData = _cache.GetSessionData(headers.Scheme);
                    if (sessionData.ExpirationDate > DateTime.Now)
                    {
                        return(true);
                    }
                }
                catch
                {
                    //return false;
                }
                finally
                {
                }
            }
            return(false);
        }
Example #13
0
        public override void OnAuthorization(System.Web.Http.Controllers.HttpActionContext actionContext)
        {
            //if (!SkipAuthorization(actionContext) && !AuthenticateApplicationService.IsAuthenticated())
            //    throw new UnauthorizeException("nao autorizado");

            base.OnAuthorization(actionContext);
        }
Example #14
0
        public override void OnAuthorization(System.Web.Http.Controllers.HttpActionContext actionContext)
        {
            //base.OnAuthorization(actionContext);
            var headers = actionContext.Request.Headers;

            if (actionContext.Request.Headers.Authorization == null)
            {
                PutUnauthorizedResult(actionContext, "No hay autorización");
            }
            else
            {
                try
                {
                    var userPwd = Encoding.UTF8.GetString(Convert.FromBase64String(headers.Authorization.Parameter));

                    var credArray = userPwd.Split(":".ToCharArray());
                    var userName  = credArray[0];
                    var password  = credArray[1];

                    if (Ion_Auth.Login(userName, password) == false)
                    {
                        PutUnauthorizedResult(actionContext, "No existe usuario");
                    }
                }
                catch (Exception ex)
                {
                    PutUnauthorizedResult(actionContext, ex.Message);
                }
            }
        }
Example #15
0
        /// <summary>
        /// 重写OnActionExecuting方法   在进入控制器之前验证 sign以及 参数合法性信息 add by caoheyang 20150318
        /// </summary>
        /// <param name="actionContext"></param>
        public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext actionContext)
        {
            Stopwatch stop = new Stopwatch();

            actionContext.Request.Properties[Key] = stop;
            stop.Start();
        }
        public virtual void InternalActionExecuting(HttpActionContext actionContext, CancellationToken cancellationToken)
        {
            var contentType = actionContext.Request.Content.Headers.ContentType;
            if (contentType != null && contentType.MediaType != JsonApiFormatter.JSON_API_MIME_TYPE)
            {
                return;
            }

            if (actionContext.ActionArguments.Any(a => a.Value is UpdateDocumentTypeWrapper))
            {
                var argument = actionContext.ActionArguments.First(a => a.Value is UpdateDocumentTypeWrapper);
                var updateDocument = argument.Value as UpdateDocumentTypeWrapper;
                if (updateDocument != null)
                {
                    var resultType = updateDocument.Type.GetGenericArguments()[0];
                    var context = new Context
                    {
                        Configuration = configuration,
                        RoutePrefix = GetRoutePrefix(actionContext)
                    };

                    var result = jsonApiTransformer.TransformBack(updateDocument.UpdateDocument, resultType, context);
                    actionContext.ActionArguments[argument.Key] = result;
                }
            }
        }
 public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext actionContext)
 {
     HttpContext.Current.Response.TrySkipIisCustomErrors = true;
     if (!actionContext.ModelState.IsValid)
     {
         var controller = actionContext.ControllerContext.Controller as TSICAppJsonAPIController;
         if (controller != null)
         {
             actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.OK, controller.CreateValidationResponse(actionContext.ModelState));
         }
         else
         {
             var errors = actionContext.ModelState
                          .Where(e => e.Value.Errors.Count > 0)
                          .Select(e => new Error {
                 Name    = e.Key,
                 Message = e.Value.Errors.First().ErrorMessage
             }).ToArray();
             actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.BadRequest, new ErrorList {
                 Errors  = errors,
                 Status  = "ValidationFailed",
                 Message = "数据绑定检查失败"
             });
         }
     }
 }
        protected override void HandleUnauthorizedRequest(System.Web.Http.Controllers.HttpActionContext actionContext)
        {
            var controller = actionContext.ControllerContext.Controller as TSICAppJsonAPIController;

            if (controller != null)
            {
                actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized, new AppJsonResponse()
                {
                    Meta = new JsonAsyncObjectMetaData()
                    {
                        Type = "UnauthorizedModel",
                        Uri  = "Unauthorized",
                    },
                    Data = new UnauthorizedModel()
                    {
                        RequireUri = controller.GetUriFromLocalPath(),
                        Message    = "未授权的请求",
                    }
                });
            }
            else
            {
                base.HandleUnauthorizedRequest(actionContext);
            }
        }
        public void Should_return_context_with_webApi_related_keys()
        {
            // Arrange
            var att = new OutputCacheAttributeWithPublicMethods();
            var dependencyScope = Substitute.For<IDependencyScope>();
            var request = new HttpRequestMessage
            {
                Method = HttpMethod.Get,
                RequestUri = new Uri("http://localhost/api"),
                Properties = { { "MS_DependencyScope", dependencyScope } }, //https://github.com/ASP-NET-MVC/aspnetwebstack/blob/master/src/System.Web.Http/Hosting/HttpPropertyKeys.cs
                Headers = { },
                Content = new StringContent("Content...")
            };

            var actionContext = new HttpActionContext(
                new HttpControllerContext(
                    new HttpConfiguration(),
                    Substitute.For<IHttpRouteData>(), request),
                Substitute.For<HttpActionDescriptor>());

            // Action
            var context = att.GetInvocationContextPublic(actionContext);

            // Assert
            Assert.AreSame(att, context[Global.__flatwhite_outputcache_attribute]);
            Assert.AreSame(dependencyScope, context[WebApiExtensions.__webApi_dependency_scope]);
            Assert.IsTrue((bool)context[WebApiExtensions.__webApi]);
            Assert.IsNotNull(context["headers"]);
            Assert.IsNotNull(context["method"]);
            Assert.IsNotNull(context["requestUri"]);
            Assert.IsNotNull(context["query"]);
        }
        public override void OnAuthorization(System.Web.Http.Controllers.HttpActionContext actionContext)
        {
            var headers = actionContext.Request.Headers;

            if (headers.Authorization != null && headers.Authorization.Scheme == "Basic")
            {
                try
                {
                    var userPwd  = Encoding.UTF8.GetString(Convert.FromBase64String(headers.Authorization.Parameter));
                    var user     = userPwd.Substring(0, userPwd.IndexOf(':'));
                    var password = userPwd.Substring(userPwd.IndexOf(':') + 1);
                    // Validamos user y password (aquí asumimos que siempre son ok)
                    if (!user.Equals("my_user") || !password.Equals("my_password"))
                    {
                        PutUnauthorizedResult(actionContext, "Invalid Authorization header");
                    }
                }
                catch (Exception)
                {
                    PutUnauthorizedResult(actionContext, "Invalid Authorization header");
                }
            }
            else
            {
                // No hay el header Authorization
                PutUnauthorizedResult(actionContext, "Auhtorization needed");
            }
        }
Example #21
0
        public override void OnAuthorization(System.Web.Http.Controllers.HttpActionContext actionContext)
        {
            base.OnAuthorization(actionContext);
            if (actionContext.Request.Headers.Authorization == null)
            {
                actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);
            }
            else
            {
                string   encoded  = actionContext.Request.Headers.Authorization.Parameter.ToString();
                string   decoded  = Encoding.UTF8.GetString(Convert.FromBase64String(encoded));
                string[] arr      = decoded.Split(new char[] { ':' });
                string   username = arr[0];
                string   password = arr[1];
                int      x        = 10;
                x = Security.Login(username, password);

                if (x == 0 || x == 1 || x == 2)
                {
                    Thread.CurrentPrincipal = new GenericPrincipal(new GenericIdentity("admin"), null);
                }
                else
                {
                    actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);
                }
            }
        }
Example #22
0
        private bool Authorize(System.Web.Http.Controllers.HttpActionContext actionContext)
        {
            try
            {
                var container = new UnityContainer();
                container.RegisterType <IClienteRepository, ClienteRepository>();
                var clienteService = container.Resolve <ClienteRepository>();

                var httpRequestHeaderToken = actionContext.Request.Headers.GetValues("Authorization").FirstOrDefault();

                var token = clienteService.CheckTokenAuthorization(httpRequestHeaderToken);

                if (token)
                {
                    return(true);
                }
                else
                {
                    return(false);
                }
            }
            catch (Exception ex)
            {
                return(false);
            }
        }
 private bool IsApiPageRequested(HttpActionContext actionContext)
 {
     var apiAttributes = GetApiAuthorizeAttributes(actionContext.ActionDescriptor);
     if (apiAttributes != null && apiAttributes.Any())
         return true;
     return false;
 }
Example #24
0
        public static bool SkipAuthorization(System.Web.Http.Controllers.HttpActionContext actionContext)
        {
            Contract.Assert(actionContext != null);

            return(actionContext.ActionDescriptor.GetCustomAttributes <System.Web.Mvc.AllowAnonymousAttribute>().Any() ||
                   actionContext.ControllerContext.ControllerDescriptor.GetCustomAttributes <System.Web.Mvc.AllowAnonymousAttribute>().Any());
        }
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            var taskId = (long) actionContext.ActionArguments[ActionParameterNames.TaskId];
            var taskFragment =
                (JObject) actionContext.ActionArguments[ActionParameterNames.TaskFragment];
            _log.DebugFormat("{0} = {1}", ActionParameterNames.TaskFragment, taskFragment);

            if (taskFragment == null)
            {
                const string errorMessage = "Malformed or null request.";
                _log.Debug(errorMessage);
                actionContext.Response = actionContext.Request.CreateErrorResponse(
                    HttpStatusCode.BadRequest, errorMessage);
                return;
            }

            try
            {
                var task = taskFragment.ToObject<Task>();
                if (task.TaskId.HasValue && task.TaskId != taskId)
                {
                    const string errorMessage = "Task ids do not match.";
                    _log.Debug(errorMessage);
                    actionContext.Response = actionContext.Request.CreateErrorResponse(
                        HttpStatusCode.BadRequest, errorMessage);
                }
            }
            catch (JsonException ex)
            {
                _log.Debug(ex.Message);
                actionContext.Response = actionContext.Request.CreateErrorResponse(
                    HttpStatusCode.BadRequest, ex.Message);
            }
        }
        /// <summary>
        /// Override to Web API filter method to handle Basic Auth check
        /// </summary>
        /// <param name="actionContext"></param>
        public override void OnAuthorization(HttpActionContext actionContext)
        {
            if (Active)
            {
                var identity = ParseAuthorizationHeader(actionContext);
                if (identity == null)
                {
                    Challenge(actionContext);
                    return;
                }

                if (!OnAuthorizeUser(identity.Name, identity.Password, actionContext))
                {
                    Challenge(actionContext);
                    return;
                }

                var principal = new GenericPrincipal(identity, null);

                Thread.CurrentPrincipal = principal;

                // inside of ASP.NET this is also required for some async scenarios
                //if (HttpContext.Current != null)
                //    HttpContext.Current.User = principal;

                base.OnAuthorization(actionContext);
            }
        }
        private ModelBindingContext GetModelBindingContext(ModelMetadataProvider metadataProvider, HttpActionContext actionContext)
        {
            string name = Descriptor.ParameterName;
            Type type = Descriptor.ParameterType;

            string prefix = Descriptor.Prefix;

            IValueProvider vp = CreateValueProvider(this._valueProviderFactories, actionContext);

            if (_metadataCache == null)
            {
                Interlocked.Exchange(ref _metadataCache, metadataProvider.GetMetadataForType(null, type));
            }

            ModelBindingContext ctx = new ModelBindingContext()
            {
                ModelName = prefix ?? name,
                FallbackToEmptyPrefix = prefix == null, // only fall back if prefix not specified
                ModelMetadata = _metadataCache,
                ModelState = actionContext.ModelState,
                ValueProvider = vp
            };
            
            if (_validationNodeCache == null)
            {
                Interlocked.Exchange(ref _validationNodeCache, ctx.ValidationNode);
            }
            else
            {
                ctx.ValidationNode = _validationNodeCache;
            }

            return ctx;
        }
 public override void OnActionExecuting(HttpActionContext actionContext)
 {
     if (!actionContext.ModelState.IsValid)
     {
         actionContext.Response = actionContext.Request.CreateErrorResponse(HttpStatusCode.BadRequest, actionContext.ModelState);
     }
 }
Example #29
0
        AuthorizationRequest GetAuthorizationRequest(HttpActionContext actionContext)
        {
            AuthorizationRequest authorizationRequest = actionContext.GetAuthorizationRequest();

            try
            {
                var absolutePath = actionContext.Request.RequestUri.AbsolutePath;
                var startIndex = GetNameStartIndex(absolutePath);
                if(startIndex > -1)
                {
                    var resourceName = HttpUtility.UrlDecode(absolutePath.Substring(startIndex, absolutePath.Length - startIndex));
                    var resource = ResourceCatalog.Instance.GetResource(GlobalConstants.ServerWorkspaceID, resourceName);

                    if(resource != null && resource.ResourceType == ResourceType.ReservedService)
                    {
                        authorizationRequest = new AuthorizationRequest
                        {
                            RequestType = WebServerRequestType.WebExecuteInternalService,
                            User = actionContext.ControllerContext.RequestContext.Principal,
                            Url = actionContext.Request.RequestUri,
                            QueryString = new QueryString(actionContext.Request.GetQueryNameValuePairs())
                        };
                    }
                }
            }
            catch(Exception e)
            {
                Dev2Logger.Log.Error(e);
            }

            return authorizationRequest;
        }
        public static bool AuthorizeUserRequest(HttpActionContext context)
        {
            var configuration = NotificationServiceContext.Current.Configuration;
            var repository = configuration.StorageProvider;
            var message = context.Request;

            Endpoint requestedEndpoint = null;

            if (message.Method != HttpMethod.Delete)
            {
                var readTask = message.Content.ReadAsAsync<Endpoint>();
                readTask.Wait();

                var endpoint = readTask.Result;
                if (endpoint != null)
                {
                    requestedEndpoint = repository.Find(endpoint.ApplicationId, endpoint.TileId, endpoint.ClientId);
                }

                // Since the content is now disposed, we need to restore it so it reaches the action
                message.Content = new ObjectContent<Endpoint>(endpoint, context.ControllerContext.Configuration.Formatters[0]);
            }
            else
            {
                var applicationId = context.ControllerContext.RouteData.Values["applicationId"] as string;
                var tileId = context.ControllerContext.RouteData.Values["tileId"] as string;
                var clientId = context.ControllerContext.RouteData.Values["clientId"] as string;

                requestedEndpoint = repository.Find(applicationId, tileId, clientId);
            }

            return requestedEndpoint == null || requestedEndpoint.UserId == configuration.MapUsername(message);
        }
Example #31
0
        public override void OnAuthorization(System.Web.Http.Controllers.HttpActionContext actionContext)
        {
            var request = actionContext.Request;

            if (request.RequestUri.Scheme != Uri.UriSchemeHttps)
            {
                HttpResponseMessage response;

                if (request.Method.Equals(HttpMethod.Get))
                {
                    response = request.CreateResponse(HttpStatusCode.Found);
                    UriBuilder uri = new UriBuilder(request.RequestUri);
                    uri.Scheme = Uri.UriSchemeHttps;
                    uri.Port   = 443;
                    response.Headers.Location = uri.Uri;
                }
                else
                {
                    response         = request.CreateResponse(HttpStatusCode.InternalServerError);
                    response.Content = new StringContent("This request needs to be made via HTTPS.");
                }

                actionContext.Response = response;
            }
        }
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            var parameters = actionContext.ActionDescriptor.GetParameters();

            foreach (var parameter in parameters)
            {
                object value = null;

                if (actionContext.ActionArguments.ContainsKey(parameter.ParameterName))
                    value = actionContext.ActionArguments[parameter.ParameterName];

                if (value != null)
                    continue;

                value = Activator.CreateInstance(parameter.ParameterType);
                actionContext.ActionArguments[parameter.ParameterName] = value;

                var bodyModelValidator = actionContext.ControllerContext.Configuration.Services.GetBodyModelValidator();
                var metadataProvider = actionContext.ControllerContext.Configuration.Services.GetModelMetadataProvider();

                bodyModelValidator.Validate(value, value.GetType(), metadataProvider, actionContext, string.Empty);
            }

            base.OnActionExecuting(actionContext);
        }
Example #33
0
        /// <summary>
        /// 驗證是反被授權
        /// </summary>
        /// <param name="actionContext"></param>
        public override void OnAuthorization(HttpActionContext actionContext)
        {
            var identity = actionContext.RequestContext.Principal.Identity as ClaimsIdentity;

            var authorized = identity.IntersectScopes(this.Scopes?.Split(',') ?? new string[0]);
            if (!authorized)
            {
                var controller = (BaseApiController)actionContext.ControllerContext.Controller;
                var Fail = new FailOutputModel()
                {
                    ApiVersion = "1.0.0",
                    Method = string.Format("{0}.{1}", controller.ControllerContext.RouteData.Values["controller"], actionContext.Request.Method),
                    Error = new ErrorMessage()
                    {
                        Domain = "API-CountyDistrictRoad",
                        Code = 0,
                        Message = "驗證錯誤",
                        Description = "驗證錯誤"
                    },
                    Id = controller.ResponseId
                };

                actionContext.Response = actionContext.ControllerContext.Request.CreateResponse(HttpStatusCode.Unauthorized, Fail);
            }
        }
        /// <summary>
        /// Check for simple binding parameters in POST data. Bind POST
        /// data as well as query string data
        /// </summary>
        /// <param name="metadataProvider"></param>
        /// <param name="actionContext"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public override Task ExecuteBindingAsync(ModelMetadataProvider metadataProvider,
                                                    HttpActionContext actionContext,
                                                    CancellationToken cancellationToken)
        {
            string stringValue = null;

            NameValueCollection col = TryReadBody(actionContext.Request);
            if (col != null)
                stringValue = col[Descriptor.ParameterName];

            // try reading query string if we have no POST/PUT match
            if (stringValue == null)
            {
                var query = actionContext.Request.GetQueryNameValuePairs();
                if (query != null)
                {
                    var matches = query.Where(kv => kv.Key.ToLower() == Descriptor.ParameterName.ToLower());
                    var keyValuePairs = matches as IList<KeyValuePair<string, string>> ?? matches.ToList();
                    if (keyValuePairs.Any())
                        stringValue = keyValuePairs.First().Value;
                }
            }

            object value = StringToType(stringValue);

            // Set the binding result here
            SetValue(actionContext, value);

            // now, we can return a completed task with no result
            TaskCompletionSource<AsyncVoid> tcs = new TaskCompletionSource<AsyncVoid>();
            tcs.SetResult(default(AsyncVoid));
            return tcs.Task;
        }
 public override void OnActionExecuting(HttpActionContext actionContext)
 {
     try
     {
         var headers = actionContext.Request.Headers;
         if (headers.Authorization != null)
         {
             if (headers.Authorization.Scheme == "Token")
             {
                 using (UserRepo repo = new UserRepo())
                 {
                     var result = repo.Auth(headers.Authorization.Parameter);
                     if (result == null)
                         throw new UnauthorizedException();
                     actionContext.ActionArguments.Add(KEY, result.Value);
                 }
             }
         }
         else
             throw new UnauthorizedException();
     }
     catch (UnauthorizedException)
     {
         actionContext.Response = new HttpResponseMessage
         {
             StatusCode = HttpStatusCode.Unauthorized,
         };
     }
 }
        public virtual Task ExecuteBindingAsync(HttpActionContext actionContext, CancellationToken cancellationToken)
        {
            if (_parameterBindings.Length == 0)
            {
                return TaskHelpers.Completed();
            }

            // First, make sure the actionBinding is valid before trying to execute it. This keeps us in a known state in case of errors.
            foreach (HttpParameterBinding parameterBinder in ParameterBindings)
            {
                if (!parameterBinder.IsValid)
                {
                    // Throwing an exception because the webService developer's action signature is bad.
                    // This exception will be caught and converted into a 500 by the dispatcher
                    return TaskHelpers.FromError(new InvalidOperationException(parameterBinder.ErrorMessage));
                }
            }

            if (_metadataProvider == null)
            {
                HttpConfiguration config = actionContext.ControllerContext.Configuration;
                _metadataProvider = config.Services.GetModelMetadataProvider();
            }

            // Execute all the binders.
            IEnumerable<Task> tasks = from parameterBinder in ParameterBindings select parameterBinder.ExecuteBindingAsync(_metadataProvider, actionContext, cancellationToken);
            return TaskHelpers.Iterate(tasks, cancellationToken, disposeEnumerator: false);
        }
        public Task<HttpResponseMessage> ExecuteAuthorizationFilterAsync(HttpActionContext actionContext, CancellationToken cancellationToken, Func<Task<HttpResponseMessage>> continuation)
        {
            try
            {
                var result = new TokenAuthenticator().Authenticate(actionContext, _authenticator);
            }
            catch (Exception e)
            {
                TaskCompletionSource<HttpResponseMessage> tcs = new TaskCompletionSource<HttpResponseMessage>();
                tcs.SetException(e);
                return tcs.Task;
            }

            if (actionContext.Response != null)
            {
                TaskCompletionSource<HttpResponseMessage> tcs = new TaskCompletionSource<HttpResponseMessage>();
                tcs.SetResult(actionContext.Response);
                return tcs.Task;
            }
            else
            {
                return continuation().ContinueWith<HttpResponseMessage>((tsk) =>
                {
                    HttpResponseMessage response = tsk.Result;
                    return response;

                }, TaskContinuationOptions.OnlyOnRanToCompletion);
            }
        }
        internal static bool ValidateObject(object o, List<ValidationResultInfo> validationErrors, HttpActionContext actionContext)
        {
            // create a model validation node for the object
            ModelMetadataProvider metadataProvider = actionContext.GetMetadataProvider();
            string modelStateKey = String.Empty;
            ModelValidationNode validationNode = CreateModelValidationNode(o, metadataProvider, actionContext.ModelState, modelStateKey);
            validationNode.ValidateAllProperties = true;

            // add the node to model state
            ModelState modelState = new ModelState();
            modelState.Value = new ValueProviderResult(o, String.Empty, CultureInfo.CurrentCulture);
            actionContext.ModelState.Add(modelStateKey, modelState);

            // invoke validation
            validationNode.Validate(actionContext);

            if (!actionContext.ModelState.IsValid)
            {
                foreach (var modelStateItem in actionContext.ModelState)
                {
                    foreach (ModelError modelError in modelStateItem.Value.Errors)
                    {
                        validationErrors.Add(new ValidationResultInfo(modelError.ErrorMessage, new string[] { modelStateItem.Key }));
                    }
                }
            }

            return actionContext.ModelState.IsValid;
        }
        protected override void HandleUnauthorizedRequest(System.Web.Http.Controllers.HttpActionContext actionContext)
        {
            var challengeMessage = new System.Net.Http.HttpResponseMessage(System.Net.HttpStatusCode.Unauthorized);

            challengeMessage.Headers.Add("WWW-Authenticate", "Basic");
            throw new System.Web.Http.HttpResponseException(challengeMessage);
        }
Example #40
0
        private bool AuthorizeRequest(System.Web.Http.Controllers.HttpActionContext actionContext)
        {
            var modulo = actionContext.Request.GetRouteData().Route.RouteTemplate;
            var accion = actionContext.Request.Method.Method;

            return(Util.IsTokenValid(modulo, accion, actionContext.Request.Headers));
        }
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            string token;

            try
            {
                token = actionContext.Request.Headers.GetValues("Authorization-Token").First();
            }
            catch (Exception)
            {
                actionContext.Response = new HttpResponseMessage(System.Net.HttpStatusCode.BadRequest)
                {
                    Content = new StringContent("Missing Authorization-Token")
                };
                return;
            }

            try
            {
		// TODO: here we use simple membership provider, 
		// replace with your own authentication. 
                if (!WebSecurity.UserExists(RsaCrypto.Decrypt(token)))
                {
                    throw new Exception() ;
                }
                base.OnActionExecuting(actionContext);
            }
            catch (Exception)
            {
                actionContext.Response = new HttpResponseMessage(System.Net.HttpStatusCode.Forbidden)
                {
                    Content = new StringContent("Unauthorized User")
                };
            }
        }
 protected override void HandleUnauthorizedRequest(HttpActionContext actionContext)
 {
     base.HandleUnauthorizedRequest(actionContext);
     if (actionContext.Request.Headers.Authorization != null) return;
     var headerValue = String.Format("Basic realm=\"{0}\"", realm);
     actionContext.Response.Headers.Add("WWW-Authenticate", headerValue);
 }
        public Task<HttpResponseMessage> ExecuteActionFilterAsync(HttpActionContext actionContext, CancellationToken cancellationToken, Func<Task<HttpResponseMessage>> continuation)
        {
            if (actionContext.Request.Headers.Contains("X-AccessToken"))
            {
                var tokenvalue = actionContext.Request.Headers.GetValues("X-AccessToken").FirstOrDefault();
                if (!string.IsNullOrWhiteSpace(tokenvalue) && tokenvalue.Equals(ConfigurationManager.AppSettings["token"]))
                {
                    return continuation();
                }
            }
            else if (actionContext.Request.RequestUri.ParseQueryString() != null)
            {
                var queryValues = actionContext.Request.RequestUri.ParseQueryString();
                var tokenvalue = queryValues["token"];
                if (!string.IsNullOrWhiteSpace(tokenvalue) && tokenvalue.Equals(ConfigurationManager.AppSettings["token"]))
                {
                    return continuation();
                }
            }

            return Task.Factory.StartNew(() =>
            {
                var retur = new HttpResponseMessage(HttpStatusCode.Unauthorized)
                {
                    Content = new StringContent("This resource cannot be used without the correct access token")
                };

                return retur;
            });

        }
        public static RequestInfo Collect(HttpActionContext context, IEnumerable<string> exclusions) {
            if (context == null)
                return null;

            var info = new RequestInfo {
                ClientIpAddress = context.Request.GetClientIpAddress(),
                HttpMethod = context.Request.Method.Method
            };

            if (context.Request.Headers.UserAgent != null)
                info.UserAgent = context.Request.Headers.UserAgent.ToString();

            if (context.Request.RequestUri != null) {
                info.Host = context.Request.RequestUri.Host;
                info.IsSecure = context.Request.RequestUri.Scheme == "https";
                info.Path = String.IsNullOrEmpty(context.Request.RequestUri.LocalPath) ? "/" : context.Request.RequestUri.LocalPath;
                info.Port = context.Request.RequestUri.Port;
            }

            if (context.Request.Headers.Referrer != null)
                info.Referrer = context.Request.Headers.Referrer.ToString();

            var exclusionList = exclusions as string[] ?? exclusions.ToArray();
            info.Cookies = context.Request.Headers.GetCookies().ToDictionary(exclusionList);
            info.QueryString = context.Request.RequestUri.ParseQueryString().ToDictionary(exclusionList);
            
            // TODO Collect form data.
            return info;
        }
        public override void OnAuthorization(System.Web.Http.Controllers.HttpActionContext actionContext)
        {
            base.OnAuthorization(actionContext);

            if (actionContext.Request.Headers.Authorization != null)
            {
                string   encoded      = actionContext.Request.Headers.Authorization.Parameter;
                string   decoded      = Encoding.UTF8.GetString(Convert.FromBase64String(encoded));
                string[] splittedData = decoded.Split(new char[] { ':' });
                string   email        = splittedData[0];
                string   password     = splittedData[1];
                if (context.Users.Any(x => x.Email == email) && context.Users.Any(x => x.Password == password))
                {
                    Thread.CurrentPrincipal = new GenericPrincipal(new GenericIdentity(email), null);
                }
                else
                {
                    actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);
                }
            }
            else
            {
                actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);
            }
        }
Example #46
0
        public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext actionContext)
        {
            int timeout = Properties.Settings.Default.CASSession_Timeout;
            var transactionInformation = new TransactionalInformation();
            var httpRequest            = HttpContext.Current.Request;
            var sessionProvider        = ProviderFactory.Instance.CreateSessionServiceProvider();

            var request = actionContext.Request;

            try
            {
                var cookieData   = BOpCookieUtility.GetCookieData(HttpContext.Current.Request);
                var sessionValid = sessionProvider.CheckIfSessionIsValid(cookieData.SessionToken);
                if (!sessionValid)
                {
                    throw new UnauthorizedAccessException("Session not valid!");
                }
            }
            catch (Exception ex)
            {
                transactionInformation.ReturnMessage.Add(ex.Message);
                transactionInformation.ReturnStatus   = false;
                transactionInformation.IsException    = true;
                transactionInformation.IsAuthenicated = false;
                transactionInformation.logoutUrl      = GlobalProperties.LOGIN_PAGE;
                actionContext.Response = request.CreateResponse <TransactionalInformation>(HttpStatusCode.Unauthorized, transactionInformation);

                CookieHeaderValue cookie = new CookieHeaderValue("bops", "st=0");
                cookie.Expires = DateTime.Now.AddDays(-7d);
                cookie.Domain  = actionContext.Request.RequestUri.Host;
                cookie.Path    = "/";

                actionContext.Response.Headers.AddCookies(new CookieHeaderValue[] { cookie });
            }
        }
        public override void OnAuthorization(HttpActionContext actionContext)
        {
            if (actionContext.Request.Content != null &&
                actionContext.Request.Content.Headers.ContentType != null)
            {
                if (allowJson && 
                    actionContext.Request.Content.Headers.ContentType.MediaType == JsonMediaTypeFormatter.DefaultMediaType.MediaType)
                {
                    return;
                }
                
                if (allowFormUrlEncoded && 
                    actionContext.Request.Content.Headers.ContentType.MediaType == FormUrlEncodedMediaTypeFormatter.DefaultMediaType.MediaType)
                {
                    return;
                }

                var env = actionContext.Request.GetOwinEnvironment();
                var localization = env.ResolveDependency<ILocalizationService>();

                actionContext.Response = actionContext.Request.CreateResponse(
                    HttpStatusCode.UnsupportedMediaType, 
                    new { ErrorMessage = localization.GetMessage(MessageIds.UnsupportedMediaType) }
                );
            }
        }
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            ReflectedHttpActionDescriptor actionDescriptor = actionContext.ActionDescriptor as ReflectedHttpActionDescriptor;
            if (null == actionDescriptor)
            {
                base.OnActionExecuting(actionContext);
            }

            CacheKey key = new CacheKey(actionDescriptor.MethodInfo,actionContext.ActionArguments);
            object[] array = HttpRuntime.Cache.Get(key.ToString()) as object[];
            if (null == array)
            {
                base.OnActionExecuting(actionContext);
                return;
            }

            object value = array.Any() ? array[0] : null;
            IHttpActionResult actionResult = value as IHttpActionResult;
            if (null != actionResult)
            {
                actionContext.Response = actionResult.ExecuteAsync(CancellationToken.None).Result;
                return;
            }
            actionContext.Response = actionDescriptor.ResultConverter.Convert(actionContext.ControllerContext, value);
        }
Example #49
0
        ////重写基类的验证方式,加入我们自定义的Ticket验证
        public override void OnAuthorization(System.Web.Http.Controllers.HttpActionContext actionContext)
        {
            //从http请求的头里面获取身份验证信息,验证是否是请求发起方的ticket
            var authorization = actionContext.Request.Headers.Authorization;

            if ((authorization != null) && (authorization.Scheme != null))
            {
                //解密用户ticket,并校验用户名密码是否匹配
                var tokenID = authorization.Scheme;
                if (ValidateTicket(tokenID))
                {
                    base.IsAuthorized(actionContext);
                }
                else
                {
                    HandleUnauthorizedRequest(actionContext);
                }
            }
            //如果取不到身份验证信息,并且不允许匿名访问,则返回未验证401
            else
            {
                var  attributes  = actionContext.ActionDescriptor.GetCustomAttributes <AllowAnonymousAttribute>().OfType <AllowAnonymousAttribute>();
                bool isAnonymous = attributes.Any(a => a is AllowAnonymousAttribute);
                if (isAnonymous)
                {
                    base.OnAuthorization(actionContext);
                }
                else
                {
                    HandleUnauthorizedRequest(actionContext);
                }
            }
        }
        //重写基类的验证方式,加入我们自定义的Ticket验证
        public override void OnAuthorization(System.Web.Http.Controllers.HttpActionContext actionContext)
        {
            var attributes  = actionContext.ActionDescriptor.GetCustomAttributes <AllowAnonymousAttribute>().OfType <AllowAnonymousAttribute>();
            var isAnonymous = attributes.Any(a => a is AllowAnonymousAttribute);

            if (isAnonymous)
            {
                base.OnAuthorization(actionContext);
            }
            else
            {
                //从http请求的头里面获取身份验证信息,验证是否是请求发起方的ticket
                var authorization = actionContext.Request.Headers.Authorization;
                if (authorization?.Parameter != null)
                {
                    //解密用户ticket,并校验用户名密码是否匹配
                    var encryptTicket = authorization.Parameter;
                    if (ValidateTicket(encryptTicket))
                    {
                        base.IsAuthorized(actionContext);
                    }
                    else
                    {
                        HandleUnauthorizedRequest(actionContext);
                    }
                }
                else
                {
                    HandleUnauthorizedRequest(actionContext);
                }
            }
        }
		public override Task OnActionExecutingAsync(HttpActionContext actionContext, CancellationToken cancellationToken)
		{
			var apiKey = System.Configuration.ConfigurationManager.AppSettings["apiKey"];

			var auth = actionContext.Request.Headers.Authorization;
			if (auth == null)
			{
				actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized);
				actionContext.Response.ReasonPhrase = "this service required an api key";
			}
			else if (auth.Scheme == null)
			{
				actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized);
				actionContext.Response.ReasonPhrase = "this service required an api key";
			}
			else if (apiKey == null)
			{
				actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized);
				actionContext.Response.ReasonPhrase = "this service required an api key";
			}
			else if (auth.Scheme != apiKey)
			{
				actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized);
				actionContext.Response.ReasonPhrase = "invalid api key";
			}

			return base.OnActionExecutingAsync(actionContext, cancellationToken);
		}
Example #52
0
        /// <summary>
        /// Public default Constructor
        /// </summary>
        public override void OnActionExecuting(HttpActionContext context)
        {
            AuthModel authModel = new AuthModel();

            var header = context.Request.Headers.SingleOrDefault(x => x.Key == "token");

            bool valid, isAdmin, okDate;

            if (header.Value == null)
            {
                valid = false;
            }
            else
            {
                //tokenul apartine unui admin
                isAdmin = authModel.VerifyAdminToken(header.Value.First());

                //tokenul este valid
                okDate = authModel.VerifyToken(header.Value.First());

                valid = isAdmin && okDate;
            }

            if (!valid)
            {
                //Invalid Authorization Key
                context.Response = context.Request.CreateResponse(HttpStatusCode.Forbidden);
            }
        }
        private static void ChallengeAuthRequest(HttpActionContext filterContext)
        {
            var dnsHost = filterContext.Request.RequestUri.DnsSafeHost;

            filterContext.Response = filterContext.Request.CreateResponse(System.Net.HttpStatusCode.Unauthorized);
            filterContext.Response.Headers.Add("WWW-Authenticate", string.Format("Basic realm=\"{0}\"", dnsHost));
        }
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            var authHead = actionContext.Request.Headers.Authorization;
            if (authHead != null)
            {
                if (authHead.Scheme.Equals("basic", StringComparison.OrdinalIgnoreCase) && authHead.Parameter != null)
                {
                    var credentials = Encoding.GetEncoding("iso-8859-1").GetString(Convert.FromBase64String(authHead.Parameter));

                    int separator = credentials.IndexOf(':');
                    string username = credentials.Substring(0, separator);
                    string password = credentials.Substring(separator + 1);

                    if (apiKeys.Contains(password))
                    {
                        IUserScopedController controller = actionContext.ControllerContext.Controller as IUserScopedController;
                        if (controller != null && !string.IsNullOrWhiteSpace(username))
                        {
                            controller.UserId = username;
                        }
                        return;
                    }
                }
            }

            actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized);
            actionContext.Response.Headers.Add("WWW-Authenticate", string.Format("Basic realm=\"{0}\"", actionContext.Request.RequestUri.Host));
        }
        /// <summary>
        /// Determines whether access for this particular request is authorized. This method uses the user <see cref="IPrincipal"/>
        /// returned via <see cref="Thread.CurrentPrincipal"/>. Authorization is denied if the user is not authenticated,
        /// the user is not in the authorized group of <see cref="Users"/> (if defined), or if the user is not in any of the authorized 
        /// <see cref="Roles"/> (if defined).
        /// </summary>
        /// <param name="actionContext">The context.</param>
        /// <returns><c>true</c> if access is authorized; otherwise <c>false</c>.</returns>
        protected virtual bool IsAuthorized(HttpActionContext actionContext)
        {
            if (actionContext == null)
            {
                throw Error.ArgumentNull("actionContext");
            }

            IPrincipal user = Thread.CurrentPrincipal;
            if (user == null || !user.Identity.IsAuthenticated)
            {
                return false;
            }

            if (_usersSplit.Length > 0 && !_usersSplit.Contains(user.Identity.Name, StringComparer.OrdinalIgnoreCase))
            {
                return false;
            }

            if (_rolesSplit.Length > 0 && !_rolesSplit.Any(user.IsInRole))
            {
                return false;
            }

            return true;
        }
        public virtual bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
        {
            ModelBindingContext newBindingContext = CreateNewBindingContext(bindingContext, bindingContext.ModelName);

            bool boundSuccessfully = TryBind(actionContext, newBindingContext);
            if (!boundSuccessfully && !String.IsNullOrEmpty(bindingContext.ModelName)
                && bindingContext.FallbackToEmptyPrefix)
            {
                // fallback to empty prefix?
                newBindingContext = CreateNewBindingContext(bindingContext, modelName: String.Empty);
                boundSuccessfully = TryBind(actionContext, newBindingContext);
            }

            if (!boundSuccessfully)
            {
                return false; // something went wrong
            }

            // run validation and return the model
            // If we fell back to an empty prefix above and are dealing with simple types,
            // propagate the non-blank model name through for user clarity in validation errors.
            // Complex types will reveal their individual properties as model names and do not require this.
            if (!newBindingContext.ModelMetadata.IsComplexType && String.IsNullOrEmpty(newBindingContext.ModelName))
            {
                newBindingContext.ValidationNode = new Validation.ModelValidationNode(newBindingContext.ModelMetadata, bindingContext.ModelName);
            }

            newBindingContext.ValidationNode.Validate(actionContext, null /* parentNode */);
            bindingContext.Model = newBindingContext.Model;
            return true;
        }
 public override void OnAuthorization(System.Web.Http.Controllers.HttpActionContext actionContext)
 {
     //判断用户是否登录
     if (!HttpContext.Current.User.Identity.IsAuthenticated)
     {
         HandleUnauthorizedRequest(actionContext);
     }
 }
        public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext actionContext)
        {
            //AuthorizationFilterAttribute
            //AuthorizeAttribute

            // OverrideActionFiltersAttribute
            HttpRequestMessageHelper.Add(actionContext.Request, new FilterModel(this.GetType(), GetFilterScope(actionContext.ActionDescriptor)));
        }
Example #59
0
 private bool AuthorizeRequest(System.Web.Http.Controllers.HttpActionContext actionContext)
 {
     if (RoleID.Equals(GetGroup(actionContext)))
     {
         return(true);
     }
     return(false);
 }
Example #60
0
 protected override bool IsAuthorized(System.Web.Http.Controllers.HttpActionContext actionContext)
 {
     if (SessionManager.IsUserLoggedIn == false)
     {
         return(false);
     }
     return(true);
 }