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
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:
- OnAuthorisation : here your authorisation logic goes.Here it is checking for handelling unauthorized request.
- HandleUnauthorizedRequest :here logic for handelling unauthorized access goes.It is calling it's parrent's class HandleUnauthorizedRequest to get executed for handling unauthorized access.