0

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

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

 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(); 
4

1 回答 1

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;
}
于 2013-09-12T09:36:50.160 回答