Lef*_*tyX 15 asp.net asp.net-mvc windows-authentication
我试图在我的ASP.NET MVC2应用程序中实现Windows身份验证.我遵循了官方文档建议的所有步骤:
<authentication mode="Windows" />
<authorization>
<deny users="?" />
</authorization>
Run Code Online (Sandbox Code Playgroud)
我已经指定了NTLM身份验证.到现在为止还挺好.一切正常.我想检查登录我的数据库的用户.我想从我的表中获取角色,然后使用自定义属性管理授权.
我不想使用会员和角色提供者.
我已经有我的表用户/角色,因为他们已经被用于互联网应用程序(这是内联网应用程序).
在我的Internet App中,我有一个用户输入数据的表单.表单将发布到控制器,该控制器将检查所有内容并使用登录用户的用户(和角色)创建cookie.
在我的global.asax中,我捕获了AuthenticateRequest事件,在那里我读取了cookie并创建了一个自定义主体,我在整个应用程序中使用它来检查授权.
如何使用Windows身份验证实现此功能?
Xha*_*ent 23
只需创建一个新的主体并将其分配给Global.asax中的用户和线程(或使用动作过滤器).
protected void Application_AuthenticateRequest(object sender, EventArgs args)
{
if(HttpContext.Current != null)
{
String [] roles = GetRolesFromSomeDataTable(HttpContext.Current.User.Identity.Name);
GenericPrincipal principal = new GenericPrincipal(HttpContext.Current.User.Identity, roles);
Thread.CurrentPrincipal = HttpContext.Current.User = principal;
}
}
Run Code Online (Sandbox Code Playgroud)
如果用户没有匹配的任何角色,则可以使用web.config authoirzation元素禁止他们访问该应用:
<authorization>
<allow roles="blah,whatever"/>
<deny users="*"/>
</authorization>
Run Code Online (Sandbox Code Playgroud)
小智 6
只是为了补充上面的答案,希望这能节省一些时间.
我有VS 2015的Intranet MVC 5站点.
在使用HttpContext.Current.User更新顶行之前,代码对我不起作用.如果用户尚未在数据库中创建,则该站点为我提供了对HttpContext.Current.User的空引用.通过将.User添加到第一行,它在第一次加载时绕过该代码并运行.
if (HttpContext.Current.User != null)
{
String[] roles = GetRolesFromSomeDataTable(HttpContext.Current.User.Identity.Name);
GenericPrincipal principal = new GenericPrincipal(HttpContext.Current.User.Identity, roles);
Thread.CurrentPrincipal = HttpContext.Current.User = principal;
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
21269 次 |
最近记录: |