MVC Intranet应用程序的自定义角色

时间:2013-09-12 07:49:57

标签: asp.net-mvc asp.net-mvc-4

我正在创建一个MVC Intranet应用程序,我使用基于自定义角色的通用主体对象进行身份验证。

我的问题是如何在请求之间保留Generic主体对象。我使用以下代码。但我需要为每个用户请求执行以下代码,因为没有机制可以跨请求保留用户角色。请注意,我不喜欢在我的MVC项目中使用会话。

 private  GenericPrincipal GetGenericPrincipal()
        {
            // Use values from the current WindowsIdentity to construct 
            // a set of GenericPrincipal roles.
            WindowsIdentity windowsIdentity = WindowsIdentity.GetCurrent();

            // Construct a GenericIdentity object based on the current Windows 
            // identity name and authentication type. 
            string authenticationType = windowsIdentity.AuthenticationType;
            string userName = windowsIdentity.Name;
            GenericIdentity genericIdentity =
                new GenericIdentity(userName, authenticationType);

            // Construct a GenericPrincipal object based on the generic identity 
            // and custom roles for the user.
            GenericPrincipal genericPrincipal =
                new GenericPrincipal(genericIdentity, GetUserRoles(userName));

            return genericPrincipal;
        }


    }



 HttpContext.Current.User = Thread.CurrentPrincipal = GetGenericPrincipal(); 

1 个答案:

答案 0 :(得分:1)

在我现有的一个项目中,我使用Application_AuthenticateRequestion()中的Global.asax.cs方法获取每个请求的主体。主要的阻碍点是从数据库中检索User,但是这个问题可以通过在后台对内存中的User对象进行数据缓存来克服。

protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
    var authCookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];

    if (authCookie != null)
    {
        var ticket = FormsAuthentication.Decrypt(authCookie.Value);

        FormsIdentity formsIdentity = new FormsIdentity(ticket);

        ClaimsIdentity claimsIdentity = new ClaimsIdentity(formsIdentity);

        EmailAddress emailAddress = new EmailAddress(ticket.Name);

        var user = this.UserService.GetUserByEmailAddress(emailAddress);

        if (user != null)
        {
            foreach (var role in user.Roles)
            {
                claimsIdentity.AddClaim(
                    new Claim(ClaimTypes.Role, role));
            }
        }

        ClaimsPrincipal claimsPrincipal = new ClaimsPrincipal(claimsIdentity);

        HttpContext.Current.User = claimsPrincipal;
    }
}

修改

注意:我引用了传递到服务类的全局缓存。这就是缓存正在使用的内容。它使用基本缓存技术尝试从缓存中获取缓存项(如果它不存在(即它为空),然后从数据库中获取它并将其存储在缓存中以供下次使用。

来自UserService.cs

public User GetUserByEmailAddress(EmailAddress emailAddress)
{
    if (emailAddress == null)
    {
        throw new ArgumentNullException("emailAddress");
    }

    User user = this.dataCache.Get(emailAddress.Address) as User;

    if (user == null)
    {
        user = this.userRepository.GetUserByUsername(emailAddress);

        if (user != null)
        {
            this.dataCache.Set(emailAddress.Address, user);
        }
    }

    return user;
}