在没有实体框架的Asp.NET身份中的RoleStore和角色管理

时间:2016-06-08 21:55:32

标签: entity-framework wcf asp.net-identity dapper user-roles

我正在编写WCF服务,我通过没有实体框架的ASP.NET身份验证可以访问我的WCF服务的用户。现在我在角色授权方面遇到了问题。我正在使用没有Entity Framework的自定义方式,因此为了实现身份验证,我创建了User类和UserStore类。我怎么能授权这个角色?

[注意:我在数据库表中有角色(ASPNetRoles和ASPNetUserRoles),只能访问WCF服务,我知道我必须使用principalpermission修饰方法。]

命名空间CalculatorService {

public class IdentityValidator : UserNamePasswordValidator
{
    public override void Validate(string UserName, string Password)
    {
        using (var userManager = new UserManager<User>(new UserStore("data=source=pcb-sql01;initial catalog=InsitePCB;integrated security=True;MultipleActiveResultSets=True")))
        {
            var user = userManager.Find(UserName, Password);
            if (user == null)
            {
                var msg = string.Format("Unknown Username {0} or incorrect password {1}", UserName, Password);
                Trace.TraceWarning(msg);
                throw new FaultException(msg);
                // //the client actually will receive MessageSecurityException. But if I throw MessageSecurityException, the runtime will give FaultException to client without clear message.
            }
        }

    }

}


public class RoleAuthorizationManager : ServiceAuthorizationManager
{
    protected override bool CheckAccessCore(OperationContext operationContext)
    {

        using (var userStore = new UserStore("data source=pcb-sql01;initial catalog=InsitePCB;integrated security=True;MultipleActiveResultSets=True"))
        {
            using (var userManager = new UserManager<User>(userStore))
            {
                var identity = operationContext.ServiceSecurityContext.PrimaryIdentity;
                var user = userManager.FindByName(identity.Name);
                if (user == null)
                {
                    var msg = string.Format("Unknown Username {0} .", user.UserName);
                    Trace.TraceWarning(msg);
                    throw new FaultException(msg);
                }

                //Assign roles to the Principal property for runtime to match with PrincipalPermissionAttributes decorated on the service operation.
                var roleNames = userManager.GetRoles(user.Id).ToArray();//users without any role assigned should then call operations not decorated by PrincipalPermissionAttributes
                operationContext.ServiceSecurityContext.AuthorizationContext.Properties["Principal"] = new GenericPrincipal(operationContext.ServiceSecurityContext.PrimaryIdentity, roleNames);

                return true;

            }
        }

    }

}

}

0 个答案:

没有答案