我一直在爲此搜索幾天。WCF .net 4.0 HTTP基本認證
我只是想使用基本HTTP身份驗證將用戶名/密碼傳遞到我的RESTful服務。其他的一切都起作用了!
這裏是我的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>
<bindings>
<wsHttpBinding>
<binding name="">
<security mode="Message">
<message clientCredentialType="UserName" />
</security>
</binding>
</wsHttpBinding>
</bindings>
<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" defaultOutgoingResponseFormat="Json" automaticFormatSelectionEnabled="true"/>
</webHttpEndpoint>
</standardEndpoints>
<behaviors>
<serviceBehaviors>
<behavior>
<serviceCredentials>
<userNameAuthentication userNamePasswordValidationMode="Custom" customUserNamePasswordValidatorType="ParkingPandaREST.CustomUserNameValidator, ParkingPandaREST" />
</serviceCredentials>
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
</configuration>
然後,我創建了一個具有以下一個CustomUserNameValidator類:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace ParkingPandaREST
{
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"))
{
// This throws an informative fault to the client.
throw new System.ServiceModel.FaultException("Unknown Username or Incorrect Password");
// When you do not want to throw an infomative fault to the client,
// throw the following exception.
// throw new SecurityTokenException("Unknown Username or Incorrect Password");
}
}
}
}
我只是在我的本地機器上運行的服務,試圖在CustomUserNameValidator類中創建一個斷點,但它永遠不會到達那裏。所以我現在不使用SSL,只是試圖讓用戶名/密碼被傳入。
相同的問題我建議使用Encoding.UTF8.GetString(encodedData),雖然 – 2011-08-03 08:27:12
你把這個代碼在哪裏? – jao 2016-09-02 09:13:37