Gor*_*001 5 c# asp.net asp.net-mvc-5 asp.net-identity
在ASP MVC5 RC我没有让角色系统工作.我的数据库有所有需要的表存在一个角色,但校对用户是否在角色中总是返回false(没有SQL异常或其他东西)!
我需要在IPrincipal某个地方激活角色系统吗?
测试代码:
AccountController accCont = new AccountController();
// check role exist : result = true
var roleExist = await accCont.IdentityManager.Roles.RoleExistsAsync("61c84919-72e2-4114-9520-83a3e5f09de1");
// try find role by name : result = role object
var role = await accCont.IdentityManager.Roles.FindRoleByNameAsync("ProjectAdministrator");
// check with AccountController instance : result = true
var exist = await accCont.IdentityManager.Roles.IsUserInRoleAsync(User.Identity.GetUserId(), role.Id);
// check if current user is in role : result (both) = false????
var inRole = User.IsInRole(role.Id);
var inRole2 = User.IsInRole(role.Name);
Run Code Online (Sandbox Code Playgroud)
我还尝试构建一个自定义的IIdentity.GetUserId()扩展,如Microsoft.AspNet.Identity.OwinNamespace中的扩展方法.
namespace Microsoft.AspNet.Identity
{
public static class IdentityExtensions
{
public static string IsUserInRole(this IIdentity identity)
{
if (identity == null)
{
throw new ArgumentNullException("identity");
}
ClaimsIdentity identity2 = identity as ClaimsIdentity;
if (identity2 != null)
{
var result = identity2.FindFirstValue(IdentityConfig.Settings.GetAuthenticationOptions().RoleClaimType);
return null; // later result
}
return null;
}
}
}
Run Code Online (Sandbox Code Playgroud)
但索赔类型的结果RoleClaimType总是null:(我真的坚持这个.
谢谢您的帮助!斯特芬
User.IsInRole基本上是查看当前登录用户的声明。您的登录逻辑是什么样的?这就是负责生成 cookie 并转化为用户身份的东西。需要正确设置角色声明才能使该IsInRole方法正常工作。
| 归档时间: |
|
| 查看次数: |
13270 次 |
| 最近记录: |