Is it possible to override the default behavior of [Authorize] in ASP.NET MVC?

前端 未结 5 1941
夕颜
夕颜 2020-12-16 03:05

I wondered if/how I can override the default [Authorize] behavior in ASP.NET MVC. I know that I can create a new Action Filter, make my own attribute and so forth; I am mere

5条回答
  •  盖世英雄少女心
    2020-12-16 03:27

    You can subclass the AuthorizeAttribute filter and put your own logic inside it.

    Let's see an example. Let's say you want to always authorize local connections. However, if it is a remote connection, you would like to keep the usual authorization logic.

    You could do something like:

    public class LocalPermittedAuthorizeAttribute : AuthorizeAttribute
    {
        protected override bool AuthorizeCore(HttpContextBase httpContext)
            {
                return (httpContext.Request.IsLocal || base.AuthorizeCore(httpContext)));
            }
    }
    

    Or you could always authorize a certain remote address (your machine, for example).

    That's it!

    Edit: forgot to mention, you will use it the same as you would use the AuthorizeAttribute filter:

    class MyController : Controller
    {
        [LocalPermittedAuthorize]
        public ActionResult Fire()
        {
            Missile.Fire(Datetime.Now);
        }
    }
    

提交回复
热议问题