.Net MVC authorization Controller and Workcontext extension in razor view


firstly make a inheritance on original Controller,
then override Initialize function, OnActionExecuting function,
which this controller would be inherited by all our Controllers.

namespace Auth.Service
{
    [UserAuthorize]
    public class WebBaseController : Controller
    {
        protected string errmsg;
        public WebBaseWorkContext WorkContext { get; set; }

        /// <summary>
        /// init
        /// </summary>
        /// <param name="requestContext"></param>
        protected override void Initialize(RequestContext requestContext)
        {
            base.Initialize(requestContext);
            WorkContext = new WebBaseWorkContext();
            ViewBag.Title = "";
        }

        /// <summary>
        /// Called before the action method is invoked.
        /// </summary>
        /// <param name="filterContext"></param>
        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            base.OnActionExecuting(filterContext);

            WorkContext.User = UserPrincipal.User;
        }

        /// <summary>
        /// before return the result
        /// </summary>
        /// <param name="filterContext"></param>
        protected override void OnResultExecuting(ResultExecutingContext filterContext)
        {
            base.OnResultExecuting(filterContext);
            WorkContext.ModelState = ModelState;
        }

        protected void Alert(string message)
        {
            ViewBag.Alert = message;
        }
    }
}

then UserPrincipal to make a get constructor, which would change the value of the boolean isAuthenticated

namespace Auth.Service
{
    public static class UserPrincipal
    {
        /// <summary>
        /// User
        /// </summary>
        public static UserIdentity User
        {
            get
            {
                //get user info from cookie

                UserIdentity cookieUserIdentity = new UserIdentity();
                if(HttpContext.Current.Request.Cookies["account"] != null)
                    cookieUserIdentity.account = HttpContext.Current.Request.Cookies["account"].Value;
                if (HttpContext.Current.Request.Cookies["password"] != null)
                    cookieUserIdentity.password = HttpContext.Current.Request.Cookies["password"].Value;


                if (string.IsNullOrEmpty(cookieUserIdentity.account))
                {
                    return null;
                }
                return cookieUserIdentity;
            }

        }

        /// <summary>
        /// is valid the user
        /// </summary>
        public static bool IsAuthenticated
        {
            get { return User != null; }
        }
    }
}

Then, we make a anootation let us run this class before a Controller, meanning we would put it on our every Controller.

    public class UserAuthorize : ActionFilterAttribute
    {
        /// <summary>
        /// no need to make a Authorization
        /// </summary>
        public bool NoAuthorize { get; set; }

        /// <summary>
        /// Authorize before the action
        /// </summary>
        /// <param name="filterContext"></param>
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            base.OnActionExecuting(filterContext);

            if (NoAuthorize)
                return;
            //if IsAuthenticated is false, go back to the Login action
            if (!UserPrincipal.IsAuthenticated)
            {
                filterContext.Result = new RedirectToRouteResult(new System.Web.Routing.RouteValueDictionary() { { "Area", "" }, { "Controller", "Home" }, { "Action", "Login" } });
                return;
            }

            string controller = filterContext.RouteData.Values["controller"].ToString();

            if (controller == "Home")
                return;
        }
    }

This is a extention for All Razor page

namespace Auth.Service
{
    /// <summary>
    /// attributes and functions which Razor page would need
    /// </summary>
    [ValidateInput(false)]
    public abstract class WebBaseViewPage<TModel> : System.Web.Mvc.WebViewPage<TModel>
    {

        public WebBaseWorkContext WorkContext;

        public override void InitHelpers()
        {
            base.InitHelpers();
            WorkContext = ((WebBaseController)(this.ViewContext.Controller)).WorkContext;
        }

        public override void Write(object value)
        {
            Output.Write(value);
        }

        public override void Execute()
        {
        }
    }
    /// <summary>
    /// attributes and functions which Razor page would need
    /// </summary>
    public abstract class WebViewPage : WebViewPage<dynamic>
    {

    }
}

this is a custom extension class that we will need.

    public class WebBaseWorkContext
    {
        public ModelStateDictionary ModelState { get; set; }

        /// <summary>
        /// Info of User
        /// </summary>
        public UserIdentity User { get; set; }
    }

then, we need to connect our custom razor extension to all razor view in our view/web.config

  <system.web.webPages.razor>
    <host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=5.2.3.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
    <!--<pages pageBaseType="System.Web.Mvc.WebViewPage">-->
    <pages pageBaseType="Auth.Service.WebBaseViewPage"> // this is the class which is our extension
      <namespaces>
        <add namespace="System.Web.Mvc" />
        <add namespace="System.Web.Mvc.Ajax" />
        <add namespace="System.Web.Mvc.Html" />
        <add namespace="System.Web.Optimization"/>
        <add namespace="System.Web.Routing" />
        <add namespace="Auth" />
        <add namespace="Auth.Service"/> // this is the namespace of our extension class
      </namespaces>
    </pages>
  </system.web.webPages.razor>

After these file, we add a notation on our every controller, and controllers need to inherit our custom WebBaseController, and we can do our ahuthorization every controller and action, use our custom WorkContext class in any razor page as well.

#C# #.Net Framework #Razor Page #authorization #authentication






你可能感興趣的文章

淺談 Session 與 Cookie:一起來讀 RFC

淺談 Session 與 Cookie:一起來讀 RFC

[BE201] 後端中階:ORM 與 Sequelize

[BE201] 後端中階:ORM 與 Sequelize

SOLID 設計原則筆記

SOLID 設計原則筆記






留言討論