我的数据库中有User表,我保留了用户的角色(主管理员,管理员,开发人员)。我想授权一些控制器 所以只有主管理员可以访问。
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)
我正在搜索其他示例,但我没有找到作者使用Claim
的任何示例答案 0 :(得分:0)
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 docs https://msdn.microsoft.com/en-us/library/vstudio/ms164660%28v=vs.100%29.aspx