简体   繁体   English

基本身份验证和WCF

[英]Basic authentication and WCF

I'm trying to learn WCF, but I don't really understand what I have to do. 我正在尝试学习WCF,但是我真的不明白我该怎么做。 I have a database with usernames and passwords and the user should authenticate before he may use the service. 我有一个包含用户名和密码的数据库,用户在使用该服务之前应先进行身份验证。

For now, the username and password is hardcoded: 现在,用户名和密码已进行硬编码:

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");
    }
}

My service is very simple: 我的服务很简单:

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

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

My question is: what exactly do I have to change in the web.config file to make this work? 我的问题是:为了使这项工作有效,我到底需要在web.config文件中进行哪些更改? I've looked at some tutorials, but don't really understand the needed changes.. 我看过一些教程,但是并不太了解所需的更改。

Also, what I'm trying to do - authenticate a user before he may access the service, is this the correct way of doing it? 另外,我正在尝试做的-在用户访问服务之前对其进行身份验证,这是正确的方法吗?

Thanks 谢谢

EDIT: My config file: 编辑:我的配置文件:

<?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>

Error: service1.svc cannot be activated. 错误:service1.svc无法激活。

You have to specify in the web.config that you will use username/password credentials and that you use a custom password validator. 您必须在web.config中指定将使用用户名/密码凭据,并使用自定义密码验证器。

The binding of your service should have set a type of security ( Transport or Message , what suits you best) and for that type of security you must set the credentials you want to use (username and password). 服务的绑定应设置一种安全性类型(“ Transport或“ Message ,最适合您),对于这种安全性,必须设置要使用的凭据(用户名和密码)。

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

Where ... means many other settings specific to your service. 其中...表示您的服务特有的许多其他设置。

Take into account that only certain types of bindings and security modes support this type of credentials, but MSDN has all the information you may need. 考虑到只有某些类型的绑定和安全模式支持这种类型的凭据,但是MSDN拥有您可能需要的所有信息。

If you do not set the credentials to username and password, you won't authenticate users this way. 如果未将凭据设置为用户名和密码,则不会以这种方式对用户进行身份验证。

To tell the service to use your password validator you need to add something like this: 要告诉服务使用您的密码验证器,您需要添加以下内容:

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

Where Microsoft.ServiceModel.Samples.CalculatorService is the namespace under which you have the custom validator, CustomUserNameValidator is teh custom validator ( UserNamePasswordValidator in your case), and service is the name of the service. 其中Microsoft.ServiceModel.Samples.CalculatorService是您具有自定义验证器的名称空间, CustomUserNameValidator是自定义验证器(在您的情况下为UserNamePasswordValidator ),而serviceservice的名称。

Otherwise, the service would expect a default validator, like the ASP.NET Membership Provider. 否则,该服务将需要一个默认验证器,例如ASP.NET Membership Provider。

The service credentials must be put in your service behaviour. 服务凭证必须放在您的服务行为中。

Also, don't forget to link the behaviour to the service definition. 另外,不要忘记将行为链接到服务定义。

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

NOTE : There are many more settings in the web.config that I didn't show. 注意 :web.config中还有许多未显示的设置。 Names of elements are only orientative. 元素的名称仅是定向的。 This is just for making username credentials work. 这只是为了使用户名凭据起作用。

You may check MSDN because they have many great tutorials on this, like this one http://msdn.microsoft.com/en-us/library/aa702565.aspx , http://msdn.microsoft.com/en-us/library/aa354513.aspx . 您可以查看MSDN,因为他们对此有很多伟大的教程,像这样一个http://msdn.microsoft.com/en-us/library/aa702565.aspxhttp://msdn.microsoft.com/en-us/ library / aa354513.aspx

And yes, in fact if you configure this in the right way, it will authenticate clients (users, client services) before given them permission to run the service methods. 是的,实际上,如果您以正确的方式进行配置,它将在授予客户端(用户,客户端服务)运行服务方法权限之前对其进行身份验证。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM