Silverlight WCF RIA服务(三十四)身份验证、角色、个性化 5

如何:创建自定义验证属性 WCF RIA Services框架提供了RequiresAuthenticationAttribute和RequiresRoleAttribute属性。这两个属性使我们很方便地指定哪个域操作是仅仅对验证用户或特定角色成员可用的。除了这两个属性,我们可以创建自制验证逻辑属性并对域操作应用这个
  

如何:创建自定义验证属性

WCF RIA Services框架提供了RequiresAuthenticationAttribute和RequiresRoleAttribute属性。这两个属性使我们很方便地指定哪个域操作是仅仅对验证用户或特定角色成员可用的。除了这两个属性,我们可以创建自制验证逻辑属性并对域操作应用这个属性。
这章我们演示如何为身份验证添加自制属性。我们通过创建一个派生于AuthorizationAttribute的类并重载Authorize方法用来提供我们自定义的逻辑,来创建一个自制验证属性。

1. 在服务端项目中,创建派生于AuthorizationAttribute的类。
2. 重载Authorize方法,并添加判断是否授权的逻辑。下面的例子演示一个名为CheckAttendeeName的定制属性,来检测用户的角色和用户名字的第一个字母。
 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class CheckAttendeeNameAttribute : System.Web.DomainServices.AuthorizationAttribute
{
    public override bool Authorize(System.Security.Principal.IPrincipal principal)
    {
        if (principal.IsInRole("Attendee") && principal.Identity.Name.StartsWith("A"))
        {
            return true;
        }
        else
        {
            return false;
        }
    }
}


3. 要执行自定义的验证逻辑,对域操作应用这个自定义的验证属性。
 

1
2
3
4
5
6
7
[CheckAttendeeName()]
public IQueryable<COURSE> GetCourses()
{
    return this.ObjectContext.Courses;
}
Powered By D&J (URL:http://www.cnblogs.com/Areas/)
原文地址:https://www.cnblogs.com/Areas/p/2172199.html