How to restrict access to certain actions in controller in ASP.net MVC

前端 未结 4 720
甜味超标
甜味超标 2020-12-29 16:33

I am new to ASP.net MVC and created my first web application using it. In my application I am using database authentication. I have created Login action in controller which

相关标签:
4条回答
  • 2020-12-29 16:48

    There are multiple ways of doing it but the preferred way would be to use the Annotation. Here is a post for it How to get custom annotation attributes for a controller action in ASP.NET MVC 4?

    If you are getting started I would suggest to follow the tutorial on http://www.asp.net/mvc

    0 讨论(0)
  • 2020-12-29 16:55

    you should create a basecontroller and inherit other controlers from base controller and then check whether the session is null or not to authenticate users.

     public class BaseController : Controller
     {
            protected override void OnActionExecuting(ActionExecutingContext filterContext)
            {
                if (Session["User"]== null)
                {
                   filterContext.HttpContext.Response.Redirect("/somepage");
            }
    
     }
    
    public class SomeController : BaseController
    {
    
    }
    
    0 讨论(0)
  • 2020-12-29 16:58

    I apply [Authorize] as well as my own customattribute for restricting the action based on permission. The code is below

     [Authorize]
     [FeatureAuthentication(AllowFeature=FeatureConst.ShowDashboard)]
     public ActionResult Index()
        {
    
        }
    

    Filter code

    public class FeatureAuthenticationAttribute : FilterAttribute, IAuthorizationFilter
     {
        public FeatureConst AllowFeature { get; set; }
    
        public void OnAuthorization(AuthorizationContext filterContext)
        {
            //var featureConst = (FeatureConst)filterContext.RouteData.Values["AllowFeature"];
    
            var filterAttribute = filterContext.ActionDescriptor.GetFilterAttributes(true)
                                    .Where(a => a.GetType() == typeof(FeatureAuthenticationAttribute));
            if (filterAttribute != null)
            {
                foreach (FeatureAuthenticationAttribute attr in filterAttribute)
                {
                    AllowFeature = attr.AllowFeature;
                }
    
                User currentLoggedInUser = (User)filterContext.HttpContext.Session["CurrentUser"];
                bool allowed = ACLAccessHelper.IsAccessible(AllowFeature.ToString(), currentLoggedInUser);
                // do your logic...
                if (!allowed)
                {
                    string unAuthorizedUrl = new UrlHelper(filterContext.RequestContext).RouteUrl(new { controller = "home", action = "UnAuthorized" });
                    filterContext.HttpContext.Response.Redirect(unAuthorizedUrl);
                }
            }
        }
     }
    
    0 讨论(0)
  • 2020-12-29 17:04

    If you are using FormsAuthentication you don't need to use ASP.NET session to track the currently authenticated user.

    I read about Authorize attribute but don't know how to use it as I am using database authentication.

    Assuming you went with FormsAuthentication, once you have validated the credentials of the user you should set a forms authentication cookie:

    public ActionResult Login()
    {
       if(uservalid)
       {
          FormsAuthentication.SetAuthCookie("username", false);
          return RedirectToAction("SomeProtectedAction");
       }
       else
       {
          //redirect to login
       }
    }
    

    and then:

    [Authorize]
    public ActionResult SomeAction()
    {
       string currentlyLoggedInUser = User.Identity.Name;
    }
    

    By the way if you create a new ASP.NET MVC application using the internet template in Visual Studio you might take a look at the AccountController which is responsible for authenticating users and setting forms authentication cookies. Of course you could throw all the Entity Framework crap out of it and implement your own credentials validation against your own database tables.

    0 讨论(0)
提交回复
热议问题