WCF-添加身份验证层

时间:2015-08-19 09:06:31

标签: c# wcf security authentication authorization

过去几天我一直在阅读很多关于WCF中的身份验证和授权的内容,我仍然无法确定我的方案中最好的选项:

在我们公司,我们有一个权限系统,每个需要访问新服务中任何方法的用户都需要获得该方法的特定权限。

我从活动目录中获取用户身份,然后向权限系统发送请求以检查用户是否具有该方法的特定权限。

我的问题如下: 应该在哪里执行检查?在每种方法中执行此操作似乎都是错误的。我希望在方法本身之前有一个图层,以通知我用户是否具有访问该方法所需的权限。

帮助将非常感激。

1 个答案:

答案 0 :(得分:1)

如果您想要一个用于检查授权的集中入口点,您可以创建ServiceAuthorizationManager的扩展自定义实现,并将其引用到您的WCF配置文件中。

public class MyServiceAuthorizationManager : ServiceAuthorizationManager
{
    protected override bool CheckAccessCore(OperationContext operationContext)
    {                
        // Extract the action URI from the OperationContext. Match this against the claims
        // in the AuthorizationContext.
        string action = operationContext.RequestContext.RequestMessage.Headers.Action;

        // Iterate through the various claim sets in the AuthorizationContext.
        foreach(ClaimSet cs in operationContext.ServiceSecurityContext.AuthorizationContext.ClaimSets)
        {
            // Examine only those claim sets issued by System.
            if (cs.Issuer == ClaimSet.System)
            {
                // Iterate through claims of type "http://www.contoso.com/claims/allowedoperation".
                foreach (Claim c in cs.FindClaims("http://www.contoso.com/claims/allowedoperation", Rights.PossessProperty))
                {
                    // If the Claim resource matches the action URI then return true to allow access.
                    if (action == c.Resource.ToString())
                        return true;
                }
            }
        }

      // If this point is reached, return false to deny access.
      return false;                 
    }
}

在服务配置中添加引用:

<behaviors>
  <serviceBehaviors>
    <behavior name="CalculatorServiceBehavior">
      <serviceAuthorization serviceAuthorizationManagerType="Samples.MyServiceAuthorizationManager,MyAssembly" />
     </behavior>
 </serviceBehaviors>

每次用户访问您服务器中的任何服务时,都会触发上述实现。

如果您想要额外的Authorization Policy,还可以扩展IAuthorizationPolicy。

相关问题