如何将ASP.NET权限绑定到WCF服务

时间:2011-01-27 18:02:16

标签: c# wcf asp.net-membership

我正在创建一个具有WCF服务后端的大型ASP.NET 4站点。我希望该网站使用该服务进行登录和授权。

基本上当用户访问登录页面时,我不想使用成员资格提供程序,而是希望将WCF服务用作身份验证机制。

WCF服务已使用身份验证和授权(带模拟),因此如果服务的客户端尝试执行他们没有权限的服务方法,则会收到错误。

问题是如何将其与ASP.NET站点联系起来?

以下是我正在使用的一些示例代码:

Web服务接口:

[ServiceContract]
public interface IService
{
    [OperationContract]
    bool Foo();

    [OperationContract]
    void Bar();
}

网络服务:

public class BackEndService : IService
{
    [PrincipalPermission(SecurityAction.Demand, Role="FooRole")]
    public bool Foo()
    {
        return false;
    }

    [PrincipalPermission(SecurityAction.Demand, Role="Bar")]
    public void Bar()
    {
        //...
    }
}

在客户端:

public class LoginPage : Page
{
    public void LoginButton_Clicked(object sender, EventArgs e)
    {
        string username = TxtUsername.Value;
        string password = TxtPassword.Value;

        BackEndService client = new BackEndService();
        client.CleintCredentials.Username = username;
        client.ClientCredentials.Password = password;

        client.Foo(); //if the credentials supplied do not have permissions there will be error
        client.Bar();
    }
}

我的目标是让一些UI元素的功能用PrincipalPermission属性标记,这样用户就不必前往服务就发现他们没有权限。

此外,我想根据用户的权限加载/卸载一些UI元素。

是否可能,或者我是否必须在我的服务中加入一些逻辑来返回用户可以看到的任何UI模块?是否有可能通过服务处理权限,就像它是成员资格提供程序一样,因为在UI元素的代码后面使用PrincipalPermissionAttribute就是这种情况?

谢谢,

<bleepzter/>

1 个答案:

答案 0 :(得分:1)

如果要使用ASP.NET成员资格,则需要编写自己的成员资格提供程序以对WCF服务进行身份验证。您可能需要向WCF服务添加操作以返回用户所属角色的列表。然后,您可以使用Membership类来确定用户是否是特定角色,并根据需要隐藏/显示UI元素。

有关创建成员资格提供程序的详细信息,请参阅http://msdn.microsoft.com/en-us/library/f1kyba5e.aspx