65.9K
CodeProject 正在变化。 阅读更多。
Home

如何为我的 WCF 服务操作实现自定义基于角色的授权

2014 年 2 月 14 日

CPOL
viewsIcon

14229

如何为我的 WCF 服务操作实现自定义基于角色的授权

您可以使用自定义属性来实现它。 如下所示创建一个新的自定义属性

CustomMembershipAuthorization.cs

    public class CustomMembershipAuthorization : Attribute, IOperationBehavior, IParameterInspector
    {
        public string AllowedRole { get; set; }

        public CustomMembershipAuthorization()
        {
        }

        public CustomMembershipAuthorization(string allowedRole) 
        {
            AllowedRole = allowedRole;
        }

        public void ApplyDispatchBehavior
        (OperationDescription operationDescription, DispatchOperation dispatchOperation)
        {
            dispatchOperation.ParameterInspectors.Add(this);
        }

        public void AfterCall(string operationName, object[] outputs,
                              object returnValue, object correlationState)
        {
        }

        public object BeforeCall(string operationName, object[] inputs)
        {
            if (!Thread.CurrentPrincipal.IsInRole(AllowedRole))
            {
                if (WebOperationContext.Current != null)
                    WebOperationContext.Current.OutgoingResponse.StatusCode = 
                                                          HttpStatusCode.Unauthorized;

                throw new WebFaultException<string>("Unauthorized", HttpStatusCode.Unauthorized);
            }

            return null;            
        }

        public void AddBindingParameters(OperationDescription operationDescription, 
        System.ServiceModel.Channels.BindingParameterCollection bindingParameters)
        {
        }

        public void ApplyClientBehavior
        (OperationDescription operationDescription, ClientOperation clientOperation)
        {
        }

        public void Validate(OperationDescription operationDescription)
        {
        }

    }

如以下所示,将上述定义的自定义属性与您的操作契约一起使用

    [ServiceContract]
    public interface IMyService
    {
        [OperationContract]
        [CustomMembershipAuthorization("client")]
        bool Log(MyLog req);

        [OperationContract]
        [CustomMembershipAuthorization("admin")]
        MyLog GetLog(string logId);
     }
}

CustomMembershipAuthorization 类的 BeforeCall() 方法中,您可以根据您的需求修改代码。 在这里,您可以验证用户是否属于允许访问该操作的角色。

请参阅 如何实现简单的自定义成员资格提供程序,了解如何使用自定义用户名和密码对用户进行身份验证的详细信息。

© . All rights reserved.