基本身份验证和 WCF [英] Basic authentication and WCF

查看:76
本文介绍了基本身份验证和 WCF的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to learn WCF, but I don't really understand what I have to do. 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");
    }
}

我的服务很简单:

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 文件中更改什么才能使其正常工作?我看过一些教程,但并不真正了解所需的更改..

My question is: what exactly do I have to change in the web.config file to make this work? 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?

谢谢

我的配置文件:

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

Error: service1.svc cannot be activated.

推荐答案

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

You have to specify in the web.config that you will use username/password credentials and that you use a custom password validator.

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

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).

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

考虑到只有某些类型的绑定和安全模式支持此类凭据,但 MSDN 拥有您可能需要的所有信息.

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.

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

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

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> 

其中 Microsoft.ServiceModel.Samples.CalculatorService 是自定义验证器所在的命名空间,CustomUserNameValidator 是自定义验证器 (UserNamePasswordValidator在您的情况下),并且 service 是服务的名称.

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.

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

Otherwise, the service would expect a default validator, like the 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>

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

NOTE: There are many more settings in the web.config that I didn't show. Names of elements are only orientative. This is just for making username credentials work.

你可以查看 MSDN,因为他们有很多很棒的教程,比如这个 http://msdn.microsoft.com/en-us/library/aa702565.aspx, http://msdn.microsoft.com/en-us/library/aa354513.aspx.

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.

是的,事实上,如果您以正确的方式配置它,它将在授予客户端(用户、客户端服务)运行服务方法的权限之前对其进行身份验证.

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.

这篇关于基本身份验证和 WCF的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆