[英]AuthorizeAttribute to handle valid authorized users
I have a implemented a custom AuthorizeAtrribute class 我实现了一个自定义AuthorizeAtrribute类
public class AdminAuthorizeAttribute : AuthorizeAttribute
{
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
base.HandleUnauthorizedRequest(filterContext);
}
}
Action method 动作方式
[AdminAuthorize(Roles = "Admin")]
public ViewResult AdminOnly()
{
return View();
}
[AdminAuthorize(Roles = "Admin, Mod")]
public ViewResult Index()
{
return View();
}
When I have a user that IsAuthenticated but not in the Admin role I would like to redirect them to the Index page and not the logon page. 当我有一个经过IsAuthenticated认证但不具有管理员角色的用户时,我想将他们重定向到“索引”页面而不是登录页面。
I've read the many other SO posts on this but my HandleUnauthorizedRequest() method is not firing. 我已经阅读了很多其他的文章, 但是我的HandleUnauthorizedRequest()方法没有触发。
You are overriding a method that is later in the process than you think. 您正在覆盖一个比您认为的要晚的方法。 You'll need to override one of these methods to implement your auth logic: 您需要重写以下方法之一来实现auth逻辑:
public override void OnAuthorization(AuthorizationContext filterContext)
{
base.OnAuthorization(filterContext);
//do custom work here
}
OR 要么
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
if (!base.AuthorizeCore(httpContext))
return false;
//do custom work here
}
this the code i always use when i work with active directory 这是我在使用活动目录时始终使用的代码
public string Groups { get; set; }
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
if (base.AuthorizeCore(httpContext))
{
if (String.IsNullOrEmpty(Groups)) { return true; }
var groups = Groups.Split(',').ToList();
var context = new PrincipalContext(ContextType.Domain,"yourDomain");
var userPrincipal = UserPrincipal.FindByIdentity(context,IdentityType.SamAccountName,httpContext.User.Identity.Name);
foreach(var group in groups){ // this will check user if the right role in active directory
if(userPrincipal.IsMemberOf(context, IdentityType.Name, group)){
return true;
}
}
}
return false;
}
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
if (filterContext.HttpContext.User.Identity.IsAuthenticated)
{
var result = new ViewResult();
result.ViewName = "NotAuthorized";
result.MasterName = "_Layout";
filterContext.Result = result;
}
else
{
base.HandleUnauthorizedRequest(filterContext);
}
}
forgot to tell the Groups variable represent the field inside my Attribute 忘记告诉Groups变量代表我的Attribute中的字段
[AuthorizeAD(Groups = ConstantsADGroups.AdminGp)]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.