代码改变世界

[Silverlight]Wcf Ria Services权限控制的实现

2011-11-14 17:28  slmk  阅读(754)  评论(2编辑  收藏  举报

WCF RIA Services使用Domain Service域服务为客户端提供数据访问等服务,如何控制这些数据服务的安全访问呢?例如有些服务只有权限高的用户可以访问,有些服务是可以匿名访问的,这又是如何实现的呢?

其实实现原理有些类似于Asp.net MVC的Action Filter,都使用Attribute标记来区分安全等级。看一个简单的Domain Service:

    [EnableClientAccess]
    public class MyService:DomainService
    {
 
   [RequiresAuthentication]
        public DataModel GetDataModel()
        {
            return new DataModel() { ID = 1, Name = "test" };
        }
    }

 如此标记后GetDataModel只有登录用户才能访问,实现了一定程度的数据访问控制。如何实现基于角色的控制呢?你可能猜到了:继承AuthorizationAttribute。

 public class AdminRequired : AuthorizationAttribute
{
protected override AuthorizationResult IsAuthorized(System.Security.Principal.IPrincipal principal, AuthorizationContext authorizationContext)
{
if (principal.IsInRole("admins"))
{
return AuthorizationResult.Allowed;
}
return new AuthorizationResult("只有管理员才能访问");
}
}

然后再需要管理员权限的地方加上:

   [AdminRequired]
        public DataModel GetDataModel()
        {
            return new DataModel() { ID = 1, Name = "test" };
        }

WCF RIA Services的权限控制就是这么简单!

 

提供Silverlight打印全套解决方案--支持打印预览、页面设置(横向纵向,页边距,纸张大小、字体大小)、自动分页和多页连续打印