asp.net-mvc User.IsInRole 不起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15567338/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
User.IsInRole doesn't work
提问by Bartosz
I have ASP.NET MVC 4 application. I use Simple Membership Provider allowing to tick remember me checkbox under login form. If ticked, persitent cookie .ASPXAUTH is created which expires 100 days from login date. And everything works fine, apart of main menu of the application.
我有 ASP.NET MVC 4 应用程序。我使用 Simple Membership Provider 允许勾选登录表单下的记住我复选框。如果勾选,则创建永久 cookie .ASPXAUTH,从登录日期起 100 天到期。除了应用程序的主菜单外,一切正常。
Some parts of the menu are available for admin users only. I use:
菜单的某些部分仅供管理员用户使用。我用:
@if (User.IsInRole("Administrator")) { @Html.Partial("_MainMenuPartial") }
to lock them from being rendered for regular user. This approach works fine just after logging into the system. When I return after a while and persistent cookie is used to authenticate me, I do get logged in, but
锁定它们不被呈现给普通用户。这种方法在登录系统后就可以正常工作。当我一段时间后返回并使用持久性 cookie 对我进行身份验证时,我确实登录了,但是
@User.IsInRole("Administrator")
returns "False" so I can't see admin menu items. At the same time
返回“False”所以我看不到管理菜单项。同时
@User.Identity.Name
returns proper login name and
返回正确的登录名和
@User.Identity.IsAuthenticated
returns "True", what proves that persistent cookie works fine. Why can't I access user roles even though user is authenticated by the system then?
返回“True”,证明持久性 cookie 工作正常。为什么即使用户已通过系统身份验证,我也无法访问用户角色?
回答by Cem Mutlu
I had a smilar issue. In my case the problem solved when i log off and log in again.
我有一个类似的问题。在我的情况下,当我注销并再次登录时问题解决了。
回答by Pa?out
Problem using roles with MVC5
在 MVC5 中使用角色的问题
I found a solution. In my web.config:
我找到了解决方案。在我的 web.config 中:
<modules>
<remove name="FormsAuthenticationModule" />
<remove name="RoleManager" />
</modules>
I added remove name="RoleManager" line, and the new AspNet.Identity code took over allowing me to use User.IsInRole(..)
我添加了 remove name="RoleManager" 行,新的 AspNet.Identity 代码接管了允许我使用 User.IsInRole(..)
http://forums.asp.net/t/1952572.aspx?Problem+using+roles+with+MVC5
http://forums.asp.net/t/1952572.aspx?Problem+using+roles+with+MVC5
回答by xfan
Have you tried adding
你有没有试过添加
[InitializeSimpleMembership]
in the controller where you're doing the check?
在您进行检查的控制器中?
回答by MattSull
I had a similar problem with IsUserInRolereturning false. By placing a watch on it, I was able to overcome the problem by using the overload described below. Try it, put a break point where you're getting false, and see what happens.
我在IsUserInRole返回 false 时遇到了类似的问题。通过将手表放在上面,我能够通过使用下面描述的过载来克服这个问题。试试看,在你出错的地方设置一个断点,看看会发生什么。
@if (Roles.IsUserInRole(Model.UserName, "Administrator"))
I'm pretty sure you could also use User.Identity.Nameas the first parameter.
我很确定你也可以User.Identity.Name用作第一个参数。
回答by Marcos R
Old question, but there's some missing information here. I ran into the same issue, and there's one thing to keep in mind. If you test the user identity (like User.IsInRole("admin")) just after authenticate (without send the response to client), Identity framework has not populated this session info yet(or at least, I could not found the way to do that). This info you're requesting for, is populated at some point after your controller return. If you want (I.E.) to redirect to different views after login, depending on the user role, you'll have to use a custom authorization filter.
老问题,但这里缺少一些信息。我遇到了同样的问题,需要记住一件事。如果您在身份验证之后测试用户身份(如 User.IsInRole("admin"))(不向客户端发送响应),则身份框架尚未填充此会话信息(或者至少,我找不到方法去做)。您请求的此信息将在您的控制器返回后的某个时间填充。如果您希望 (IE) 在登录后重定向到不同的视图,根据用户角色,您必须使用自定义授权过滤器。
回答by Sergey
I had a similar issue, seems like authentication module is not wired up completely with the SimpleMembershipProvider. To get around that problem, you can use a Role class to access needed information. For example to check if the use in role you can use the following:
我有一个类似的问题,似乎身份验证模块没有与 SimpleMembershipProvider 完全连接。为了解决这个问题,您可以使用 Role 类来访问所需的信息。例如,要检查是否使用角色,您可以使用以下内容:
Roles.GetRolesForUser("sergey").Contains("Developer")
And so other useful methods when working wit SimpleMembershipProvider roles:
以及使用 SimpleMembershipProvider 角色时的其他有用方法:
Roles.RoleExists("Developer")
Roles.CreateRole("Developer");
Roles.AddUserToRole("sergey", "Developer");
回答by agressen
None of these answers worked for me, but I did find the answer here: https://thinkthencode.wordpress.com/2016/04/24/azure-ad-using-app-roles-for-authorization/
这些答案都不适合我,但我确实在这里找到了答案:https: //thinkthencode.wordpress.com/2016/04/24/azure-ad-using-app-roles-for-authorization/
The key was adding the following to Startup.Auth.cs:
关键是将以下内容添加到Startup.Auth.cs:
TokenValidationParameters = new TokenValidationParameters
{
RoleClaimType = "roles"
}
回答by Ashok B
If you are using latest Identity framework please see if you are using following
如果您使用的是最新的身份框架,请查看您是否使用以下
services.AddIdentity<IdentityUser,IdentityRole>()
.AddEntityFrameworkStores<WebUserContext>()
.AddDefaultTokenProviders();
If you are using AddDefaultIdentity Roles don't get populated.
如果您使用的是 AddDefaultIdentity 角色,则不会填充。
services.AddDefaultIdentity<IdentityUser>()
.AddEntityFrameworkStores<WebUserContext>()
.AddDefaultTokenProviders();
回答by VFein
If you're using IdentityManager by Brock Allen to create roles and assign them to users then you should read this article: https://github.com/IdentityManager/IdentityManager.AspNetIdentity/issues/3
如果您使用 Brock Allen 的 IdentityManager 创建角色并将其分配给用户,那么您应该阅读这篇文章:https: //github.com/IdentityManager/IdentityManager.AspNetIdentity/issues/3
You'll need to uncomment the following line:
您需要取消注释以下行:
this.RoleClaimType = System.Security.Claims.ClaimTypes.Role;
Now you'll realize that your user that used to be in roles is no longer in them, and you'll have to re add them. If you take a look at the AspNetUserClaims table, you'll see claimType of Role and 'http://schemas.microsoft.com/ws/2008/06/identity/claims/role' you want the later.
现在你会意识到你曾经在角色中的用户不再在他们中,你必须重新添加他们。如果您查看 AspNetUserClaims 表,您将看到 claimType of Role 和“ http://schemas.microsoft.com/ws/2008/06/identity/claims/role”,您需要后者。
Once you do this, User.IsInRole("rolename")behaves as expected.
执行此操作后,User.IsInRole("rolename")将按预期运行。
I hope this helps someone, took me a while to figure this out.
我希望这对某人有帮助,我花了一段时间才弄明白。
回答by ViniBH
The "EmailConfirmed" of this account probably still false, try to change it to true
这个账号的“EmailConfirmed”可能还是false,尝试改成true



