我的数据库中有用户表,其中我保留用户的角色(主管,管理员,开发人员)。我想授权一些控制器因此,只有主管理员才能访问。
namespace TicketSystem.Controllers
{
public class UserCredentials : ClaimsPrincipal, IIdentity, IPrincipal
{
public IIdentity Identity { get; private set; }
public int UserId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string[] roles { get; set; }
public string email { get; set; }
override
public bool IsInRole(string role)
{
if (roles.Any(r => role.Contains(r)))
{
return true;
}
else
{
return false;
}
}
public UserCredentials() { }
public UserCredentials(ClaimsPrincipal principal)
: base(principal)
{
}
public UserCredentials(int userId, string email, string firstName, string lastName, string[] roles)
{
this.Identity = new GenericIdentity(email);
this.UserId = userId;
this.email = email;
this.FirstName = firstName;
this.LastName = lastName;
this.roles = roles;
}
override
public string ToString()
{
return UserId + "";
}
}
}
这是我的登录方法
UserCredentials loggedUser = null;
User loginUser = db.tblUser.Where(x => x.email == model.UserName).FirstOrDefault();
loggedUser = new UserCredentials( loginUser.idUser,
loginUser.email, loginUser.firsName, loginUser.lastName, new string[] { loginUser.role });
if (loggedUser != null)
{
var identity = new ClaimsIdentity(new[] {
new Claim(ClaimTypes.Name, loggedUser.email),
new Claim("http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider", User.Identity.AuthenticationType),
new Claim(ClaimTypes.NameIdentifier, loggedUser.FirstName),
new Claim(ClaimTypes.Role, loggedUser.roles[0])
}, "ApplicationCookie");
var ctx = Request.GetOwinContext();
var authManager = ctx.Authentication;
authManager.SignIn(identity);
我尝试这个
public class CustomRoleProvider : RoleProvider
{
public override bool IsUserInRole(string username, string roleName)
{
using (var usersContext = new TicketSystemEntities())
{
var user = usersContext.tblUser.SingleOrDefault(u => u.email == username);
if (user == null)
return false;
return user.role != null && user.role==roleName;
}
}
}
,但我不知道如何配置web.config。我也有错误,例如
ticketsystem.models.customroleprovider'不实现继承的抽象成员'system.web.security.roleprovider.getusersinrole(string)
我正在搜索其他示例,但是我没有找到作者使用索赔
RoleProvider
是一个抽象类,您必须实现所有抽象方法来编译CustomRoleProvider
。
在Web.config
中,您需要添加roleManager
节并添加您的自定义提供商。这样的东西:
<roleManager enabled="true" defaultProvider="CustomRoleProvider">
<providers>
<clear/>
<add name="CustomRoleProvider"
type="TicketSystem.Models.CustomRoleProvider,
TicketSystem, Version=1.0.0.0, Culture=neutral"
connectionStringName="TicketSystemEntities"
enablePasswordRetrieval="false" enablePasswordReset="true"/>
</providers>
</roleManager>
参考查看Roleprovider docs https://msdn.microsoft.com/en-us/library/system.web.security.roleprovider(v = vs.140).aspx和rolemanager and rolemanager https://msdn.microsoft。