Windows身份验证& SQL成员服务

时间:2009-05-20 14:40:48

标签: asp.net-mvc authentication windows-authentication sqlmembershipprovider

我有一个ASP.Net MVC内部网站点,它使用Windows身份验证来了解谁登录(不允许匿名浏览)。用户第一次访问时,我会从他们那里收集一些非常基本的信息,用于他们的Contact对象(例如姓名,电子邮件,国家/地区),然后存储在apps数据库中。

我想基于网站角色,因此我需要能够为每个用户分配一个角色(用户,管理员等)。我可以使用ADS组来做到这一点,但这似乎相当重量级。我可以使用ASP.Net提供的SQL Membership服务来存储他们的用户名,然后存储他们所属的角色,还是会被迫收集密码等(打败使用Windows身份验证的点)?这也与ASP.Net MVC [授权]属性集成?

2 个答案:

答案 0 :(得分:7)

在“普通”ASP.NET中肯定可以使用这种组合(Windows身份验证和角色的SQL),因此它也应该适用于MVC。

这是a link that might help

答案 1 :(得分:2)

是的,你可以这样做。

Authorize使用IPrincipal的IsInRole方法来确定用户是否在给定角色内。

您可以在Global.asax中的AuthenticateRequest事件期间使用您的实现方式切换IPrincipal的默认实现。

以下是一些可能实际工作和编译的示例代码,并且不会将您的网站暴露给黑客的攻击:

private void Application_AuthenticateRequest(object sender, EventArgs e)
{
    if (!Request.IsAuthenticated)
    {
        Context.User = new MyPrincipal { Identity = new MyIdentity 
                { Type = UserType.Inactive, Id = int.MinValue }};
        Thread.CurrentPrincipal = Context.User;
    }
    else
    {
        HttpCookie authCookie = Request.Cookies[
            FormsAuthentication.FormsCookieName];
        if (authCookie != null)
        {
            FormsAuthenticationTicket authTicket =
                   FormsAuthentication.Decrypt(authCookie.Value);

            var identity = Db.GetIdentity(
              authTicket.Name, new HttpRequestWrapper(Request));
        Context.User = new MyPrincipal { Identity = new MyIdentity 
                { Type = UserType.Inactive, Id = int.MinValue }};
        Thread.CurrentPrincipal = Context.User;
        }
    }
}