使用WCF RIA Service中的Authentication进行自定义验证

      不少文章有提到怎样使用WCF RIA Service中的验证功能,但一般都是以建立一个SilverLight Business Application项目作为开始,然而SilverLight Business Application的模板并不是那么符合实际需要,默认添加了一堆的类、方法,在这个基础上去调整,实在恶心,故实验了一下在普通的SilverLight项目中使用。现总结如下:

 

     1、建立一个普通的SilverLight项目,选中“Enable WCF RIA Service”,假设项目SL项目名为MyAuthentication,对应WEB项目为MyAuthentication.Web;

     2、在MyAuthentication.Web项目中添加一项:Authentication Domain Service,使用"Authentication Domain Service"项目文件模板将自动添加一个继承自AuthenticationBase<T>的类,一个继承自UserBase的User类,假设继承自AuthenticationBase<T>的类名为AuthenticationDomainService;

     3、编译解决方案,编译成功后将在SL项目中生成类:AuthenticationDomainContext、WebContext、User;

     接下来就可以做验证功能了。在AuthenticationDomainService类中重载ValidateUser方法可实现自定义验证,重载GetAuthenticatedUser方法可实现自定义加载当前登录用户信息。

     4、扩展User类,重载ValidateUser、GetAuthenticatedUser方法:

View Code
[EnableClientAccess]
public class AuthenticationDomainService : AuthenticationBase<User>
{
// To enable Forms/Windows Authentication for the Web Application, edit the appropriate section of web.config file.

protected override bool ValidateUser(string userName, string password)
{
return userName == "zhangsan" && password == "123456";
}

protected override User GetAuthenticatedUser(IPrincipal principal)
{
return new User() { Name = principal.Identity.Name, DisplayName = "张三" };
//return base.GetAuthenticatedUser(principal);
}
}

public class User : UserBase
{
// NOTE: Profile properties can be added here
// To enable profiles, edit the appropriate section of web.config file.

// public string MyProfileProperty { get; set; }

public User()
: base()
{

}

public string DisplayName { get; internal set; }
}

      编译后貌似就可以在SL项目中使用WebContext了,其实不然。还需要做以下准备工作:

      5、在SL的App类的构造函数中加上WebContext初始化代码:

View Code
WebContext webContext = new WebContext();
webContext.Authentication = new FormsAuthentication();
//webContext.Authentication = new WindowsAuthentication();
this.ApplicationLifetimeObjects.Add(webContext);

      6、在Web.Config中指定身份验证模式为Forms验证:

      <authentication mode="Forms">

      7、测试:

View Code
private void button1_Click(object sender, RoutedEventArgs e)
{
LoginOperation operation = WebContext.Current.Authentication.Login(GetLoginParameters(), LoginCompeted, null);
}

private LoginParameters GetLoginParameters()
{
return new LoginParameters("zhangsan", "123456");
}

private void LoginCompeted(LoginOperation operation)
{
if (operation.LoginSuccess)
{
MessageBox.Show("success");
MessageBox.Show(WebContext.Current.User.DisplayName);
}
else if (operation.HasError)
{
MessageBox.Show(operation.Error.Message);
operation.MarkErrorAsHandled();
}
else if (!operation.IsCanceled)
{
MessageBox.Show("用户名或密码错误!");
}
}


      参考资料:http://msdn.microsoft.com/zh-cn/library/ee707361%28v=vs.91%29.aspx

 

posted @ 2012-04-03 21:49  细雨黄昏  阅读(620)  评论(0编辑  收藏  举报