Я создал пользовательскую аутентификацию и авторизацию для своих пользователей. Проблема, с которой я столкнулась, заключается в том, как заставить mvc проверять, что роль из таблицы моих пользователей соответствует [Авторизовать (Роль)] на моем контроллере, чтобы настроить httpauthorised на true.Below - мой класс customauthorise.Пользовательская авторизация пользователя, основанная на ролях в asp.net mvc
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true, AllowMultiple = true)]
public class CustomAuthorizeAttribute : AuthorizeAttribute
{
public override void OnAuthorization(AuthorizationContext filterContext)
{
base.OnAuthorization(filterContext);
if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
{
filterContext.Controller.TempData["ErrorDetails"] = "You must be logged in to access this page";
filterContext.Result = new RedirectResult("~/User/Login");
return;
}
if (filterContext.HttpContext.Request.IsAuthenticated)
{
using (var db = new GManagerDBEntities())
{
var authorizedRoles = (from u in db.Users
where u.Username == filterContext.HttpContext.User.Identity.Name
select u.Role).FirstOrDefault();
Roles = String.IsNullOrEmpty(Roles) ? authorizedRoles.ToString() : Roles;
}
}
if (filterContext.Result is HttpUnauthorizedResult)
{
filterContext.Controller.TempData["ErrorDetails"] = "You do nat have necessary rights to access this page";
filterContext.Result = new RedirectResult("~/User/Login");
return;
}
}
public CustomAuthorizeAttribute(params object[] roles)
{
if (roles.Any(r => r.GetType().BaseType != typeof(Enum)))
throw new ArgumentException("roles");
this.Roles = string.Join(",", roles.Select(r => Enum.GetName(r.GetType(), r)));
}
}
ниже мой контроллер с украшением
[CustomAuthorize(Role.Administrator)]
[HttpGet]
public ActionResult CreateEmployees()
{
return View();
}
и мое перечисление для роли
public enum Role
{
Administrator = 1,
UserWithPrivileges = 2,
User = 3,
}
и модель
public class UserModel
{
public int UserID { get; set; }
[Required]
[Display(Name="Username:")]
public string Username { get; set; }
[Required]
public string Password { get; set; }
public int Role { get; set; }
}
см Pastie для ясного зрения pastie
ссылки Я просмотрены в попытке решить эту проблему среди других, но я не могу показаться, чтобы собрать вместе MVC 3 Authorize custom roles http://forums.asp.net/p/1573254/3948388.aspx
Customized authorization attribute in MVC 4 with Roles
посмотрите по адресу: //www.codeproject.com/Articles/578374/AplusBeginner-splusTutorialplusonplusCustomplusF –
Я надеюсь использовать одну единственную таблицу и роль как целое, но если все не удастся, просто создаст таблицу ролей и выполнит ваше предложение @VikasRana – GotaloveCode
Я попытался изменить его в соответствии с вашей ссылкой на этот http : //pastie.org/9510205 до сих пор не повезло – GotaloveCode