0

我一直在学习 MVC,并且正在研究无会话身份验证(以减少服务器压力/可扩展性,并且因为 AppFabric 缓存在 Azure 网站上托管会话的成本很高)。

我的用户信息存储在 SQL 中,每个用户都有一个部门、等级、角色和权限(角色/部门也有权限)。我在想我真正需要存储的只是他们在安全 cookie 中的 userId,如果它没有过期,请在 global.asax 中的每个请求中获取他们的其余信息。我会使用诸如http://eversystems.eu/Document/15/Sessionless_Authentication_with_Encrypted_Tokens之类的方法来保护它

我最终想要的是在我的 ViewModel 中使用自定义字段注释它们的能力

[Authorize(Roles="Admin")] [Authorize(Dept="IT")] [Authorize(Rank="Manager")]

或者在 Html 中说

@if(User.IsInDept("IT")

或者

@if(User.HasRank("Manager"))

我查看了扩展FormsAthenticationTicketMembership Provider / RolesIPricipalIIdentity很难理解我将如何修改它们以实现我所追求的。我见过的例子有很多我不想要的额外膨胀,但我发现的最好的例子是@Ahmad Abu Raddad 在这里ASP.NET MVC - Set custom IIdentity or IPrincipal

如果有人能指出我是否朝着正确的方向前进或可能提出替代方案,我将不胜感激。

4

1 回答 1

0

只是想分享我是如何最终解决这个问题的。我最终只是简单地创建了一个自定义 IPrincipal 并公开了我的内部数据库类。

 interface ICustomPrincipal : IPrincipal
{
    //I pass the whole model across so if we update/modify in the future it will automatically populate the new items for the cookie
    user d { get; set; }
   //some other variables
}

我在用户类中设置了大量方法,如 IsInRole()、isInDept()、HasRank()、HasPermission 等,它们在查询数据库后返回一个布尔值,这给了我所需的视图/控制器中的逻辑。

我创建了一个 BaseController 可以检索这个新的 CustomPrincipal

public class BaseController : Controller
{
    protected virtual new CustomPrincipal User
    {
        get { return HttpContext.User as CustomPrincipal; }
    }
}

我还需要更新我的 WebViewPage,以便我可以在视图中检索我的新 CustomPrincipal。

public abstract class BaseViewPage : WebViewPage
{
    public virtual new CustomPrincipal User
    {
        get { return base.User as CustomPrincipal; }
    }

}

并修改我的意见 web.config

<system.web.webPages.razor>
<host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<pages pageBaseType="MyNameSpace.BaseViewPage">
  <namespaces>
    <add namespace="System.Web.Mvc" /> .....

如果有人觉得这很有用但需要更多信息,请私信我

于 2013-04-28T18:28:49.000 回答