2

I use Authorize attribute to check if user is authorized or not to enter special view.

    [HttpGet]
    [Authorize]
    public ActionResult Index(int ID)
    {
             ViewBag.sID = ID;
             return View();
    }

Suppose this is mu URL : localhost:16621/Panel/Index/1 Now this authorized user can change 1 to 2 and navigate to another user information. Like localhost:16621/Panel/Index/2 How to prevent from this??? Is there any way to pass parameter to authorize attribute? How to prevent user from access another user information?

Dmitry Efimenko
  • 10,973
  • 7
  • 62
  • 79
Angelina
  • 103
  • 4
  • 10
  • 2
    Angelina. this is so many time already asked on SO. http://stackoverflow.com/questions/2329197/custom-form-authentication-authorization-scheme-in-asp-net-mvc?rq=1 http://stackoverflow.com/questions/427598/customizing-authorization-in-asp-net-mvc?rq=1 http://stackoverflow.com/questions/554094/asp-net-mvc-adding-to-the-authorize-attribute?rq=1 – Ashwini Verma Jul 08 '13 at 15:17
  • Look into this post, it does exactly what you want it to. http://stackoverflow.com/questions/10064631/mvc-3-access-for-specific-user-only – SOfanatic Jul 08 '13 at 16:31

2 Answers2

4

I'm afraid there is no magical switch - [Authorize] just kick off unauthorized users, users that are not within specified range, or users in wrong role. Safety of context-bound data is up to you - you'll have to do it within Index() body and redirect user elsewhere if the passed id is not available for actual user.

Ondrej Svejdar
  • 21,349
  • 5
  • 54
  • 89
1

There is a "AuthenticationFilter" ASP.NET MVC5 available for exactly this purpose.

Authentication filters

Authentication filters are a new kind of filter in ASP.NET MVC that run prior to authorization filters in the ASP.NET MVC pipeline and allow you to specify authentication logic per-action, per-controller, or globally for all controllers. Authentication filters process credentials in the request and provide a corresponding principal. Authentication filters can also add authentication challenges in response to unauthorized requests.

See this tutorial for how to use it.

using System.Web.Mvc;
using System.Web.Mvc.Filters;

namespace VSMMvc5AuthFilterDemo.CustomAttributes
{
  public class BasicAuthAttribute : ActionFilterAttribute, IAuthenticationFilter
  {
    public void OnAuthentication(AuthenticationContext filterContext)
    {
    }

    public void OnAuthenticationChallenge(AuthenticationChallengeContext filterContext)
    {
      var user = filterContext.HttpContext.User;
      if (user == null || !user.Identity.IsAuthenticated)
      {
        filterContext.Result = new HttpUnauthorizedResult();
      }
    }
  }
}
s.meijer
  • 3,403
  • 3
  • 26
  • 23