如何在WCF服务中使用角色管理器?

Cod*_*ody 13 c# wcf

如何在WCF服务中使用角色管理器?

在我的.NET应用程序中,我可以使用[Authorize(Roles=)]标记限制类或方法.如何为我的WCF服务启用此功能?

我目前为每个端点设置了以下绑定:

  <webHttpBinding>
    <binding name="TransportSecurity" maxReceivedMessageSize="5242880">
      <security mode="Transport">
        <transport clientCredentialType="None"/>
      </security>
    </binding>
  </webHttpBinding>
Run Code Online (Sandbox Code Playgroud)

由于我希望用户登录并接收带有主体的cookie,我是否需要将其更改为另一种clientCredentialType

编辑1:

这是使用REST,而不是SOAP.还需要注意的是,它适用于移动设备(Android,iPhone)并且可以使用cookie来维护会话.到目前为止,我一直无法使用以下代码/配置工作:

配置文件:

   <roleManager enabled="true" defaultProvider="ActiveDirectoryRoleProvider" cacheRolesInCookie="true" cookieName="RoleCookie" cookiePath="/" cookieTimeout="30" cookieRequireSSL="false" cookieSlidingExpiration="true" createPersistentCookie="false" cookieProtection="All">
      <providers>
        <clear />
        <add name="ActiveDirectoryRoleProvider" connectionStringName="ADServices" connectionUsername="" connectionPassword="" attributeMapUsername="sAMAccountName" type="" />
      </providers>
    </roleManager>

    <membership defaultProvider="MembershipADProvider">
      <providers>
        <add name="MembershipADProvider" type="System.Web.Security.ActiveDirectoryMembershipProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" applicationName="" connectionStringName="ADServices" connectionUsername="" connectionPassword="" attributeMapUsername="sAMAccountName" />
      </providers>
    </membership>

<bindings>
  <webHttpBinding> <!-- webHttpBinding is for REST -->
    <binding name="TransportSecurity" maxReceivedMessageSize="5242880">
      <security mode="Transport">
      </security>
    </binding>
  </webHttpBinding>
</bindings>

<behaviors>
  <endpointBehaviors>
    <behavior name="web">
      <webHttp />
    </behavior>
  </endpointBehaviors>
  <serviceBehaviors>
    <behavior name="ServiceBehaviour">
      <serviceMetadata httpGetEnabled="false" httpsGetEnabled="true" />
      <serviceDebug httpHelpPageEnabled="true" includeExceptionDetailInFaults="true" />
      <serviceAuthorization principalPermissionMode="UseAspNetRoles" roleProviderName="ActiveDirectoryRoleProvider" />
      <serviceCredentials>
        <userNameAuthentication userNamePasswordValidationMode="MembershipProvider" membershipProviderName="MembershipADProvider" />
      </serviceCredentials>
    </behavior>
  </serviceBehaviors>
</behaviors>
Run Code Online (Sandbox Code Playgroud)

    public void SignIn2(string userName, bool createPersistentCookie)
    {
        if (String.IsNullOrEmpty(userName)) throw new ArgumentException("Value cannot be null or empty.", "userName");

        // put the attributes in a string for userdata
        string userData = "";

        // create the ticket
        FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(1,
                                                userName,
                                                DateTime.Now,
                                                DateTime.Now.AddMinutes(240),
                                                createPersistentCookie,
                                                userData);

        // Now encrypt the ticket.
        string encryptedTicket = FormsAuthentication.Encrypt(authTicket);

        // Create a cookie and add the encrypted ticket to the cookie as data.
        HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);

        // add the cookie
        HttpContext.Current.Response.Cookies.Add(authCookie);
    }
Run Code Online (Sandbox Code Playgroud)

现在使用Principal Permission,我得到一个SecurityException(我知道该角色在服务器上有效)

    [PrincipalPermission(SecurityAction.Demand, Role = Constants.RoleUser)]
    public Message TestRoles()
    {
        var context = NetworkHelper.GetWebOperationContext();

        return context.CreateTextResponse("You have successfully activated the endpoint.");
    }
Run Code Online (Sandbox Code Playgroud)

我错过了关键的一步吗?

Pau*_*ter 9

我写了一篇关于如何在WCF中使用ASP.NET身份验证的博客文章 ; 它的要点是你想使用以下绑定:

  <basicHttpBinding>
    <binding>
      <security mode="TransportWithMessageCredential">
        <message clientCredentialType="UserName"/>
      </security>
    </binding>
  </basicHttpBinding>
Run Code Online (Sandbox Code Playgroud)

您还必须应用以下内容 serviceBehavior

    <behavior>
      <!-- no need for http get;
          but https get exposes endpoint over SSL/TLS-->
      <serviceMetadata httpGetEnabled="false" httpsGetEnabled="true"/>
      <!-- the authorization and credentials elements tie
        this behavior (defined as the default behavior) to
        the ASP.NET membership framework-->
      <serviceAuthorization
          principalPermissionMode="UseAspNetRoles"
          roleProviderName="AspNetRoleProvider" />
      <serviceCredentials>
        <userNameAuthentication
            userNamePasswordValidationMode="MembershipProvider"
            membershipProviderName="AspNetMembershipProvider" />
      </serviceCredentials>
    </behavior>
Run Code Online (Sandbox Code Playgroud)

需要注意的一点是,如果要使用名称和密码保护WCF,则必须使用SSL,这就是指定传输安全性的原因.

完成此操作后,您应该能够使用该PrincipalPermission属性来保护您的服务方法.