WCF Membership and Role Provider

本文介绍的是如何使用Membership 和 Role Provider 来控制 WCF 调用方法的权限。

比如我们有一个WCF Method 叫 GetData(int num),然后我们只允许Role = "Administrator"的用户来调用它,这就是本文要介绍的。

首先,我们先建立一个Solution,Solution里面有两个Project,一个是我们的WCF Service叫MyService,另外是一个客户端的Web Project,叫 MyClientApp, 在MyClientApp下有个Default.aspx,来调用MyService.

 

里面的MyService是默认建立的WCF Service,这里我们不介绍如何写一个简单的WCF 程序。

重要的是,在我们的方法GetData(int value)上加上这么一句话

  1. [PrincipalPermission(SecurityAction.Demand, Role = "Administrator")]

意思是我们只允许Administrator Role的用户来调用GetDate这个方法

整个的代码为

  1. [PrincipalPermission(SecurityAction.Demand, Role = "Administrator")]
  2.        public string GetData(int value)
  3.        {
  4.            return string.Format("You entered: {0}", value);
  5.        }

 

WCF Membership and Role Provider

 

当运行Default.aspx的时候,我们看到这样的结果。

WCF Membership and Role Provider

 

aspnet_regsql建立Membership 数据库。

WCF Membership and Role Provider

完成后修改MyService里面的Web.config,在这里一定看好,不是MyClientApp,而是MyService的web.config

添加如下

  1. <connectionStrings>
  2.     <add name="WCFDemoConnection"
  3.          connectionString="Data Source=localhost;Initial Catalog=WCFDemo;User ID=sa;Password=9ijn)OKM;"
  4.          providerName="Sql.Data.SqlClient" />
  5.   </connectionStrings>

 

  1. <roleManager enabled="true" defaultProvider="AspNetSqlRoleProvider" >
  2.       <providers>
  3.         <remove name="AspNetSqlRoleProvider" />
  4.         <remove name="AspNetWindowsTokenRoleProvider" />
  5.         <add connectionStringName="WCFDemoConnection"
  6.              applicationName="WCFDemo"
  7.              name="AspNetSqlRoleProvider"
  8.              type="System.Web.Security.SqlRoleProvider" />
  9.       </providers>
  10.     </roleManager>
  11.     <membership defaultProvider="AspNetSqlProvider" >
  12.       <providers>
  13.         <remove name="AspNetSqlMembershipProvider" />
  14.         <add connectionStringName="WCFDemoConnection"
  15.              applicationName="WCFDemo"
  16.              minRequiredPasswordLength="2"
  17.              minRequiredNonalphanumericCharacters="0"
  18.              requiresQuestionAndAnswer="false"
  19.              requiresUniqueEmail=" false"
  20.              name="AspNetSqlProvider"
  21.              type="System.Web.Security.SqlMembershipProvider "
  22.              enablePasswordRetrieval="true"
  23.              passwordFormat="Encrypted"
  24.              maxInvalidPasswordAttempts="20"/>
  25.       </providers>
  26.     </membership>
  27.     <machineKey validationKey="0D9EA75EE7CEF839CACB3DBAC68F420060EC381F315C2C12A80DBBBE7A8ED02079B8371B0654F11549248F58E55B5E74051DC888BA978BE1D733CF452511ECB7 " decryptionKey="BD9A8F945ACCB35EAB54542B771D34CFFE01F026A5FC5857A4253FAA20EA207F" validation="SHA1" decryption=" AES" />

 

 

 

选择MyService的Project,然后进入到ASP.NET Web Site Administration Tool的界面,在里面建立两个Role,一个Administrator,一个是User

WCF Membership and Role Provider

然后我们在建立两个User,一个是Administrator group里面的admin,密码Password,一个是User group里面的user1,密码是Password

 

WCF Membership and Role Provider

 

WCF Membership and Role Provider

在MyService\web.config,进行修改,这里我们暂时不做Certificate Check, 所以我们使用NoCheck.

  1. <behaviors>
  2.  
  3.       <serviceBehaviors>
  4.  
  5.         <behavior>
  6.           <serviceAuthorization principalPermissionMode="UseAspNetRoles" roleProviderName="AspNetSqlRoleProvider">
  7.           </serviceAuthorization>
  8.           <serviceMetadata httpGetEnabled="true" />
  9.           <serviceDebug includeExceptionDetailInFaults="false" />
  10.           <serviceCredentials>
  11.             <clientCertificate >
  12.               <authentication certificateValidationMode="PeerOrChainTrust" revocationMode="NoCheck"/>
  13.               <certificate findValue="localhost" storeLocation="LocalMachine" storeName="My" x509FindType="FindBySubjectName" />
  14.             </clientCertificate>
  15.             <serviceCertificate findValue="localhost" storeLocation="LocalMachine" storeName="My" x509FindType="FindBySubjectName" />
  16.             <userNameAuthentication userNamePasswordValidationMode="MembershipProvider"
  17.               membershipProviderName="AspNetSqlProvider" />
  18.           </serviceCredentials>
  19.         </behavior>
  20.       </serviceBehaviors>
  21.     </behaviors>

 

在MyClientApp端进,Add Reference,自动生成web.config,

进行测试,输入正确的用户名密码

  1. try
  2.            {
  3.                ServiceReference1.Service1Client client = new ServiceReference1.Service1Client();
  4.                client.ClientCredentials.ServiceCertificate.Authentication.CertificateValidationMode = System.ServiceModel.Security.X509CertificateValidationMode.None;
  5.                client.ClientCredentials.UserName.UserName = "admin";
  6.                client.ClientCredentials.UserName.Password = "Password";
  7.                Response.Write(client.GetData(5));
  8.            }
  9.            catch (Exception ex)
  10.            {
  11.                Response.Write(ex.Message);
  12.            }

 

WCF Membership and Role Provider

输入另外User group内User1,

  1. try
  2.             {
  3.                 ServiceReference1.Service1Client client = new ServiceReference1.Service1Client();
  4.                 client.ClientCredentials.ServiceCertificate.Authentication.CertificateValidationMode = System.ServiceModel.Security.X509CertificateValidationMode.None;
  5.                 client.ClientCredentials.UserName.UserName = "user1";
  6.                 client.ClientCredentials.UserName.Password = "Password";
  7.                 Response.Write(client.GetData(5));
  8.             }
  9.             catch (Exception ex)
  10.             {
  11.                 Response.Write(ex.Message);
  12.             }

 

WCF Membership and Role Provider

 

 

你可能感兴趣的:(Provider)