WCF自定义角色提供程序和主要权限

时间:2012-03-09 12:18:43

标签: wcf forms-authentication roleprovider iprincipal principalpermission

编辑:我认为问题可能与下面的问题有关,因为我也在使用SSL PrincipalPermission.Demand() failing once WCF Service was moved to SSL

我正在开发一组安全的Web服务,我已经实现了CustomRoleProvider和CustomMembershipProvider以验证用户身份。

这很好用,但是如果用户未经过身份验证,我想限制对大多数服务调用的访问。

我计划使用以下内容来完成此操作

[PrincipalPermission(SecurityAction.Demand, Authenticated=true)]

但是,这似乎无法检测用户何时进行身份验证并始终抛出安全性异常。我不确定我做错了什么。

public class CustomMembershipProvider : MembershipProvider
{
    public string UserType;

    public override bool ValidateUser(string username, string password)
    {
           //Custom logic to work out if user exists and password is correct

           //If the user exists and password matches we will get a populated user
           //object containing their username and usertype

            if (user == null)
            {
                return false;
            }
            else
            {
                return true;
            }
        }
    }

在我的身份验证服务调用中,我检查成员资格提供程序是否返回true并设置表单身份验证cookie。

        if (Membership.ValidateUser(username, password))
        {
            FormsAuthentication.SetAuthCookie(username, false);
        }

我在我的网络配置中设置了服务授权,如下所示:

    <behavior name="SecureAuthServiceBehavior">
      <serviceAuthorization principalPermissionMode="UseAspNetRoles" roleProviderName="CustomRoleProvider"/>
      .... 
     </behaviour>

非常感谢任何帮助,谢谢

编辑:

我已经对这个问题做了一些进一步的调查,发现校长设置正确。  我有以下服务方法,在其中我获得了Principal并检查用户是否处于正确的角色,有效地做了开始时的标记。

[PrincipalPermission(SecurityAction.Demand,Role="A" )]
public bool DoWork()
{
    IPrincipal p = HttpContext.Current.User;
    if (p.IsInRole("A"))
    {
        return true;
    }
    else
    {
        return false;
     }
}

此方法当前每次都会抛出一个SecurityException,但是如果我在开始时注释掉了主体权限,那么该方法将起作用并返回true。

1 个答案:

答案 0 :(得分:1)

PrincipalPermission检查Thread.CurrentPrincipal,而不是HttpContext.Current.User,这就是为什么使用principalpermission属性注释掉你的DoWork()返回true,但是当该行存在时它返回false(因为没有设置Thread.CurrentPrincipal)什么)。

在我的服务类的构造函数中,我设置了Thread.CurrentPrincipal = HttpContext.Current.User,现在它们正确匹配。然后,principalpermission属性会按照您的预期阻止/允许。