1- AuthorizeUserAttribute.cs是服装授权属性的类
public class AuthorizeUserAttribute : AuthorizeAttribute
{
public string AccessLevel { get; set; }
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
var isAuthorized = base.AuthorizeCore(httpContext);
if (!isAuthorized)
return false;
if (this.AccessLevel.Contains("Admin"))
{
return true;
}
else return false;
}
2-这是我的控制者
[AuthorizeUser(AccessLevel = "Admin")]
public class ProductsController : Controller
{
private DataBaseContext db = new DataBaseContext();
public ActionResult Index()
{
var product = db.Product.Include(p => p.ProductGroup);
return View(product.ToList());
}
}
[AuthorizeUser(AccessLevel = "Admin")]
public ActionResult Create([Bind(Include = "Product_Id,ProductName,Description,PicUrl,Group_Id")] Product product)
{
if (ModelState.IsValid)
{
db.Product.Add(product);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.Group_Id = new SelectList(db.ProductGroups, "Group_Id", "GreoupName", product.Group_Id);
return View(product);
}
start_up文件夹中的3-FilterConfig.cs
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
filters.Add(new AuthorizeAttribute());
filters.Add(new AuthorizeUserAttribute());
}
}
4的Global.asax.cs
void Application_Start(object sender, EventArgs e)
{
// Code that runs on application startup
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register);
RouteConfig.RegisterRoutes(RouteTable.Routes);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimTypes.NameIdentifier;
}
5- Admin1Controller.cs用于登录等...
[HttpPost]
public ActionResult Login(LoginViewModel model)
{
if (!ModelState.IsValid) //Checks if input fields have the correct format
{
return View(model); //Returns the view with the input values so that the user doesn't have to retype again
}
if(model.Email == "info@psmgroups.com" & model.Password == "@1234psm")
{
var identity = new ClaimsIdentity(new[] {
new Claim(ClaimTypes.Name,"Admin" ),
new Claim(ClaimTypes.Email, "info@psmgroups.com"),
new Claim(ClaimTypes.Role,"Admin")
}, "ApplicationCookie");
var ctx = Request.GetOwinContext();
var authManager = ctx.Authentication;
authManager.SignIn(identity);
return Redirect(GetRedirectUrl(model.ReturnUrl));
}
ModelState.AddModelError("", "incorrect UserName or pass");
return View(model);
}
创建新产品并返回产品/显示HTTP错误403.14 - 禁止页面。写产品/索引显示正确页面
答案 0 :(得分:0)
首先,这里没有代码实际上在自定义属性上设置AccessLevel
属性。也许你只是没有发布它,但如果这是你的所有代码,那么为什么这不起作用是相当明显的:AccessLevel
总是为空,因此永远不会包含字符串“Admin”。
那就是说,你甚至不需要这里的自定义属性。 AuthorizeAttribute
已经处理了角色。您似乎正在尝试实现某种类似并行角色的功能,但这是浪费时间。只是做:
[Authorize(Roles = "Admin")]
并称之为一天。