If Controller.OnAuthorization () returns void, then how can I deny access?

I would expect it to return "true" or "false" ...

I overridden OnAuthorization in my controller and based on missing or invalid HTTP header value. I want to return the 403 ban, however, I cannot figure out how to return anything from OnAuthorization so that it actually stops the rest of the controller launch.

What should I do?

My first attempt below was a huge failure, I think Deny () works, but nothing happens ...

public class AuthController : Controller
    {
        protected override void OnAuthorization(AuthorizationContext filterContext)
        {
            if (string.IsNullOrEmpty(filterContext.HttpContext.Request.Headers["Authorization"]))
                Deny();

            string authString = filterContext.HttpContext.Request.Headers["Authorization"];

            base.OnAuthorization(filterContext);
        }

        private ActionResult Deny()
        {
            HttpContext.Response.StatusCode = 403;

            return Content("Access Denied", "text/plain");
        }
    }

UPDATE looks like it's a trick, for some reason, why could this be a bad approach?

    if (string.IsNullOrEmpty(filterContext.HttpContext.Request.Headers["Authorization"]))
    {
        filterContext.Result = Content("Access Denied", "text/plain");
        filterContext.HttpContext.Response.StatusCode = 403;

        base.OnAuthorization(filterContext);
    }

UPDATE AGAIN ok, ... , INTO if base.OnAuthorization(...) call, ... if, ? , base.OnAuthorization(...) ?

+5
5

httpexception:

throw new HttpException(403, "Access Denied");
+8

?

throw new UnauthorizedAccessException();
+4
+1

:

filterContext.Result.Result = new RedirectToRouteResult(new RouteValueDictionary(new { controller = "Message", action = "AccessDenied" }));

:)

0

In fact, when the controller is called for ActionResult, the page expects a View. You can implement the following user interface so that the user can better understand:

//code for checking whether authorized goes here...//
bool isAuthorised = SomeFunction();
if (!isAuthorised)
{
    var viewData = new ViewDataDictionary();
    viewData.Add("Message", "You do not have sufficient privileges for this operation.");
    filterContext.Result = new ViewResult { ViewName = "Unauthorized", ViewData = viewData };
    //The View "Unauthorized" is merely a View page that could inherit from a master View or none,       
    //and could be situated in your Views\Shared folder.
    //And you can present the message in the View page like this or so: 
    //<div style="color:Red; font-size:12pt; font-weight:bold;"> <%:ViewData["Message"] %></div>
}
return;

The "Unauthorized" view can be any name you want, and it must be a view that is in the view's public folder.

0
source

All Articles