Angelina
Angelina

Reputation: 103

Using authorize attribute ASP.Net MVC

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?

Upvotes: 2

Views: 4586

Answers (2)

s.meijer
s.meijer

Reputation: 3909

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();
      }
    }
  }
}

Upvotes: 1

Ondrej Svejdar
Ondrej Svejdar

Reputation: 22054

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.

Upvotes: 4

Related Questions