【发布时间】:2014-03-04 13:17:58
【问题描述】:
我创建了自己的授权属性实现:
public class CustomAuthorizeAttribute : AuthorizeAttribute
{
/// <summary>
/// Log4net logger
/// </summary>
private static readonly ILog logger = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
logger.Info("User name IsAuthenticated " + httpContext.User.Identity.IsAuthenticated);
logger.Info("User name " + httpContext.User.Identity.Name);
if (httpContext.User.Identity.IsAuthenticated)
{
if (!string.IsNullOrEmpty(httpContext.User.Identity.Name))
{
logger.Info("User name " + httpContext.User.Identity.Name);
string[] domainUser = httpContext.User.Identity.Name.Split('\\');
if (domainUser.Count() == 2)
{
if (domainUser[0].Equals("MyDomain", StringComparison.OrdinalIgnoreCase))
{
LdapService ldap = new LdapService();
return ldap.IsUserInAd(domainUser[1]);
}
}
}
}
return base.AuthorizeCore(httpContext);
}
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
base.HandleUnauthorizedRequest(filterContext);
filterContext.Result = new RedirectResult("~/Error/Unauthorized");
}
}
并为控制器设置此属性:
[CustomAuthorize]
public class AccountController : Controller
{
/// <summary>
/// Log4net logger
/// </summary>
private static readonly ILog logger = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
/// <summary>
/// Index method run on start of the Account view.
/// </summary>
/// <returns>Action Result.</returns>
[CustomAuthorize]
public ActionResult Index()
{
WindowsIdentity identity = System.Web.HttpContext.Current.Request.LogonUserIdentity;
logger.Info("User name IsAuthenticated " + identity.IsAuthenticated);
logger.Info("User name " + identity.Name);
if (identity != null)
{
LdapService ldap = new LdapService();
string[] domainUser = identity.Name.Split('\\');
if (domainUser[1].Equals(AccessHelper.ReceptionUserName))
{
return RedirectToAction("Index", "Guest");
}
else
if (ldap.IsUserInReception(domainUser[1]))
{
return RedirectToAction("Index", "Reception");
}
else
{
return RedirectToAction("Index", "Employee");
}
}
return RedirectToAction("Index", "Employee");
}
在网络配置中,我设置了 Windows 身份验证...:
<appSettings>
<add key="webpages:Version" value="2.0.0.0" />
<add key="webpages:Enabled" value="false" />
<add key="PreserveLoginUrl" value="true" />
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
<add key="autoFormsAuthentication" value="false" />
<add key="enableSimpleMembership" value="false" />
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" />
<globalization uiCulture="en-GB" culture="en-GB" />
<authentication mode="Windows" />
<identity impersonate="true" />
当我为服务器 iis 部署我的 Asp.net mvc 4 应用程序并运行时,我已记录我未通过身份验证且用户为空。为什么我的页面看不到我应该通过 Windows 凭据进行身份验证?
【问题讨论】:
-
为什么要将 ldapservice 与基于 Windows 的应用程序一起使用?
标签: c# asp.net-mvc-4 windows-authentication authorize-attribute