This is a good place to appy an ActionFilter
. If the user parameter in the Url does not match the FormsAuthentication
user you can take the appropriate action. Putting the logic in an ActionFilter
allows to perform this check in other places in your application -- DRY.
Here is a sample you can tweak to your own needs that should give you an idea of what to do.
using System.Globalization;
using System.Web.Mvc;
using System.Web.Security;
public class RequiresAuthorizationAttribute : ActionFilterAttribute
{
/// <summary>
/// Checks user's authentication and authorization using FormsAuthentication
/// and redirects failure to login page.
/// </summary>
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
string redirectOnSuccess = filterContext.HttpContext.Request.Url.AbsolutePath;
string redirectUrl = string.Format("?ReturnUrl={0}", redirectOnSuccess);
string loginUrl = FormsAuthentication.LoginUrl + redirectUrl;
if (filterContext.HttpContext.User.Identity.IsAuthenticated)
{
string contextUserId = filterContext.RequestContext.HttpContext.User.Identity.Name;
string urlUserId = filterContext.ActionParameters["id"].ToString();
if (string.Compare(contextUserId, urlUserId, true, CultureInfo.InvariantCulture) != 0)
{
//if user is not authorized redirect to login page.
filterContext.HttpContext.Response.Redirect(loginUrl, true);
}
}
else
{
//if user is not authenticated redirect to login page.
filterContext.HttpContext.Response.Redirect(loginUrl, true);
}
}
}
Then you would decorate your controller method with the RequiresAuthorizationAttribute like
[RequiresAuthorization]
public ActionResult Edit()
{
// do editing.
}