How do I lock down a controller class to only be accessible by one or more roles? I’ve tried using the AuthorizeAttribute in my second example, but it seems to force authorization to be requested, instead of granting access to the page.
[PrincipalPermission(SercurityAction.?????????)]
public class MySecuredController { ...
OR
[Authorize(Roles="MyRoleName")
public class MySecuredController { ...
OR
Am I completely wrong?
Whole script it is really just the MVC3 tutorial…
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.IO;
using System.Security.Permissions;
namespace mvc3test.Controllers
{
[Authorize(Roles="taxpayer")]
public class HomeController : Controller
{
public ActionResult Index()
{
ViewBag.Message = "Welcome to ASP.NET MVC!";
return View();
}
public ActionResult About()
{
return View();
}
[HttpPost]
public ActionResult Index(HttpPostedFileBase dr405)
{
var saveLocation = Path.Combine(Server.MapPath("\\"),"returns");
System.IO.Directory.CreateDirectory(saveLocation);
dr405.SaveAs(Path.Combine(saveLocation,User.Identity.Name) + ".xlsx");
ViewBag.Message = String.Format("File name: {0}, {1}Kb Uploaded Successfully.",dr405.FileName,(int)dr405.ContentLength / 1024);
return View();
}
}
}
when I run this the site logs me in after entering my credentials. I know this because my name appears in the upper right corner of the screen. But It just keeps taking my to the login screen over and over and over.
Update
So I added a watch to the Redirect Method in the LogOn Action for the value of User.IsInRole("taxpayer") where User.Identity.Name is the username in question. User.IsInRole("taxpayer") returned false. Below when I run the aspnet_db stored proc, it indicates the user in the list returned…..
USE [aspnetdb]
GO
DECLARE @return_value int
EXEC @return_value = [dbo].[aspnet_UsersInRoles_GetUsersInRoles]
@ApplicationName = N'/',
@RoleName = N'taxpayer'
SELECT 'Return Value' = @return_value
GO
So now I’m wondering if it is a data issue. Any thoughts???
If the user accessing the page is either not authenticated or not a member of the given role (your second option is the one I use) then they will be redirected to the authentication page. This is a filter, not a grant.