ASP.. NET IIS用户角色身份验证
本文关键字:角色 身份验证 用户 IIS NET ASP | 更新日期: 2023-09-27 17:54:11
我目前正在做一个ASP。NET MVC4网站。在这个网站中,我不希望用户是某个角色的一部分,被允许运行代码。我使用以下代码:
[Authorize(Roles = GROUP)]
public void Auth()
{
/* if user is in the domain and signed in
* and a member of the above group
* they will come here */
username = User.Identity.Name;
//Do somthing
}
这工作得很好,但是当用户不是域和/或组的一部分时,它会提示输入用户名和密码。是否有可能跳过提示,直接重定向该用户?
此网站是在IIS 8中设置的,身份验证设置为windows身份验证
我将创建一个自定义授权属性并实现HandleUnauthorizedRequest方法来解决这个问题。
public class CustomAutorizeAttribute : AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
// do authorization logic
// ...
return (/* isAuthorized */);
}
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
UrlHelper urlHelper = new UrlHelper(filterContext.RequestContext);
filterContext.Result = new RedirectResult(urlHelper.Action("Index", "Error"));
}
}
有关详细信息,请参阅如何:创建自定义授权属性
use
[Authorize(Roles = GROUP)]
[HandleError(ExceptionType = typeof(UnauthorizedAccessException), View = "ApplicationError")]
public void Auth()
{
/* if user is in the domain and signed in
* and a member of the above group
* they will come here */
username = User.Identity.Name;
//Do somthing
}
,其中可以为未授权访问的用户指定视图