1

我正在尝试使用 Visual Studio 2010 将 UserNamePasswordValidator 添加到“WCF Rest Service Application”项目,问题是..它永远不会进入 UserNamePasswordValidator 类,UserNamePasswordValidator 是否与 Wcf Rest 一起使用?

好心提醒..

以下是我的服务类:

using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;
using System.Text;
using System.Security.Principal;


namespace MyService
{
    // Start the service and browse to http://<machine_name>:<port>/Service1/help to view the service's generated help page
    // NOTE: By default, a new instance of the service is created for each call; change the InstanceContextMode to Single if you want
    // a single instance of the service to process all calls.   
    [ServiceContract(Namespace = "MyService")]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
    // NOTE: If the service is renamed, remember to update the global.asax.cs file
    public class Helo
    {
        [WebGet(UriTemplate = "{name}")]
        public string GetName(string name)
        {
            // TODO: Replace the current implementation to return a collection of SampleItem instances
            return "Hello " + name;
        }

        public class CustomUserNameValidator : System.IdentityModel.Selectors.UserNamePasswordValidator
        {
            // This method validates users. It allows in two users, test1 and test2 
            // with passwords 1tset and 2tset respectively.
            // This code is for illustration purposes only and 
            // MUST NOT be used in a production environment because it is NOT secure.   
            public override void Validate(string userName, string password)
            {
                if (null == userName || null == password)
                {
                    throw new ArgumentNullException();
                }

                if (!(userName == "test1" && password == "1tset") && !(userName == "test2" && password == "2tset"))
                {
                    throw new FaultException("Unknown Username or Incorrect Password");
                }

                throw new FaultException("Unknown Username or Incorrect Password");
            }
        }
    }
}

下面是web.config:

<?xml version="1.0"?>
<configuration>

  <system.web>
    <compilation debug="true" targetFramework="4.0" />
  </system.web>

  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true">
      <add name="UrlRoutingModule" type="System.Web.Routing.UrlRoutingModule, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
    </modules>
  </system.webServer>

  <system.serviceModel>

    <services>
      <service name="MyService.Hello" behaviorConfiguration="HelloServiceBehavior">
        <!-- use base address provided by host, provide one endpoint -->
        <endpoint address="username" binding="wsHttpBinding" bindingConfiguration="Binding1" contract="MyService.Hello"/>
      </service>
    </services>

    <bindings>
      <wsHttpBinding>
        <!-- Username binding -->
        <binding name="Binding1">
          <security mode="Message">
            <message clientCredentialType="UserName"/>
          </security>
        </binding>
      </wsHttpBinding>
    </bindings>

    <behaviors>
      <serviceBehaviors>
        <behavior name="HelloServiceBehavior">
          <serviceCredentials>
            <!-- 
            The serviceCredentials behavior allows one to specify a custom validator for username/password combinations.                  
            -->
            <userNameAuthentication userNamePasswordValidationMode="Custom" customUserNamePasswordValidatorType="MyService.Hello+CustomUserNameValidator, MyService"/>
          </serviceCredentials>
        </behavior>
      </serviceBehaviors>
    </behaviors>


    <serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
    <!--<standardEndpoints>
      <webHttpEndpoint>
        --><!-- 
            Configure the WCF REST service base address via the global.asax.cs file and the default endpoint 
            via the attributes on the <standardEndpoint> element below
        --><!--
        <standardEndpoint name="" helpEnabled="true" automaticFormatSelectionEnabled="true"/>
      </webHttpEndpoint>
    </standardEndpoints>-->
  </system.serviceModel>

</configuration>
4

2 回答 2

1

您必须有一个 webHttpBinding 并将 clientCredentialType 设置为 basic,这将使用您派生的 UserNamePasswordValidator。如果您有 HTTPS 设置,那么当然将安全模式更改为传输:

        <bindings>
        <webHttpBinding>
            <binding name="RestBindingConfiguration">
                <security mode="None">
                    <transport clientCredentialType="Basic"/>
                </security>
            </binding>
        </webHttpBinding>
        </bindings>

在相关的旁注中,FaultExceptions 只是 SOAP,因此请注意,以防您需要为客户端引发异常。根据例外情况,MessageSecurityException 可能有意义。

于 2013-03-15T12:52:28.063 回答
0

我不确定您是否仍在为此寻找答案,但如果您...

在 WCF REST 上设置身份验证有点棘手。好像您直接从msdn模拟了您的尝试,amirite?我也没有太多运气。您可以尝试在解决方案之后进行建模,这是基本身份验证的一个非常基本的示例。但我的建议是,因为它对我来说效果很好,所以在WcfRestContrib之后为您的项目建模。不仅基本身份验证已经内置到项目中,而且您最终会发现您想要的许多其他功能也在那里。您可以对整个服务强制执行身份验证,也可以逐个端点强制执行身份验证。

希望有帮助。

于 2011-07-15T15:07:14.823 回答