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

BizTalk 的向导发布的 WCF 服务的自定义服务授权管理器

2013年10月16日

CPOL

1分钟阅读

viewsIcon

19073

这篇博客简单地介绍了一种在 WCF 服务中实现基于角色的授权的解决方案,该 WCF 服务通过 BizTalk 的 WCF 服务发布向导暴露。

这篇博客简单地介绍了一种在 WCF 服务中实现基于角色的授权的解决方案,该 WCF 服务通过 BizTalk 的 WCF 服务发布向导暴露。在正常的 WCF 服务实现中,可以通过将安全属性放在 Web 方法上简单地完成授权,如下所示:

[PrincipalPermission(SecurityAction.Demand, Role = "Administrator")]
public string GetSecuredData(int id)
{
return string.Format(“here is a secured data of {0}”, id);
}

但是,当涉及到使用 WCF 发布向导暴露的 WCF 服务的授权实现时,您无法在 Web 方法中放置任何此类属性。我在 Mohamed M Malek 的文章 使用 SQL 提供程序实现 WCF 服务的动态授权 中找到了一种解决方案,但在对自定义服务授权管理器进行了一些研究和开发后,我发现该解决方案可以简化一些。我的自定义服务授权管理器版本如下:

using System.ServiceModel;
using System.Web.Security;
using System.Security.Principal;
using System.IdentityModel.Tokens;
public class SqlAuthorizationManager : ServiceAuthorizationManager 
{
protected override bool CheckAccessCore(OperationContext operationContext) 
{
  bool baseResult = base.CheckAccessCore(operationContext);
   if (operationContext.ServiceSecurityContext.IsAnonymous)
   { return true; }
   //Extract the identity token of the current context user making the call to this service 
   IIdentity Identity = operationContext.ServiceSecurityContext.PrimaryIdentity;
    //Prior to proceeding, throw an exception if the user has not been authenticated at all 
    if (!Identity.IsAuthenticated)
    {
    throw new SecurityTokenValidationException
    (“Service Authorization can not be done for unauthenticated user.”); 
     }
     if (operationContext.Host.Authorization.RoleProvider != null)
     {
      //Get the instance of Role provider from operation context 
      //and get the roles of associated identity
     string[] roles =  operationContext.Host.Authorization.RoleProvider.GetRolesForUser
			(Identity.Name);
     // You can put your logic here to retrieve expected role based on 
     // method called or any other criteria.
     // I hardcoded the role here for simplicity
      if (roles == null || roles.Length == 0 || !roles.Contains(“MyRole”))
      {
      throw new System.ServiceModel.Security.SecurityAccessDeniedException
      (“User is not authorized. Identity : “ + Identity.Name);
      }
      }
      else
      {
      throw new System.ServiceModel.Security.SecurityAccessDeniedException
(“Service Authorization failed because role provider is missing or it is not configured properly.”);
      }
return baseResult;
}
}

构建您的项目并将 DLL 部署到 GAC。下图显示了我如何在 WCF 自定义适配器配置中配置我的 SQL 授权管理器。

关于我

我是一名集成专家,在集成领域拥有 8 年的经验。我的主要专长在于使用 Microsoft BizTalk Server、.NETWCF 等实现基于 SOAESB 的集成平台。在我的博客中,我通常会包含关于我在项目中遇到的问题以及如何解决这些问题的相关主题。


© . All rights reserved.