asp.net mvc authorization problem
I am trying to add authorization to my controllers and it's not working...
I am not sure where to look in my program, but adding the
[Authorize]
filter in my controller is not working, let alone anything like
[Authorize(Roles = "Manager")]
I have been able to get this working in the default application that is provided when creating a new MVC project (i.e., I am able to make the "about" tab redirect to the login screen if I'm not logged in), so I assume I have mucked things up along the开发者_如何转开发 way as I've built my app. Does anyone know where I should be looking to fix this? I have users and they have roles; I'm using the ASP.net schema that is auto-created; I've examined my web.config file up and down and although I'm pretty new to this, nothing seems to be out of place. I have no clue why my authorization filters aren't working.?.
I wrote a custom attribute to solve this problem. You can attribute your controller methods as follows:
[RequiresRole(Role="Admin")]
public ActionResult Index()
{
int i = 5 + 5;
return View();
}
The code for the attribute is as follows....
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
namespace Web.Controllers
{
public class RequiresRoleAttribute : ActionFilterAttribute
{
public string Role { get; set; }
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (string.IsNullOrEmpty(Role))
{
throw new InvalidOperationException("No role specified.");
}
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)
{
filterContext.HttpContext.Response.Redirect(loginUrl, true);
}
else
{
bool isAuthorised = filterContext.HttpContext.User.IsInRole(this.Role);
if (!isAuthorised)
{
filterContext.HttpContext.Response.Redirect(loginUrl, true);
}
}
}
}
}
精彩评论