基本身份验证和WCF

时间:2013-03-15 10:59:28

标签: c# wcf security

我正在努力学习WCF,但我真的不明白我必须做什么。我有一个包含用户名和密码的数据库,用户在使用该服务之前应该进行身份验证。

目前,用户名和密码是硬编码的:

class UsernameAuthentication : UserNamePasswordValidator
{
    /// <summary>
    /// When overridden in a derived class, validates the specified username and password.
    /// </summary>
    /// <param name="userName">The username to validate.</param><param name="password">The password to validate.</param>
    public override void Validate(string userName, string password)
    {
        var ok = (userName == "test") && (password == "test");
        if (ok == false)
            throw new AuthenticationException("username and password does not match");
    }
}

我的服务非常简单:

public class Service1 : IService1
{
    public int Add(int a, int b)
    {
        return a + b;
    }

    public int Subtract(int a, int b)
    {
        return a - b;
    }
}

我的问题是:我究竟需要在web.config文件中进行哪些更改才能使其正常工作?我看过一些教程,但并不真正了解所需的更改。

另外,我正在尝试做的事情 - 在用户访问服务之前对用户进行身份验证,这是正确的做法吗?

由于

编辑: 我的配置文件:

<?xml version="1.0"?>
<configuration>
  <appSettings>
    <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
  </appSettings>
  <system.web>
    <compilation debug="true" targetFramework="4.5" />
    <httpRuntime targetFramework="4.5"/>
  </system.web>
  <system.serviceModel>
    <bindings>
      <wsHttpBinding>
        <binding name="Binding1">
          <security mode="Message">
            <message clientCredentialType="UserName" />
          </security>
        </binding>
      </wsHttpBinding>
    </bindings>
    <behaviors>
      <serviceBehaviors>
        <behavior>
          <serviceCredentials>
            <userNameAuthentication userNamePasswordValidationMode="Custom" customUserNamePasswordValidatorType="WcfService1.UsernameAuthentication, service1" />
          </serviceCredentials>
          <!-- To avoid disclosing metadata information, set the values below to false before deployment -->
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
          <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
          <serviceDebug includeExceptionDetailInFaults="false"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <protocolMapping>
        <add binding="basicHttpsBinding" scheme="https" />
    </protocolMapping>    
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
  </system.serviceModel>
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
    <!--
        To browse web app root directory during debugging, set the value below to true.
        Set to false before deployment to avoid disclosing web app folder information.
      -->
    <directoryBrowse enabled="true"/>
  </system.webServer>
</configuration>

错误:无法激活service1.svc。

1 个答案:

答案 0 :(得分:4)

您必须在web.config中指定您将使用用户名/密码凭据并使用自定义密码验证程序。

您的服务绑定应设置一种安全类型(TransportMessage,最适合您的安全类型),对于该类型的安全性,您必须设置要使用的凭据(用户名)和密码)。

<system.serviceModel> 
  <bindings>
  <wsHttpBinding>
      <binding name="Binding1" ...>
        <security mode="Message">
          <message clientCredentialType="UserName" />
        </security>
      </binding>        
    </wsHttpBinding>
  </bindings>
</system.serviceModel>

其中...表示特定于您服务的许多其他设置。

请注意,只有某些类型的绑定和安全模式支持此类凭据,但MSDN会提供您可能需要的所有信息。

如果您未将凭据设置为用户名和密码,则不会以这种方式对用户进行身份验证。

要告诉服务使用您的密码验证程序,您需要添加以下内容:

<behaviors>
      <serviceBehaviors>
        <behavior name="ServiceBehavior">
            <serviceCredentials>
              <userNameAuthentication userNamePasswordValidationMode="Custom" customUserNamePasswordValidatorType="Microsoft.ServiceModel.Samples.CalculatorService.CustomUserNameValidator, service" />
            </serviceCredentials>
         .....
         </serviceBehaviors>
</behaviors> 

其中Microsoft.ServiceModel.Samples.CalculatorService是您拥有自定义验证程序的命名空间,CustomUserNameValidator是自定义验证程序(在您的情况下为UserNamePasswordValidator),而service是其名称服务。

否则,该服务将需要一个默认验证器,如ASP.NET成员资格提供程序。

必须将服务凭证放入您的服务行为中。

另外,不要忘记将行为链接到服务定义。

<services>
  <service behaviorConfiguration="ServiceBehavior" name="ServiceName">
    <endpoint address="" binding="basicHttpBinding" bindingConfiguration="Binding1" contract="ContractName" />
     ....
  </service>
</services>

注意:web.config中还有很多我没有显示的设置。元素的名称只是方向性的。这只是为了使用户名凭据有效。

您可以查看MSDN,因为它们有很多很棒的教程,例如http://msdn.microsoft.com/en-us/library/aa702565.aspxhttp://msdn.microsoft.com/en-us/library/aa354513.aspx

是的,实际上如果你以正确的方式配置它,它将在给予客户运行服务方法的权限之前验证客户端(用户,客户端服务)。