Correct way to authorize an ASMX .NET web service from MVC 4 Project

后端 未结 4 2175
萌比男神i
萌比男神i 2021-02-14 00:59

I have an ASP.NET MVC application that has a .asmx web service

I wrote an action filter attribute that I wanted to use on web methods on the web service, to che

4条回答
  •  既然无缘
    2021-02-14 01:14

    I think creating custom attribute filter for Authorization will be good idea. You can create your costume filter that customizes authorization as like this.

    namespace CustomeFilters
    {
        class CustomAuthorize : AuthorizeAttribute
        {
            private const string _securityParameter = "someCredentials"; // Name of the url parameter. 
            public override void OnAuthorization(AuthorizationContext filterContext)
            {
                if (Authorize(filterContext))
                {
                    return;
                }
    
                HandleUnauthorizedRequest(filterContext);
            }
    
    
        protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {
            //Your logic for unauthorized access
            HttpRequestBase request = filterContext.RequestContext.HttpContext.Request;
            string deviceId = request.Params[_securityParameter]; //Your may have values in request headers
    
            if (!string.IsNullOrEmpty(_securityParameter ))
            {
                base.HandleUnauthorizedRequest(filterContext);
    
            }
    
            //You can also check if request is authorized as basic authentication or not
            //if(!filterContext.HttpContext.User.Identity.IsAuthenticated)
        }
    
    
        private bool Authorize(AuthorizationContext actionContext)
        {
                HttpRequestBase request = actionContext.RequestContext.HttpContext.Request;
    
                // Your authorisation logic goes here..                                     
    
               //actionContext.RequestContext.HttpContext.Response.StatusCode = 400;
    
               //actionContext.Result = new JsonResult { JsonRequestBehavior = JsonRequestBehavior.AllowGet, Data = "Request from invalid device !" };
    
                bool success = ;//Acording to authorisation logic
                return success;
        }
    }
    

    It will be used like this

        [CustomAuthorize]
        public ActionResult Test()
        { 
            ViewBag.Message = "Hello World.";
    
            return View();
        }
    

    Here you are inheriting Authorize attribute from MVC authorization. It is overriding two methods:

    1. OnAuthorisation : here your authorisation logic goes.Here it is checking for handelling unauthorized request.
    2. HandleUnauthorizedRequest :here logic for handelling unauthorized access goes.It is calling it's parrent's class HandleUnauthorizedRequest to get executed for handling unauthorized access.

提交回复
热议问题