asp.net – HttpContext.Current.User!= HttpContext.User?

全局asax中的HttpContext.Current.User与动作方法中的HttpContext.User不同吗?我为用户分配了一些角色,但他们似乎迷路了.

下面的代码显示了正在发生的事情.当用户登录时,两个Assert都会被点击,首先是全局的asax,然后是action方法.但是他们给出了不同的结果

首先这个:

protected void Application_AuthenticateRequest(object sender,EventArgs e)
{
    // ... omitted some code to check user is authenticated
    FormsIdentity identity = (FormsIdentity)HttpContext.Current.User.Identity;

    string[] roles = new string[] { "admin","user" };

    HttpContext.Current.User =
        new System.Security.Principal.GenericPrincipal(identity,roles);

    Assert(HttpContext.User.IsInRole("admin"));
}

然后在我的动作方法中:

public ActionResult Index()
{
    bool isAdmin = HttpContext.User.IsInRole("admin");

    Assert(isAdmin); // this fails,isAdmin is false

    // ...
}

我使用了以下资源

This SO answer

http://csharpdotnetfreak.blogspot.com/2009/02/formsauthentication-ticket-roles-aspnet.html

解决方法

你的问题标签上写着“aspnet-mvc(3和4)”,你可以选择使用以下内容让你的生活更轻松吗?如果您使用的是VS2012中的MVC 4 Internet应用程序模板中的 Simple Membership,那么您只需开箱即用):

> WebSecurity.CreateUserAndAccount(name,password) – 创建用户
> Roles.AddUserToRole(和AddUserToRoles) – 将用户添加到角色
> Roles.IsUserInRole – 测试用户是否在角色中
> [Authorize(Roles = "admin")] – [授权]可以在整个控制器或操作上强制执行角色

CreateUserAndAccount的优点是也可以轻松设置UserProfile的属性,例如:

WebSecurity.CreateUserAndAccount(newUser.UserName,newUser.Password,new { FullName = newUser.FullName,Email = newUser.Email,Timezone = newUser.TZ });
Roles.AddUserToRoles(newUser.UserName,new[] {"admin","user"});

编辑,我意识到上面没有回答你关于.User属性等价的原始问题.

Controller中的HttpContext是一个属性:Controller.HttpContext.global.asax.cs中的HttpContext是静态类,这就是你使用HttpContext.Current的原因.他们指的是同一件事.

如果您运行以下代码,您可以看到它们显然是“相同的主体”.那么问题是你分配的角色发生了什么?

protected void Application_AuthenticateRequest(object sender,EventArgs e) {
    ...
    FormsIdentity identity = (FormsIdentity)HttpContext.Current.User.Identity;
    string[] roles = new string[] { "admin","user" };
    identity.Label = "test label";
    System.Security.Principal.GenericPrincipal ppl = new System.Security.Principal.GenericPrincipal(identity,roles);            
    HttpContext.Current.User = ppl;
... }

public ActionResult Index() {
    bool isAdmin = HttpContext.User.IsInRole("admin");
    bool isAdmin2 = System.Web.HttpContext.Current.User.IsInRole("admin");
    System.Web.Security.FormsIdentity identity = (System.Web.Security.FormsIdentity)HttpContext.User.Identity;

    // The label is carried through from Application_AuthenticateRequest to Index.
    string label = identity.Label;
}

问题是,您为.User分配了GenericPrincipal.根据RoleProvider,可以在PostAuthenticateRequest期间覆盖(例如,通过RoleManagerModule),并且(例如)将其转换为RolePrincipal.然后,这可以推迟回到数据库(再次取决于提供者)以获取角色,从而覆盖您的角色.如果您在Application_OnPostAuthenticateRequest中完成工作,那么您可能没问题.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


判断URL文件是不是在于在。private static bool UrlIsExist(string url){ System.Uri u = null; try { u = new Uri(url); } catch { return false; } bool isExist = false;
由于在.net中,Request时出现有HTML或Javascript等字符串时,系统会认为是危险性值。立马报错。解决方案一:在.aspx文件头中加入这句:解决方案二:修改web.config文件:因为validateRequest默认值为true。只要设为false即可。
public static bool ProcessIdCard(this string idCard, out DateTime birthday, out string genderName) { bool result; birthda...
如果你在GridView控件上设置 AllowPaging="true" or AllowSorting="true" 而没有使用使用数据源控件 DataSource (i.e. SqlDataSource, ObjectDataSource),运行则会出现下
protected void Page_Load(object sender, EventArgs e){ ScriptManager sm = Page.Master.FindControl("ScriptManager1") as ScriptManager; if (sm
1. install all features in IIS2. Try the following steps to register it.run %windir%\Microsoft.NET\Framework\v4.0.21006\aspnet_regiis.exe -i或运行,跳出如下错误
一般来说一个 HTML 文档有很多标签,比如“”、“”、“”等,想把文档中的 img 标签提取出来并不是一件容易的事。由于 img 标签样式变化多端,使提取的时候用程序寻找并不容易。于是想要寻找它们就必须写一个非常健全的正则表达式,不然有可能会找得不全,或者找出来的不是正确的 img 标签。我们可以
asp.net updatepanel 局部刷新,导致JS不能加载,而无法使用,而且 updatepanel会刷两次,郁闷的。解决方法如下:
FileHandlerhttp://www.cnblogs.com/vipsoft/p/3627709.htmlUpdatePanel无法导出下载文件:http://www.cnblogs.com/vipsoft/p/3298299.html//相对路径下载。path: ~/DownLoad///p
本地能上传文件,部署到服务器上就报Cannot access a closed file 错误,以下是解决方法: 最重要是requestLengthDiskThreshold此属性设置输入流缓冲阈值。
http://tool.oschina.net/commons字符十进制转义字符"""&&&>>不断开空格(non-breaking space) HTML特殊转义字符
1、2两步为推荐做法1. 将MySql.Data.dll放到 bin目录下面,或都安装mysql-connector-net-6.0.0.msi2.web.config 添加如下节点,注册版本号一致 3.全局配置在C:\WINDOWS\Microsoft.NET\Framework\v2.0.507
C# 跳转新页面string url = "http://www.vipsoft.com.cn";ResponseRedirect.Redirect(Response, url, "_blank", "'toolbar=0,scrollbar
.NET Core 在其上下文中,该请求的地址无效。 看了端口,发现没被占用,后来发现是IP地址变了 改成正确的IP就可以了。
datatable是一个jquery扩展的表格插件。其提供了强大的表格功能。官方地址:http://www.datatables.net/在官方示例中,对于表格的是否可排序是在初始化中设置的一个值来决定的$(".datatable-simplified").dataTable(
Html table 细边框 导航页档 军事 历史 ...
C# 跳转新页面判断URL文件是不是在于在。C# 指定物理目录下载文件,Response.End导致“正在中止线程”异常的问题public class FileHandler { public static bool DownLoadFile(string path, string fileName
由于将IE11升级到了 11 之前的网站无法正常使用,如果是开发人员碰到之问题,使用了微软的asp.net 控件,那么将服务器的.net framework 升级到 4.5http://www.microsoft.com/en-us/download/details.aspx?id=30653如果浏
引言 本文从Linux小白的视角, 在CentOS 7.x服务器上搭建一个Nginx-Powered AspNet Core Web准生产应用。 在开始之前,我们还是重温一下部署原理,正如你所常见的.Net Core 部署图: 在Linux上部署.Net Core App最好的方式是在Linux机器